Remove functions deprecated since 1.21 from EditPage.php
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui.js
blob1c2dfc963f5a72dd51d0f216aebfc8cf4c11285d
1 /*!
2 * OOjs UI v0.1.0-pre (e9cf571db2)
3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2014-07-28T21:48:00Z
11 ( function ( OO ) {
13 'use strict';
15 /**
16 * Namespace for all classes, static methods and static properties.
18 * @class
19 * @singleton
21 OO.ui = {};
23 OO.ui.bind = $.proxy;
25 /**
26 * @property {Object}
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
47 /**
48 * Get the user's language and any fallback languages.
50 * These language codes are used to localize user interface elements in the user's language.
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.
55 * @return {string[]} Language codes, in descending order of priority
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
61 /**
62 * Get a value in an object keyed by language code.
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
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
72 // Requested language
73 if ( obj[lang] ) {
74 return obj[lang];
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];
84 // Fallback language
85 if ( obj[fallback] ) {
86 return obj[fallback];
88 // First existing language
89 for ( lang in obj ) {
90 return obj[lang];
93 return undefined;
96 ( function () {
97 /**
98 * Message store for the default implementation of OO.ui.msg
100 * Environments that provide a localization system should not use this, but should override
101 * OO.ui.msg altogether.
103 * @private
105 var messages = {
106 // Tool tip for a button that moves items in a list down one place
107 'ooui-outline-control-move-down': 'Move item down',
108 // Tool tip for a button that moves items in a list up one place
109 'ooui-outline-control-move-up': 'Move item up',
110 // Tool tip for a button that removes items from a list
111 'ooui-outline-control-remove': 'Remove item',
112 // Label for the toolbar group that contains a list of all other available tools
113 'ooui-toolbar-more': 'More',
114 // Default label for the accept button of a confirmation dialog
115 'ooui-dialog-message-accept': 'OK',
116 // Default label for the reject button of a confirmation dialog
117 'ooui-dialog-message-reject': 'Cancel',
118 // Title for process dialog error description
119 'ooui-dialog-process-error': 'Something went wrong',
120 // Label for process dialog dismiss error button, visible when describing errors
121 'ooui-dialog-process-dismiss': 'Dismiss',
122 // Label for process dialog retry action button, visible when describing recoverable errors
123 'ooui-dialog-process-retry': 'Try again'
127 * Get a localized message.
129 * In environments that provide a localization system, this function should be overridden to
130 * return the message translated in the user's language. The default implementation always returns
131 * English messages.
133 * After the message key, message parameters may optionally be passed. In the default implementation,
134 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
135 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
136 * they support unnamed, ordered message parameters.
138 * @abstract
139 * @param {string} key Message key
140 * @param {Mixed...} [params] Message parameters
141 * @return {string} Translated message with parameters substituted
143 OO.ui.msg = function ( key ) {
144 var message = messages[key], params = Array.prototype.slice.call( arguments, 1 );
145 if ( typeof message === 'string' ) {
146 // Perform $1 substitution
147 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
148 var i = parseInt( n, 10 );
149 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
150 } );
151 } else {
152 // Return placeholder if message not found
153 message = '[' + key + ']';
155 return message;
159 * Package a message and arguments for deferred resolution.
161 * Use this when you are statically specifying a message and the message may not yet be present.
163 * @param {string} key Message key
164 * @param {Mixed...} [params] Message parameters
165 * @return {Function} Function that returns the resolved message when executed
167 OO.ui.deferMsg = function () {
168 var args = arguments;
169 return function () {
170 return OO.ui.msg.apply( OO.ui, args );
175 * Resolve a message.
177 * If the message is a function it will be executed, otherwise it will pass through directly.
179 * @param {Function|string} msg Deferred message, or message text
180 * @return {string} Resolved message
182 OO.ui.resolveMsg = function ( msg ) {
183 if ( $.isFunction( msg ) ) {
184 return msg();
186 return msg;
189 } )();
192 * List of actions.
194 * @abstract
195 * @class
196 * @mixins OO.EventEmitter
198 * @constructor
199 * @param {Object} [config] Configuration options
201 OO.ui.ActionSet = function OoUiActionSet( config ) {
202 // Configuration intialization
203 config = config || {};
205 // Mixin constructors
206 OO.EventEmitter.call( this );
208 // Properties
209 this.list = [];
210 this.categories = {
211 actions: 'getAction',
212 flags: 'getFlags',
213 modes: 'getModes'
215 this.categorized = {};
216 this.special = {};
217 this.others = [];
218 this.organized = false;
219 this.changing = false;
220 this.changed = false;
223 /* Setup */
225 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
227 /* Static Properties */
230 * Symbolic name of dialog.
232 * @abstract
233 * @static
234 * @inheritable
235 * @property {string}
237 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
239 /* Events */
242 * @event click
243 * @param {OO.ui.ActionWidget} action Action that was clicked
247 * @event resize
248 * @param {OO.ui.ActionWidget} action Action that was resized
252 * @event add
253 * @param {OO.ui.ActionWidget[]} added Actions added
257 * @event remove
258 * @param {OO.ui.ActionWidget[]} added Actions removed
262 * @event change
265 /* Methods */
268 * Handle action change events.
270 * @fires change
272 OO.ui.ActionSet.prototype.onActionChange = function () {
273 this.organized = false;
274 if ( this.changing ) {
275 this.changed = true;
276 } else {
277 this.emit( 'change' );
282 * Check if a action is one of the special actions.
284 * @param {OO.ui.ActionWidget} action Action to check
285 * @return {boolean} Action is special
287 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
288 var flag;
290 for ( flag in this.special ) {
291 if ( action === this.special[flag] ) {
292 return true;
296 return false;
300 * Get actions.
302 * @param {Object} [filters] Filters to use, omit to get all actions
303 * @param {string|string[]} [filters.actions] Actions that actions must have
304 * @param {string|string[]} [filters.flags] Flags that actions must have
305 * @param {string|string[]} [filters.modes] Modes that actions must have
306 * @param {boolean} [filters.visible] Actions must be visible
307 * @param {boolean} [filters.disabled] Actions must be disabled
308 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
310 OO.ui.ActionSet.prototype.get = function ( filters ) {
311 var i, len, list, category, actions, index, match, matches;
313 if ( filters ) {
314 this.organize();
316 // Collect category candidates
317 matches = [];
318 for ( category in this.categorized ) {
319 list = filters[category];
320 if ( list ) {
321 if ( !Array.isArray( list ) ) {
322 list = [ list ];
324 for ( i = 0, len = list.length; i < len; i++ ) {
325 actions = this.categorized[category][list[i]];
326 if ( Array.isArray( actions ) ) {
327 matches.push.apply( matches, actions );
332 // Remove by boolean filters
333 for ( i = 0, len = matches.length; i < len; i++ ) {
334 match = matches[i];
335 if (
336 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
337 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
339 matches.splice( i, 1 );
340 len--;
341 i--;
344 // Remove duplicates
345 for ( i = 0, len = matches.length; i < len; i++ ) {
346 match = matches[i];
347 index = matches.lastIndexOf( match );
348 while ( index !== i ) {
349 matches.splice( index, 1 );
350 len--;
351 index = matches.lastIndexOf( match );
354 return matches;
356 return this.list.slice();
360 * Get special actions.
362 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
363 * Special flags can be configured by changing #static-specialFlags in a subclass.
365 * @return {OO.ui.ActionWidget|null} Safe action
367 OO.ui.ActionSet.prototype.getSpecial = function () {
368 this.organize();
369 return $.extend( {}, this.special );
373 * Get other actions.
375 * Other actions include all non-special visible actions.
377 * @return {OO.ui.ActionWidget[]} Other actions
379 OO.ui.ActionSet.prototype.getOthers = function () {
380 this.organize();
381 return this.others.slice();
385 * Toggle actions based on their modes.
387 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
388 * visibility; matching actions will be shown, non-matching actions will be hidden.
390 * @param {string} mode Mode actions must have
391 * @chainable
392 * @fires toggle
393 * @fires change
395 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
396 var i, len, action;
398 this.changing = true;
399 for ( i = 0, len = this.list.length; i < len; i++ ) {
400 action = this.list[i];
401 action.toggle( action.hasMode( mode ) );
404 this.organized = false;
405 this.changing = false;
406 this.emit( 'change' );
408 return this;
412 * Change which actions are able to be performed.
414 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
416 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
417 * indicate actions are able to be performed
418 * @chainable
420 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
421 var i, len, action, item;
423 for ( i = 0, len = this.list.length; i < len; i++ ) {
424 item = this.list[i];
425 action = item.getAction();
426 if ( actions[action] !== undefined ) {
427 item.setDisabled( !actions[action] );
431 return this;
435 * Executes a function once per action.
437 * When making changes to multiple actions, use this method instead of iterating over the actions
438 * manually to defer emitting a change event until after all actions have been changed.
440 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
441 * @param {Function} callback Callback to run for each action; callback is invoked with three
442 * arguments: the action, the action's index, the list of actions being iterated over
443 * @chainable
445 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
446 this.changed = false;
447 this.changing = true;
448 this.get( filter ).forEach( callback );
449 this.changing = false;
450 if ( this.changed ) {
451 this.emit( 'change' );
454 return this;
458 * Add actions.
460 * @param {OO.ui.ActionWidget[]} actions Actions to add
461 * @chainable
462 * @fires add
463 * @fires change
465 OO.ui.ActionSet.prototype.add = function ( actions ) {
466 var i, len, action;
468 this.changing = true;
469 for ( i = 0, len = actions.length; i < len; i++ ) {
470 action = actions[i];
471 action.connect( this, {
472 click: [ 'emit', 'click', action ],
473 resize: [ 'emit', 'resize', action ],
474 toggle: [ 'onActionChange' ]
475 } );
476 this.list.push( action );
478 this.organized = false;
479 this.emit( 'add', actions );
480 this.changing = false;
481 this.emit( 'change' );
483 return this;
487 * Remove actions.
489 * @param {OO.ui.ActionWidget[]} actions Actions to remove
490 * @chainable
491 * @fires remove
492 * @fires change
494 OO.ui.ActionSet.prototype.remove = function ( actions ) {
495 var i, len, index, action;
497 this.changing = true;
498 for ( i = 0, len = actions.length; i < len; i++ ) {
499 action = actions[i];
500 index = this.list.indexOf( action );
501 if ( index !== -1 ) {
502 action.disconnect( this );
503 this.list.splice( index, 1 );
506 this.organized = false;
507 this.emit( 'remove', actions );
508 this.changing = false;
509 this.emit( 'change' );
511 return this;
515 * Remove all actions.
517 * @chainable
518 * @fires remove
519 * @fires change
521 OO.ui.ActionSet.prototype.clear = function () {
522 var i, len, action,
523 removed = this.list.slice();
525 this.changing = true;
526 for ( i = 0, len = this.list.length; i < len; i++ ) {
527 action = this.list[i];
528 action.disconnect( this );
531 this.list = [];
533 this.organized = false;
534 this.emit( 'remove', removed );
535 this.changing = false;
536 this.emit( 'change' );
538 return this;
542 * Organize actions.
544 * This is called whenver organized information is requested. It will only reorganize the actions
545 * if something has changed since the last time it ran.
547 * @private
548 * @chainable
550 OO.ui.ActionSet.prototype.organize = function () {
551 var i, iLen, j, jLen, flag, action, category, list, item, special,
552 specialFlags = this.constructor.static.specialFlags;
554 if ( !this.organized ) {
555 this.categorized = {};
556 this.special = {};
557 this.others = [];
558 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
559 action = this.list[i];
560 if ( action.isVisible() ) {
561 // Populate catgeories
562 for ( category in this.categories ) {
563 if ( !this.categorized[category] ) {
564 this.categorized[category] = {};
566 list = action[this.categories[category]]();
567 if ( !Array.isArray( list ) ) {
568 list = [ list ];
570 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
571 item = list[j];
572 if ( !this.categorized[category][item] ) {
573 this.categorized[category][item] = [];
575 this.categorized[category][item].push( action );
578 // Populate special/others
579 special = false;
580 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
581 flag = specialFlags[j];
582 if ( !this.special[flag] && action.hasFlag( flag ) ) {
583 this.special[flag] = action;
584 special = true;
585 break;
588 if ( !special ) {
589 this.others.push( action );
593 this.organized = true;
596 return this;
600 * DOM element abstraction.
602 * @abstract
603 * @class
605 * @constructor
606 * @param {Object} [config] Configuration options
607 * @cfg {Function} [$] jQuery for the frame the widget is in
608 * @cfg {string[]} [classes] CSS class names
609 * @cfg {string} [text] Text to insert
610 * @cfg {jQuery} [$content] Content elements to append (after text)
612 OO.ui.Element = function OoUiElement( config ) {
613 // Configuration initialization
614 config = config || {};
616 // Properties
617 this.$ = config.$ || OO.ui.Element.getJQuery( document );
618 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
619 this.elementGroup = null;
621 // Initialization
622 if ( $.isArray( config.classes ) ) {
623 this.$element.addClass( config.classes.join( ' ' ) );
625 if ( config.text ) {
626 this.$element.text( config.text );
628 if ( config.$content ) {
629 this.$element.append( config.$content );
633 /* Setup */
635 OO.initClass( OO.ui.Element );
637 /* Static Properties */
640 * HTML tag name.
642 * This may be ignored if getTagName is overridden.
644 * @static
645 * @inheritable
646 * @property {string}
648 OO.ui.Element.static.tagName = 'div';
650 /* Static Methods */
653 * Get a jQuery function within a specific document.
655 * @static
656 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
657 * @param {OO.ui.Frame} [frame] Frame of the document context
658 * @return {Function} Bound jQuery function
660 OO.ui.Element.getJQuery = function ( context, frame ) {
661 function wrapper( selector ) {
662 return $( selector, wrapper.context );
665 wrapper.context = this.getDocument( context );
667 if ( frame ) {
668 wrapper.frame = frame;
671 return wrapper;
675 * Get the document of an element.
677 * @static
678 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
679 * @return {HTMLDocument|null} Document object
681 OO.ui.Element.getDocument = function ( obj ) {
682 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
683 return ( obj[0] && obj[0].ownerDocument ) ||
684 // Empty jQuery selections might have a context
685 obj.context ||
686 // HTMLElement
687 obj.ownerDocument ||
688 // Window
689 obj.document ||
690 // HTMLDocument
691 ( obj.nodeType === 9 && obj ) ||
692 null;
696 * Get the window of an element or document.
698 * @static
699 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
700 * @return {Window} Window object
702 OO.ui.Element.getWindow = function ( obj ) {
703 var doc = this.getDocument( obj );
704 return doc.parentWindow || doc.defaultView;
708 * Get the direction of an element or document.
710 * @static
711 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
712 * @return {string} Text direction, either `ltr` or `rtl`
714 OO.ui.Element.getDir = function ( obj ) {
715 var isDoc, isWin;
717 if ( obj instanceof jQuery ) {
718 obj = obj[0];
720 isDoc = obj.nodeType === 9;
721 isWin = obj.document !== undefined;
722 if ( isDoc || isWin ) {
723 if ( isWin ) {
724 obj = obj.document;
726 obj = obj.body;
728 return $( obj ).css( 'direction' );
732 * Get the offset between two frames.
734 * TODO: Make this function not use recursion.
736 * @static
737 * @param {Window} from Window of the child frame
738 * @param {Window} [to=window] Window of the parent frame
739 * @param {Object} [offset] Offset to start with, used internally
740 * @return {Object} Offset object, containing left and top properties
742 OO.ui.Element.getFrameOffset = function ( from, to, offset ) {
743 var i, len, frames, frame, rect;
745 if ( !to ) {
746 to = window;
748 if ( !offset ) {
749 offset = { top: 0, left: 0 };
751 if ( from.parent === from ) {
752 return offset;
755 // Get iframe element
756 frames = from.parent.document.getElementsByTagName( 'iframe' );
757 for ( i = 0, len = frames.length; i < len; i++ ) {
758 if ( frames[i].contentWindow === from ) {
759 frame = frames[i];
760 break;
764 // Recursively accumulate offset values
765 if ( frame ) {
766 rect = frame.getBoundingClientRect();
767 offset.left += rect.left;
768 offset.top += rect.top;
769 if ( from !== to ) {
770 this.getFrameOffset( from.parent, offset );
773 return offset;
777 * Get the offset between two elements.
779 * @static
780 * @param {jQuery} $from
781 * @param {jQuery} $to
782 * @return {Object} Translated position coordinates, containing top and left properties
784 OO.ui.Element.getRelativePosition = function ( $from, $to ) {
785 var from = $from.offset(),
786 to = $to.offset();
787 return { top: Math.round( from.top - to.top ), left: Math.round( from.left - to.left ) };
791 * Get element border sizes.
793 * @static
794 * @param {HTMLElement} el Element to measure
795 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
797 OO.ui.Element.getBorders = function ( el ) {
798 var doc = el.ownerDocument,
799 win = doc.parentWindow || doc.defaultView,
800 style = win && win.getComputedStyle ?
801 win.getComputedStyle( el, null ) :
802 el.currentStyle,
803 $el = $( el ),
804 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
805 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
806 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
807 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
809 return {
810 top: Math.round( top ),
811 left: Math.round( left ),
812 bottom: Math.round( bottom ),
813 right: Math.round( right )
818 * Get dimensions of an element or window.
820 * @static
821 * @param {HTMLElement|Window} el Element to measure
822 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
824 OO.ui.Element.getDimensions = function ( el ) {
825 var $el, $win,
826 doc = el.ownerDocument || el.document,
827 win = doc.parentWindow || doc.defaultView;
829 if ( win === el || el === doc.documentElement ) {
830 $win = $( win );
831 return {
832 borders: { top: 0, left: 0, bottom: 0, right: 0 },
833 scroll: {
834 top: $win.scrollTop(),
835 left: $win.scrollLeft()
837 scrollbar: { right: 0, bottom: 0 },
838 rect: {
839 top: 0,
840 left: 0,
841 bottom: $win.innerHeight(),
842 right: $win.innerWidth()
845 } else {
846 $el = $( el );
847 return {
848 borders: this.getBorders( el ),
849 scroll: {
850 top: $el.scrollTop(),
851 left: $el.scrollLeft()
853 scrollbar: {
854 right: $el.innerWidth() - el.clientWidth,
855 bottom: $el.innerHeight() - el.clientHeight
857 rect: el.getBoundingClientRect()
863 * Get closest scrollable container.
865 * Traverses up until either a scrollable element or the root is reached, in which case the window
866 * will be returned.
868 * @static
869 * @param {HTMLElement} el Element to find scrollable container for
870 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
871 * @return {HTMLElement|Window} Closest scrollable container
873 OO.ui.Element.getClosestScrollableContainer = function ( el, dimension ) {
874 var i, val,
875 props = [ 'overflow' ],
876 $parent = $( el ).parent();
878 if ( dimension === 'x' || dimension === 'y' ) {
879 props.push( 'overflow-' + dimension );
882 while ( $parent.length ) {
883 if ( $parent[0] === el.ownerDocument.body ) {
884 return $parent[0];
886 i = props.length;
887 while ( i-- ) {
888 val = $parent.css( props[i] );
889 if ( val === 'auto' || val === 'scroll' ) {
890 return $parent[0];
893 $parent = $parent.parent();
895 return this.getDocument( el ).body;
899 * Scroll element into view.
901 * @static
902 * @param {HTMLElement} el Element to scroll into view
903 * @param {Object} [config={}] Configuration config
904 * @param {string} [config.duration] jQuery animation duration value
905 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
906 * to scroll in both directions
907 * @param {Function} [config.complete] Function to call when scrolling completes
909 OO.ui.Element.scrollIntoView = function ( el, config ) {
910 // Configuration initialization
911 config = config || {};
913 var rel, anim = {},
914 callback = typeof config.complete === 'function' && config.complete,
915 sc = this.getClosestScrollableContainer( el, config.direction ),
916 $sc = $( sc ),
917 eld = this.getDimensions( el ),
918 scd = this.getDimensions( sc ),
919 $win = $( this.getWindow( el ) );
921 // Compute the distances between the edges of el and the edges of the scroll viewport
922 if ( $sc.is( 'body' ) ) {
923 // If the scrollable container is the <body> this is easy
924 rel = {
925 top: eld.rect.top,
926 bottom: $win.innerHeight() - eld.rect.bottom,
927 left: eld.rect.left,
928 right: $win.innerWidth() - eld.rect.right
930 } else {
931 // Otherwise, we have to subtract el's coordinates from sc's coordinates
932 rel = {
933 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
934 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
935 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
936 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
940 if ( !config.direction || config.direction === 'y' ) {
941 if ( rel.top < 0 ) {
942 anim.scrollTop = scd.scroll.top + rel.top;
943 } else if ( rel.top > 0 && rel.bottom < 0 ) {
944 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
947 if ( !config.direction || config.direction === 'x' ) {
948 if ( rel.left < 0 ) {
949 anim.scrollLeft = scd.scroll.left + rel.left;
950 } else if ( rel.left > 0 && rel.right < 0 ) {
951 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
954 if ( !$.isEmptyObject( anim ) ) {
955 $sc.stop( true ).animate( anim, config.duration || 'fast' );
956 if ( callback ) {
957 $sc.queue( function ( next ) {
958 callback();
959 next();
960 } );
962 } else {
963 if ( callback ) {
964 callback();
969 /* Methods */
972 * Get the HTML tag name.
974 * Override this method to base the result on instance information.
976 * @return {string} HTML tag name
978 OO.ui.Element.prototype.getTagName = function () {
979 return this.constructor.static.tagName;
983 * Check if the element is attached to the DOM
984 * @return {boolean} The element is attached to the DOM
986 OO.ui.Element.prototype.isElementAttached = function () {
987 return $.contains( this.getElementDocument(), this.$element[0] );
991 * Get the DOM document.
993 * @return {HTMLDocument} Document object
995 OO.ui.Element.prototype.getElementDocument = function () {
996 return OO.ui.Element.getDocument( this.$element );
1000 * Get the DOM window.
1002 * @return {Window} Window object
1004 OO.ui.Element.prototype.getElementWindow = function () {
1005 return OO.ui.Element.getWindow( this.$element );
1009 * Get closest scrollable container.
1011 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1012 return OO.ui.Element.getClosestScrollableContainer( this.$element[0] );
1016 * Get group element is in.
1018 * @return {OO.ui.GroupElement|null} Group element, null if none
1020 OO.ui.Element.prototype.getElementGroup = function () {
1021 return this.elementGroup;
1025 * Set group element is in.
1027 * @param {OO.ui.GroupElement|null} group Group element, null if none
1028 * @chainable
1030 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1031 this.elementGroup = group;
1032 return this;
1036 * Scroll element into view.
1038 * @param {Object} [config={}]
1040 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1041 return OO.ui.Element.scrollIntoView( this.$element[0], config );
1045 * Bind a handler for an event on this.$element
1047 * @deprecated Use jQuery#on instead.
1048 * @param {string} event
1049 * @param {Function} callback
1051 OO.ui.Element.prototype.onDOMEvent = function ( event, callback ) {
1052 OO.ui.Element.onDOMEvent( this.$element, event, callback );
1056 * Unbind a handler bound with #offDOMEvent
1058 * @deprecated Use jQuery#off instead.
1059 * @param {string} event
1060 * @param {Function} callback
1062 OO.ui.Element.prototype.offDOMEvent = function ( event, callback ) {
1063 OO.ui.Element.offDOMEvent( this.$element, event, callback );
1066 ( function () {
1068 * Bind a handler for an event on a DOM element.
1070 * Used to be for working around a jQuery bug (jqbug.com/14180),
1071 * but obsolete as of jQuery 1.11.0.
1073 * @static
1074 * @deprecated Use jQuery#on instead.
1075 * @param {HTMLElement|jQuery} el DOM element
1076 * @param {string} event Event to bind
1077 * @param {Function} callback Callback to call when the event fires
1079 OO.ui.Element.onDOMEvent = function ( el, event, callback ) {
1080 $( el ).on( event, callback );
1084 * Unbind a handler bound with #static-method-onDOMEvent.
1086 * @deprecated Use jQuery#off instead.
1087 * @static
1088 * @param {HTMLElement|jQuery} el DOM element
1089 * @param {string} event Event to unbind
1090 * @param {Function} [callback] Callback to unbind
1092 OO.ui.Element.offDOMEvent = function ( el, event, callback ) {
1093 $( el ).off( event, callback );
1095 }() );
1098 * Embedded iframe with the same styles as its parent.
1100 * @class
1101 * @extends OO.ui.Element
1102 * @mixins OO.EventEmitter
1104 * @constructor
1105 * @param {Object} [config] Configuration options
1107 OO.ui.Frame = function OoUiFrame( config ) {
1108 // Parent constructor
1109 OO.ui.Frame.super.call( this, config );
1111 // Mixin constructors
1112 OO.EventEmitter.call( this );
1114 // Properties
1115 this.loading = null;
1116 this.config = config;
1118 // Initialize
1119 this.$element
1120 .addClass( 'oo-ui-frame' )
1121 .attr( { frameborder: 0, scrolling: 'no' } );
1125 /* Setup */
1127 OO.inheritClass( OO.ui.Frame, OO.ui.Element );
1128 OO.mixinClass( OO.ui.Frame, OO.EventEmitter );
1130 /* Static Properties */
1133 * @static
1134 * @inheritdoc
1136 OO.ui.Frame.static.tagName = 'iframe';
1138 /* Events */
1141 * @event load
1144 /* Static Methods */
1147 * Transplant the CSS styles from as parent document to a frame's document.
1149 * This loops over the style sheets in the parent document, and copies their nodes to the
1150 * frame's document. It then polls the document to see when all styles have loaded, and once they
1151 * have, resolves the promise.
1153 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1154 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1155 * Firefox, where the styles won't load until the iframe becomes visible.
1157 * For details of how we arrived at the strategy used in this function, see #load.
1159 * @static
1160 * @inheritable
1161 * @param {HTMLDocument} parentDoc Document to transplant styles from
1162 * @param {HTMLDocument} frameDoc Document to transplant styles to
1163 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1164 * @return {jQuery.Promise} Promise resolved when styles have loaded
1166 OO.ui.Frame.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1167 var i, numSheets, styleNode, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1168 $pollNodes = $( [] ),
1169 // Fake font-family value
1170 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1171 deferred = $.Deferred();
1173 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1174 styleNode = parentDoc.styleSheets[i].ownerNode;
1175 if ( styleNode.disabled ) {
1176 continue;
1178 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1179 // External stylesheet
1180 // Create a node with a unique ID that we're going to monitor to see when the CSS
1181 // has loaded
1182 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + i;
1183 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1184 .attr( 'id', pollNodeId )
1185 .appendTo( frameDoc.body )
1188 // Add <style>@import url(...); #pollNodeId { font-family: ... }</style>
1189 // The font-family rule will only take effect once the @import finishes
1190 newNode = frameDoc.createElement( 'style' );
1191 newNode.textContent = '@import url(' + styleNode.href + ');\n' +
1192 '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1193 } else {
1194 // Not an external stylesheet, or no polling required; just copy the node over
1195 newNode = frameDoc.importNode( styleNode, true );
1197 frameDoc.head.appendChild( newNode );
1200 // Poll every 100ms until all external stylesheets have loaded
1201 $pendingPollNodes = $pollNodes;
1202 timeoutID = setTimeout( function pollExternalStylesheets() {
1203 while (
1204 $pendingPollNodes.length > 0 &&
1205 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1207 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1210 if ( $pendingPollNodes.length === 0 ) {
1211 // We're done!
1212 if ( timeoutID !== null ) {
1213 timeoutID = null;
1214 $pollNodes.remove();
1215 deferred.resolve();
1217 } else {
1218 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1220 }, 100 );
1221 // ...but give up after a while
1222 if ( timeout !== 0 ) {
1223 setTimeout( function () {
1224 if ( timeoutID ) {
1225 clearTimeout( timeoutID );
1226 timeoutID = null;
1227 $pollNodes.remove();
1228 deferred.reject();
1230 }, timeout || 5000 );
1233 return deferred.promise();
1236 /* Methods */
1239 * Load the frame contents.
1241 * Once the iframe's stylesheets are loaded, the `load` event will be emitted and the returned
1242 * promise will be resolved. Calling while loading will return a promise but not trigger a new
1243 * loading cycle. Calling after loading is complete will return a promise that's already been
1244 * resolved.
1246 * Sounds simple right? Read on...
1248 * When you create a dynamic iframe using open/write/close, the window.load event for the
1249 * iframe is triggered when you call close, and there's no further load event to indicate that
1250 * everything is actually loaded.
1252 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
1253 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
1254 * are added to document.styleSheets immediately, and the only way you can determine whether they've
1255 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
1256 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
1258 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>` tags.
1259 * Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets until
1260 * the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the `@import`
1261 * has finished. And because the contents of the `<style>` tag are from the same origin, accessing
1262 * .cssRules is allowed.
1264 * However, now that we control the styles we're injecting, we might as well do away with
1265 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
1266 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
1267 * and wait for its font-family to change to someValue. Because `@import` is blocking, the font-family
1268 * rule is not applied until after the `@import` finishes.
1270 * All this stylesheet injection and polling magic is in #transplantStyles.
1272 * @return {jQuery.Promise} Promise resolved when loading is complete
1273 * @fires load
1275 OO.ui.Frame.prototype.load = function () {
1276 var win, doc,
1277 frame = this;
1279 // Return existing promise if already loading or loaded
1280 if ( this.loading ) {
1281 return this.loading.promise();
1284 // Load the frame
1285 this.loading = $.Deferred();
1287 win = this.$element.prop( 'contentWindow' );
1288 doc = win.document;
1290 // Figure out directionality:
1291 this.dir = OO.ui.Element.getDir( this.$element ) || 'ltr';
1293 // Initialize contents
1294 doc.open();
1295 doc.write(
1296 '<!doctype html>' +
1297 '<html>' +
1298 '<body class="oo-ui-frame-content oo-ui-' + this.dir + '" style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
1299 '</body>' +
1300 '</html>'
1302 doc.close();
1304 // Properties
1305 this.$ = OO.ui.Element.getJQuery( doc, this );
1306 this.$content = this.$( '.oo-ui-frame-content' ).attr( 'tabIndex', 0 );
1307 this.$document = this.$( doc );
1309 // Initialization
1310 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[0] )
1311 .always( function () {
1312 frame.emit( 'load' );
1313 frame.loading.resolve();
1314 } );
1316 return this.loading.promise();
1320 * Set the size of the frame.
1322 * @param {number} width Frame width in pixels
1323 * @param {number} height Frame height in pixels
1324 * @chainable
1326 OO.ui.Frame.prototype.setSize = function ( width, height ) {
1327 this.$element.css( { width: width, height: height } );
1328 return this;
1332 * Container for elements.
1334 * @abstract
1335 * @class
1336 * @extends OO.ui.Element
1337 * @mixins OO.EventEmitter
1339 * @constructor
1340 * @param {Object} [config] Configuration options
1342 OO.ui.Layout = function OoUiLayout( config ) {
1343 // Initialize config
1344 config = config || {};
1346 // Parent constructor
1347 OO.ui.Layout.super.call( this, config );
1349 // Mixin constructors
1350 OO.EventEmitter.call( this );
1352 // Initialization
1353 this.$element.addClass( 'oo-ui-layout' );
1356 /* Setup */
1358 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1359 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1362 * User interface control.
1364 * @abstract
1365 * @class
1366 * @extends OO.ui.Element
1367 * @mixins OO.EventEmitter
1369 * @constructor
1370 * @param {Object} [config] Configuration options
1371 * @cfg {boolean} [disabled=false] Disable
1373 OO.ui.Widget = function OoUiWidget( config ) {
1374 // Initialize config
1375 config = $.extend( { disabled: false }, config );
1377 // Parent constructor
1378 OO.ui.Widget.super.call( this, config );
1380 // Mixin constructors
1381 OO.EventEmitter.call( this );
1383 // Properties
1384 this.visible = true;
1385 this.disabled = null;
1386 this.wasDisabled = null;
1388 // Initialization
1389 this.$element.addClass( 'oo-ui-widget' );
1390 this.setDisabled( !!config.disabled );
1393 /* Setup */
1395 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1396 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1398 /* Events */
1401 * @event disable
1402 * @param {boolean} disabled Widget is disabled
1406 * @event toggle
1407 * @param {boolean} visible Widget is visible
1410 /* Methods */
1413 * Check if the widget is disabled.
1415 * @param {boolean} Button is disabled
1417 OO.ui.Widget.prototype.isDisabled = function () {
1418 return this.disabled;
1422 * Check if widget is visible.
1424 * @return {boolean} Widget is visible
1426 OO.ui.Widget.prototype.isVisible = function () {
1427 return this.visible;
1431 * Set the disabled state of the widget.
1433 * This should probably change the widgets' appearance and prevent it from being used.
1435 * @param {boolean} disabled Disable widget
1436 * @chainable
1438 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1439 var isDisabled;
1441 this.disabled = !!disabled;
1442 isDisabled = this.isDisabled();
1443 if ( isDisabled !== this.wasDisabled ) {
1444 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1445 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1446 this.emit( 'disable', isDisabled );
1448 this.wasDisabled = isDisabled;
1450 return this;
1454 * Toggle visibility of widget.
1456 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1457 * @fires visible
1458 * @chainable
1460 OO.ui.Widget.prototype.toggle = function ( show ) {
1461 show = show === undefined ? !this.visible : !!show;
1463 if ( show !== this.isVisible() ) {
1464 this.visible = show;
1465 this.$element.toggle( show );
1466 this.emit( 'toggle', show );
1469 return this;
1473 * Update the disabled state, in case of changes in parent widget.
1475 * @chainable
1477 OO.ui.Widget.prototype.updateDisabled = function () {
1478 this.setDisabled( this.disabled );
1479 return this;
1483 * Container for elements in a child frame.
1485 * Use together with OO.ui.WindowManager.
1487 * @abstract
1488 * @class
1489 * @extends OO.ui.Element
1490 * @mixins OO.EventEmitter
1492 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1493 * teardown processes are executed when the window is closed.
1495 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1496 * - Window manager begins opening window
1497 * - {@link #getSetupProcess} method is called and its result executed
1498 * - {@link #getReadyProcess} method is called and its result executed
1499 * - Window is now open
1501 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1502 * - Window manager begins closing window
1503 * - {@link #getHoldProcess} method is called and its result executed
1504 * - {@link #getTeardownProcess} method is called and its result executed
1505 * - Window is now closed
1507 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1508 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1509 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchonous
1510 * processing can complete. Always assume window processes are executed asychronously. See
1511 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1512 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1514 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1515 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1517 * @constructor
1518 * @param {OO.ui.WindowManager} manager Manager of window
1519 * @param {Object} [config] Configuration options
1520 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large` or `full`; omit to
1521 * use #static-size
1522 * @fires initialize
1524 OO.ui.Window = function OoUiWindow( manager, config ) {
1525 var win = this;
1527 // Configuration initialization
1528 config = config || {};
1530 // Parent constructor
1531 OO.ui.Window.super.call( this, config );
1533 // Mixin constructors
1534 OO.EventEmitter.call( this );
1536 if ( !( manager instanceof OO.ui.WindowManager ) ) {
1537 throw new Error( 'Cannot construct window: window must have a manager' );
1540 // Properties
1541 this.manager = manager;
1542 this.initialized = false;
1543 this.visible = false;
1544 this.opening = null;
1545 this.closing = null;
1546 this.opened = null;
1547 this.timing = null;
1548 this.size = config.size || this.constructor.static.size;
1549 this.frame = new OO.ui.Frame( { $: this.$ } );
1550 this.$frame = this.$( '<div>' );
1551 this.$ = function () {
1552 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1555 // Initialization
1556 this.$element
1557 .addClass( 'oo-ui-window' )
1558 // Hide the window using visibility: hidden; while the iframe is still loading
1559 // Can't use display: none; because that prevents the iframe from loading in Firefox
1560 .css( 'visibility', 'hidden' )
1561 .append( this.$frame );
1562 this.$frame
1563 .addClass( 'oo-ui-window-frame' )
1564 .append( this.frame.$element );
1566 // Events
1567 this.frame.on( 'load', function () {
1568 win.initialize();
1569 win.initialized = true;
1570 // Undo the visibility: hidden; hack and apply display: none;
1571 // We can do this safely now that the iframe has initialized
1572 // (don't do this from within #initialize because it has to happen
1573 // after the all subclasses have been handled as well).
1574 win.$element.hide().css( 'visibility', '' );
1575 } );
1578 /* Setup */
1580 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1581 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1583 /* Events */
1586 * @event resize
1587 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1590 /* Static Properties */
1593 * Symbolic name of size.
1595 * Size is used if no size is configured during construction.
1597 * @static
1598 * @inheritable
1599 * @property {string}
1601 OO.ui.Window.static.size = 'medium';
1603 /* Methods */
1606 * Check if window has been initialized.
1608 * @return {boolean} Window has been initialized
1610 OO.ui.Window.prototype.isInitialized = function () {
1611 return this.initialized;
1615 * Check if window is visible.
1617 * @return {boolean} Window is visible
1619 OO.ui.Window.prototype.isVisible = function () {
1620 return this.visible;
1624 * Check if window is opening.
1626 * This is a wrapper around OO.ui.WindowManager#isOpening.
1628 * @return {boolean} Window is opening
1630 OO.ui.Window.prototype.isOpening = function () {
1631 return this.manager.isOpening( this );
1635 * Check if window is closing.
1637 * This is a wrapper around OO.ui.WindowManager#isClosing.
1639 * @return {boolean} Window is closing
1641 OO.ui.Window.prototype.isClosing = function () {
1642 return this.manager.isClosing( this );
1646 * Check if window is opened.
1648 * This is a wrapper around OO.ui.WindowManager#isOpened.
1650 * @return {boolean} Window is opened
1652 OO.ui.Window.prototype.isOpened = function () {
1653 return this.manager.isOpened( this );
1657 * Get the window manager.
1659 * @return {OO.ui.WindowManager} Manager of window
1661 OO.ui.Window.prototype.getManager = function () {
1662 return this.manager;
1666 * Get the window frame.
1668 * @return {OO.ui.Frame} Frame of window
1670 OO.ui.Window.prototype.getFrame = function () {
1671 return this.frame;
1675 * Get the window size.
1677 * @return {string} Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1679 OO.ui.Window.prototype.getSize = function () {
1680 return this.size;
1684 * Get the height of the dialog contents.
1686 * @return {number} Content height
1688 OO.ui.Window.prototype.getContentHeight = function () {
1689 return Math.round(
1690 // Add buffer for border
1691 ( ( this.$frame.outerHeight() - this.$frame.innerHeight() ) * 2 ) +
1692 // Height of contents
1693 ( this.$head.outerHeight( true ) + this.getBodyHeight() + this.$foot.outerHeight( true ) )
1698 * Get the height of the dialog contents.
1700 * @return {number} Height of content
1702 OO.ui.Window.prototype.getBodyHeight = function () {
1703 return this.$body[0].scrollHeight;
1707 * Get a process for setting up a window for use.
1709 * Each time the window is opened this process will set it up for use in a particular context, based
1710 * on the `data` argument.
1712 * When you override this method, you can add additional setup steps to the process the parent
1713 * method provides using the 'first' and 'next' methods.
1715 * @abstract
1716 * @param {Object} [data] Window opening data
1717 * @return {OO.ui.Process} Setup process
1719 OO.ui.Window.prototype.getSetupProcess = function () {
1720 return new OO.ui.Process();
1724 * Get a process for readying a window for use.
1726 * Each time the window is open and setup, this process will ready it up for use in a particular
1727 * context, based on the `data` argument.
1729 * When you override this method, you can add additional setup steps to the process the parent
1730 * method provides using the 'first' and 'next' methods.
1732 * @abstract
1733 * @param {Object} [data] Window opening data
1734 * @return {OO.ui.Process} Setup process
1736 OO.ui.Window.prototype.getReadyProcess = function () {
1737 return new OO.ui.Process();
1741 * Get a process for holding a window from use.
1743 * Each time the window is closed, this process will hold it from use in a particular context, based
1744 * on the `data` argument.
1746 * When you override this method, you can add additional setup steps to the process the parent
1747 * method provides using the 'first' and 'next' methods.
1749 * @abstract
1750 * @param {Object} [data] Window closing data
1751 * @return {OO.ui.Process} Hold process
1753 OO.ui.Window.prototype.getHoldProcess = function () {
1754 return new OO.ui.Process();
1758 * Get a process for tearing down a window after use.
1760 * Each time the window is closed this process will tear it down and do something with the user's
1761 * interactions within the window, based on the `data` argument.
1763 * When you override this method, you can add additional teardown steps to the process the parent
1764 * method provides using the 'first' and 'next' methods.
1766 * @abstract
1767 * @param {Object} [data] Window closing data
1768 * @return {OO.ui.Process} Teardown process
1770 OO.ui.Window.prototype.getTeardownProcess = function () {
1771 return new OO.ui.Process();
1775 * Set the window size.
1777 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1778 * @chainable
1780 OO.ui.Window.prototype.setSize = function ( size ) {
1781 this.size = size;
1782 this.manager.updateWindowSize( this );
1783 return this;
1787 * Set window dimensions.
1789 * Properties are applied to the frame container.
1791 * @param {Object} dim CSS dimension properties
1792 * @param {string|number} [dim.width] Width
1793 * @param {string|number} [dim.minWidth] Minimum width
1794 * @param {string|number} [dim.maxWidth] Maximum width
1795 * @param {string|number} [dim.width] Height, omit to set based on height of contents
1796 * @param {string|number} [dim.minWidth] Minimum height
1797 * @param {string|number} [dim.maxWidth] Maximum height
1798 * @chainable
1800 OO.ui.Window.prototype.setDimensions = function ( dim ) {
1801 // Apply width before height so height is not based on wrapping content using the wrong width
1802 this.$frame.css( {
1803 width: dim.width || '',
1804 minWidth: dim.minWidth || '',
1805 maxWidth: dim.maxWidth || ''
1806 } );
1807 this.$frame.css( {
1808 height: ( dim.height !== undefined ? dim.height : this.getContentHeight() ) || '',
1809 minHeight: dim.minHeight || '',
1810 maxHeight: dim.maxHeight || ''
1811 } );
1812 return this;
1816 * Initialize window contents.
1818 * The first time the window is opened, #initialize is called when it's safe to begin populating
1819 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
1821 * Once this method is called, this.$ can be used to create elements within the frame.
1823 * @chainable
1825 OO.ui.Window.prototype.initialize = function () {
1826 // Properties
1827 this.$ = this.frame.$;
1828 this.$head = this.$( '<div>' );
1829 this.$body = this.$( '<div>' );
1830 this.$foot = this.$( '<div>' );
1831 this.$overlay = this.$( '<div>' );
1833 // Initialization
1834 this.$head.addClass( 'oo-ui-window-head' );
1835 this.$body.addClass( 'oo-ui-window-body' );
1836 this.$foot.addClass( 'oo-ui-window-foot' );
1837 this.$overlay.addClass( 'oo-ui-window-overlay' );
1838 this.frame.$content
1839 .addClass( 'oo-ui-window-content' )
1840 .append( this.$head, this.$body, this.$foot, this.$overlay );
1842 return this;
1846 * Open window.
1848 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
1849 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
1851 * @param {Object} [data] Window opening data
1852 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
1853 * first argument will be a promise which will be resolved when the window begins closing
1855 OO.ui.Window.prototype.open = function ( data ) {
1856 return this.manager.openWindow( this, data );
1860 * Close window.
1862 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
1863 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
1865 * @param {Object} [data] Window closing data
1866 * @return {jQuery.Promise} Promise resolved when window is closed
1868 OO.ui.Window.prototype.close = function ( data ) {
1869 return this.manager.closeWindow( this, data );
1873 * Load window.
1875 * This is called by OO.ui.WindowManager durring window adding, and should not be called directly
1876 * by other systems.
1878 * @return {jQuery.Promise} Promise resolved when window is loaded
1880 OO.ui.Window.prototype.load = function () {
1881 return this.frame.load();
1885 * Setup window.
1887 * This is called by OO.ui.WindowManager durring window opening, and should not be called directly
1888 * by other systems.
1890 * @param {Object} [data] Window opening data
1891 * @return {jQuery.Promise} Promise resolved when window is setup
1893 OO.ui.Window.prototype.setup = function ( data ) {
1894 var win = this,
1895 deferred = $.Deferred();
1897 this.$element.show();
1898 this.visible = true;
1899 this.getSetupProcess( data ).execute().done( function () {
1900 win.manager.updateWindowSize( win );
1901 // Force redraw by asking the browser to measure the elements' widths
1902 win.$element.addClass( 'oo-ui-window-setup' ).width();
1903 win.frame.$content.addClass( 'oo-ui-window-content-setup' ).width();
1904 deferred.resolve();
1905 } );
1907 return deferred.promise();
1911 * Ready window.
1913 * This is called by OO.ui.WindowManager durring window opening, and should not be called directly
1914 * by other systems.
1916 * @param {Object} [data] Window opening data
1917 * @return {jQuery.Promise} Promise resolved when window is ready
1919 OO.ui.Window.prototype.ready = function ( data ) {
1920 var win = this,
1921 deferred = $.Deferred();
1923 this.frame.$content[0].focus();
1924 this.getReadyProcess( data ).execute().done( function () {
1925 // Force redraw by asking the browser to measure the elements' widths
1926 win.$element.addClass( 'oo-ui-window-ready' ).width();
1927 win.frame.$content.addClass( 'oo-ui-window-content-ready' ).width();
1928 deferred.resolve();
1929 } );
1931 return deferred.promise();
1935 * Hold window.
1937 * This is called by OO.ui.WindowManager durring window closing, and should not be called directly
1938 * by other systems.
1940 * @param {Object} [data] Window closing data
1941 * @return {jQuery.Promise} Promise resolved when window is held
1943 OO.ui.Window.prototype.hold = function ( data ) {
1944 var win = this,
1945 deferred = $.Deferred();
1947 this.getHoldProcess( data ).execute().done( function () {
1948 var $focused = win.frame.$content.find( ':focus' );
1949 if ( $focused.length ) {
1950 $focused[0].blur();
1952 // Force redraw by asking the browser to measure the elements' widths
1953 win.$element.removeClass( 'oo-ui-window-ready' ).width();
1954 win.frame.$content.removeClass( 'oo-ui-window-content-ready' ).width();
1955 deferred.resolve();
1956 } );
1958 return deferred.promise();
1962 * Teardown window.
1964 * This is called by OO.ui.WindowManager durring window closing, and should not be called directly
1965 * by other systems.
1967 * @param {Object} [data] Window closing data
1968 * @return {jQuery.Promise} Promise resolved when window is torn down
1970 OO.ui.Window.prototype.teardown = function ( data ) {
1971 var win = this,
1972 deferred = $.Deferred();
1974 this.getTeardownProcess( data ).execute().done( function () {
1975 // Force redraw by asking the browser to measure the elements' widths
1976 win.$element.removeClass( 'oo-ui-window-setup' ).width();
1977 win.frame.$content.removeClass( 'oo-ui-window-content-setup' ).width();
1978 win.$element.hide();
1979 win.visible = false;
1980 deferred.resolve();
1981 } );
1983 return deferred.promise();
1987 * Base class for all dialogs.
1989 * Logic:
1990 * - Manage the window (open and close, etc.).
1991 * - Store the internal name and display title.
1992 * - A stack to track one or more pending actions.
1993 * - Manage a set of actions that can be performed.
1994 * - Configure and create action widgets.
1996 * User interface:
1997 * - Close the dialog with Escape key.
1998 * - Visually lock the dialog while an action is in
1999 * progress (aka "pending").
2001 * Subclass responsibilities:
2002 * - Display the title somewhere.
2003 * - Add content to the dialog.
2004 * - Provide a UI to close the dialog.
2005 * - Display the action widgets somewhere.
2007 * @abstract
2008 * @class
2009 * @extends OO.ui.Window
2010 * @mixins OO.ui.LabeledElement
2012 * @constructor
2013 * @param {Object} [config] Configuration options
2015 OO.ui.Dialog = function OoUiDialog( manager, config ) {
2016 // Parent constructor
2017 OO.ui.Dialog.super.call( this, manager, config );
2019 // Properties
2020 this.actions = new OO.ui.ActionSet();
2021 this.attachedActions = [];
2022 this.currentAction = null;
2023 this.pending = 0;
2025 // Events
2026 this.actions.connect( this, {
2027 click: 'onActionClick',
2028 resize: 'onActionResize',
2029 change: 'onActionsChange'
2030 } );
2032 // Initialization
2033 this.$element
2034 .addClass( 'oo-ui-dialog' )
2035 .attr( 'role', 'dialog' );
2038 /* Setup */
2040 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2042 /* Static Properties */
2045 * Symbolic name of dialog.
2047 * @abstract
2048 * @static
2049 * @inheritable
2050 * @property {string}
2052 OO.ui.Dialog.static.name = '';
2055 * Dialog title.
2057 * @abstract
2058 * @static
2059 * @inheritable
2060 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2062 OO.ui.Dialog.static.title = '';
2065 * List of OO.ui.ActionWidget configuration options.
2067 * @static
2068 * inheritable
2069 * @property {Object[]}
2071 OO.ui.Dialog.static.actions = [];
2074 * Close dialog when the escape key is pressed.
2076 * @static
2077 * @abstract
2078 * @inheritable
2079 * @property {boolean}
2081 OO.ui.Dialog.static.escapable = true;
2083 /* Methods */
2086 * Handle frame document key down events.
2088 * @param {jQuery.Event} e Key down event
2090 OO.ui.Dialog.prototype.onFrameDocumentKeyDown = function ( e ) {
2091 if ( e.which === OO.ui.Keys.ESCAPE ) {
2092 this.close();
2093 return false;
2098 * Handle action resized events.
2100 * @param {OO.ui.ActionWidget} action Action that was resized
2102 OO.ui.Dialog.prototype.onActionResize = function () {
2103 // Override in subclass
2107 * Handle action click events.
2109 * @param {OO.ui.ActionWidget} action Action that was clicked
2111 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2112 if ( !this.isPending() ) {
2113 this.currentAction = action;
2114 this.executeAction( action.getAction() );
2119 * Handle actions change event.
2121 OO.ui.Dialog.prototype.onActionsChange = function () {
2122 this.detachActions();
2123 if ( !this.isClosing() ) {
2124 this.attachActions();
2129 * Check if input is pending.
2131 * @return {boolean}
2133 OO.ui.Dialog.prototype.isPending = function () {
2134 return !!this.pending;
2138 * Get set of actions.
2140 * @return {OO.ui.ActionSet}
2142 OO.ui.Dialog.prototype.getActions = function () {
2143 return this.actions;
2147 * Get a process for taking action.
2149 * When you override this method, you can add additional accept steps to the process the parent
2150 * method provides using the 'first' and 'next' methods.
2152 * @abstract
2153 * @param {string} [action] Symbolic name of action
2154 * @return {OO.ui.Process} Action process
2156 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2157 return new OO.ui.Process()
2158 .next( function () {
2159 if ( !action ) {
2160 // An empty action always closes the dialog without data, which should always be
2161 // safe and make no changes
2162 this.close();
2164 }, this );
2168 * @inheritdoc
2170 * @param {Object} [data] Dialog opening data
2171 * @param {jQuery|string|Function|null} [data.label] Dialog label, omit to use #static-label
2172 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2173 * action item, omit to use #static-actions
2175 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2176 data = data || {};
2178 // Parent method
2179 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2180 .next( function () {
2181 var i, len,
2182 items = [],
2183 config = this.constructor.static,
2184 actions = data.actions !== undefined ? data.actions : config.actions;
2186 this.title.setLabel(
2187 data.title !== undefined ? data.title : this.constructor.static.title
2189 for ( i = 0, len = actions.length; i < len; i++ ) {
2190 items.push(
2191 new OO.ui.ActionWidget( $.extend( { $: this.$ }, actions[i] ) )
2194 this.actions.add( items );
2195 }, this );
2199 * @inheritdoc
2201 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2202 // Parent method
2203 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2204 .first( function () {
2205 this.actions.clear();
2206 this.currentAction = null;
2207 }, this );
2211 * @inheritdoc
2213 OO.ui.Dialog.prototype.initialize = function () {
2214 // Parent method
2215 OO.ui.Dialog.super.prototype.initialize.call( this );
2217 // Properties
2218 this.title = new OO.ui.LabelWidget( { $: this.$ } );
2220 // Events
2221 if ( this.constructor.static.escapable ) {
2222 this.frame.$document.on( 'keydown', OO.ui.bind( this.onFrameDocumentKeyDown, this ) );
2225 // Initialization
2226 this.frame.$content.addClass( 'oo-ui-dialog-content' );
2230 * Attach action actions.
2232 OO.ui.Dialog.prototype.attachActions = function () {
2233 // Remember the list of potentially attached actions
2234 this.attachedActions = this.actions.get();
2238 * Detach action actions.
2240 * @chainable
2242 OO.ui.Dialog.prototype.detachActions = function () {
2243 var i, len;
2245 // Detach all actions that may have been previously attached
2246 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2247 this.attachedActions[i].$element.detach();
2249 this.attachedActions = [];
2253 * Execute an action.
2255 * @param {string} action Symbolic name of action to execute
2256 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2258 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2259 this.pushPending();
2260 return this.getActionProcess( action ).execute()
2261 .always( OO.ui.bind( this.popPending, this ) );
2265 * Increase the pending stack.
2267 * @chainable
2269 OO.ui.Dialog.prototype.pushPending = function () {
2270 if ( this.pending === 0 ) {
2271 this.frame.$content.addClass( 'oo-ui-actionDialog-content-pending' );
2272 this.$head.addClass( 'oo-ui-texture-pending' );
2274 this.pending++;
2276 return this;
2280 * Reduce the pending stack.
2282 * Clamped at zero.
2284 * @chainable
2286 OO.ui.Dialog.prototype.popPending = function () {
2287 if ( this.pending === 1 ) {
2288 this.frame.$content.removeClass( 'oo-ui-actionDialog-content-pending' );
2289 this.$head.removeClass( 'oo-ui-texture-pending' );
2291 this.pending = Math.max( 0, this.pending - 1 );
2293 return this;
2297 * Collection of windows.
2299 * @class
2300 * @extends OO.ui.Element
2301 * @mixins OO.EventEmitter
2303 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2304 * already opening or opened, the current window will be closed without data. Empty closing data
2305 * should always result in the window being closed without causing constructive or destructive
2306 * action.
2308 * As a window is opened and closed, it passes through several stages and the manager emits several
2309 * corresponding events.
2311 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2312 * - {@link #event-opening} is emitted with `opening` promise
2313 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2314 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2315 * - `setup` progress notification is emitted from opening promise
2316 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2317 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2318 * - `ready` progress notification is emitted from opening promise
2319 * - `opening` promise is resolved with `opened` promise
2320 * - Window is now open
2322 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2323 * - `opened` promise is resolved with `closing` promise
2324 * - {@link #event-closing} is emitted with `closing` promise
2325 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2326 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2327 * - `hold` progress notification is emitted from opening promise
2328 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2329 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2330 * - `teardown` progress notification is emitted from opening promise
2331 * - Closing promise is resolved
2332 * - Window is now closed
2334 * @constructor
2335 * @param {Object} [config] Configuration options
2336 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2337 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2339 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2340 // Configuration initialization
2341 config = config || {};
2343 // Parent constructor
2344 OO.ui.WindowManager.super.call( this, config );
2346 // Mixin constructors
2347 OO.EventEmitter.call( this );
2349 // Properties
2350 this.factory = config.factory;
2351 this.modal = config.modal === undefined || !!config.modal;
2352 this.windows = {};
2353 this.opening = null;
2354 this.opened = null;
2355 this.closing = null;
2356 this.size = null;
2357 this.currentWindow = null;
2358 this.$ariaHidden = null;
2359 this.requestedSize = null;
2360 this.onWindowResizeTimeout = null;
2361 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
2362 this.afterWindowResizeHandler = OO.ui.bind( this.afterWindowResize, this );
2363 this.onWindowMouseWheelHandler = OO.ui.bind( this.onWindowMouseWheel, this );
2364 this.onDocumentKeyDownHandler = OO.ui.bind( this.onDocumentKeyDown, this );
2366 // Events
2367 this.$element.on( 'mousedown', false );
2369 // Initialization
2370 this.$element
2371 .addClass( 'oo-ui-windowManager' )
2372 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2375 /* Setup */
2377 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2378 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2380 /* Events */
2383 * Window is opening.
2385 * Fired when the window begins to be opened.
2387 * @event opening
2388 * @param {OO.ui.Window} win Window that's being opened
2389 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2390 * resolved the first argument will be a promise which will be resolved when the window begins
2391 * closing, the second argument will be the opening data; progress notifications will be fired on
2392 * the promise for `setup` and `ready` when those processes are completed respectively.
2393 * @param {Object} data Window opening data
2397 * Window is closing.
2399 * Fired when the window begins to be closed.
2401 * @event closing
2402 * @param {OO.ui.Window} win Window that's being closed
2403 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2404 * is resolved the first argument will be a the closing data; progress notifications will be fired
2405 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2406 * @param {Object} data Window closing data
2409 /* Static Properties */
2412 * Map of symbolic size names and CSS properties.
2414 * @static
2415 * @inheritable
2416 * @property {Object}
2418 OO.ui.WindowManager.static.sizes = {
2419 small: {
2420 width: 300
2422 medium: {
2423 width: 500
2425 large: {
2426 width: 700
2428 full: {
2429 // These can be non-numeric because they are never used in calculations
2430 width: '100%',
2431 height: '100%'
2436 * Symbolic name of default size.
2438 * Default size is used if the window's requested size is not recognized.
2440 * @static
2441 * @inheritable
2442 * @property {string}
2444 OO.ui.WindowManager.static.defaultSize = 'medium';
2446 /* Methods */
2449 * Handle window resize events.
2451 * @param {jQuery.Event} e Window resize event
2453 OO.ui.WindowManager.prototype.onWindowResize = function () {
2454 clearTimeout( this.onWindowResizeTimeout );
2455 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2459 * Handle window resize events.
2461 * @param {jQuery.Event} e Window resize event
2463 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2464 if ( this.currentWindow ) {
2465 this.updateWindowSize( this.currentWindow );
2470 * Handle window mouse wheel events.
2472 * @param {jQuery.Event} e Mouse wheel event
2474 OO.ui.WindowManager.prototype.onWindowMouseWheel = function () {
2475 return false;
2479 * Handle document key down events.
2481 * @param {jQuery.Event} e Key down event
2483 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2484 switch ( e.which ) {
2485 case OO.ui.Keys.PAGEUP:
2486 case OO.ui.Keys.PAGEDOWN:
2487 case OO.ui.Keys.END:
2488 case OO.ui.Keys.HOME:
2489 case OO.ui.Keys.LEFT:
2490 case OO.ui.Keys.UP:
2491 case OO.ui.Keys.RIGHT:
2492 case OO.ui.Keys.DOWN:
2493 // Prevent any key events that might cause scrolling
2494 return false;
2499 * Check if window is opening.
2501 * @return {boolean} Window is opening
2503 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2504 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2508 * Check if window is closing.
2510 * @return {boolean} Window is closing
2512 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2513 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2517 * Check if window is opened.
2519 * @return {boolean} Window is opened
2521 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2522 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2526 * Check if a window is being managed.
2528 * @param {OO.ui.Window} win Window to check
2529 * @return {boolean} Window is being managed
2531 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2532 var name;
2534 for ( name in this.windows ) {
2535 if ( this.windows[name] === win ) {
2536 return true;
2540 return false;
2544 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2546 * @param {OO.ui.Window} win Window being opened
2547 * @param {Object} [data] Window opening data
2548 * @return {number} Milliseconds to wait
2550 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2551 return 0;
2555 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2557 * @param {OO.ui.Window} win Window being opened
2558 * @param {Object} [data] Window opening data
2559 * @return {number} Milliseconds to wait
2561 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2562 return 0;
2566 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2568 * @param {OO.ui.Window} win Window being closed
2569 * @param {Object} [data] Window closing data
2570 * @return {number} Milliseconds to wait
2572 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2573 return 0;
2577 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2579 * @param {OO.ui.Window} win Window being closed
2580 * @param {Object} [data] Window closing data
2581 * @return {number} Milliseconds to wait
2583 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2584 return this.modal ? 250 : 0;
2588 * Get managed window by symbolic name.
2590 * If window is not yet instantiated, it will be instantiated and added automatically.
2592 * @param {string} name Symbolic window name
2593 * @return {jQuery.Promise} Promise resolved when window is ready to be accessed; when resolved the
2594 * first argument is an OO.ui.Window; when rejected the first argument is an OO.ui.Error
2595 * @throws {Error} If the symbolic name is unrecognized by the factory
2596 * @throws {Error} If the symbolic name unrecognized as a managed window
2598 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2599 var deferred = $.Deferred(),
2600 win = this.windows[name];
2602 if ( !( win instanceof OO.ui.Window ) ) {
2603 if ( this.factory ) {
2604 if ( !this.factory.lookup( name ) ) {
2605 deferred.reject( new OO.ui.Error(
2606 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2607 ) );
2608 } else {
2609 win = this.factory.create( name, this, { $: this.$ } );
2610 this.addWindows( [ win ] ).then(
2611 OO.ui.bind( deferred.resolve, deferred, win ),
2612 deferred.reject
2615 } else {
2616 deferred.reject( new OO.ui.Error(
2617 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2618 ) );
2620 } else {
2621 deferred.resolve( win );
2624 return deferred.promise();
2628 * Get current window.
2630 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2632 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2633 return this.currentWindow;
2637 * Open a window.
2639 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2640 * @param {Object} [data] Window opening data
2641 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2642 * for more details about the `opening` promise
2643 * @fires opening
2645 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2646 var manager = this,
2647 preparing = [],
2648 opening = $.Deferred();
2650 // Argument handling
2651 if ( typeof win === 'string' ) {
2652 return this.getWindow( win ).then( function ( win ) {
2653 return manager.openWindow( win, data );
2654 } );
2657 // Error handling
2658 if ( !this.hasWindow( win ) ) {
2659 opening.reject( new OO.ui.Error(
2660 'Cannot open window: window is not attached to manager'
2661 ) );
2664 // Window opening
2665 if ( opening.state() !== 'rejected' ) {
2666 // Begin loading the window if it's not loaded already - may take noticable time and we want
2667 // too do this in paralell with any preparatory actions
2668 preparing.push( win.load() );
2670 if ( this.opening || this.opened ) {
2671 // If a window is currently opening or opened, close it first
2672 preparing.push( this.closeWindow( this.currentWindow ) );
2673 } else if ( this.closing ) {
2674 // If a window is currently closing, wait for it to complete
2675 preparing.push( this.closing );
2678 $.when.apply( $, preparing ).done( function () {
2679 if ( manager.modal ) {
2680 manager.$( manager.getElementDocument() ).on( {
2681 // Prevent scrolling by keys in top-level window
2682 keydown: manager.onDocumentKeyDownHandler
2683 } );
2684 manager.$( manager.getElementWindow() ).on( {
2685 // Prevent scrolling by wheel in top-level window
2686 mousewheel: manager.onWindowMouseWheelHandler,
2687 // Start listening for top-level window dimension changes
2688 'orientationchange resize': manager.onWindowResizeHandler
2689 } );
2690 // Hide other content from screen readers
2691 manager.$ariaHidden = $( 'body' )
2692 .children()
2693 .not( manager.$element.parentsUntil( 'body' ).last() )
2694 .attr( 'aria-hidden', '' );
2696 manager.currentWindow = win;
2697 manager.opening = opening;
2698 manager.emit( 'opening', win, opening, data );
2699 manager.updateWindowSize( win );
2700 setTimeout( function () {
2701 win.setup( data ).then( function () {
2702 manager.opening.notify( { state: 'setup' } );
2703 setTimeout( function () {
2704 win.ready( data ).then( function () {
2705 manager.opening.notify( { state: 'ready' } );
2706 manager.opening = null;
2707 manager.opened = $.Deferred();
2708 opening.resolve( manager.opened.promise(), data );
2709 } );
2710 }, manager.getReadyDelay() );
2711 } );
2712 }, manager.getSetupDelay() );
2713 } );
2716 return opening;
2720 * Close a window.
2722 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
2723 * @param {Object} [data] Window closing data
2724 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-closing}
2725 * for more details about the `closing` promise
2726 * @throws {Error} If no window by that name is being managed
2727 * @fires closing
2729 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
2730 var manager = this,
2731 preparing = [],
2732 closing = $.Deferred(),
2733 opened = this.opened;
2735 // Argument handling
2736 if ( typeof win === 'string' ) {
2737 win = this.windows[win];
2738 } else if ( !this.hasWindow( win ) ) {
2739 win = null;
2742 // Error handling
2743 if ( !win ) {
2744 closing.reject( new OO.ui.Error(
2745 'Cannot close window: window is not attached to manager'
2746 ) );
2747 } else if ( win !== this.currentWindow ) {
2748 closing.reject( new OO.ui.Error(
2749 'Cannot close window: window already closed with different data'
2750 ) );
2751 } else if ( this.closing ) {
2752 closing.reject( new OO.ui.Error(
2753 'Cannot close window: window already closing with different data'
2754 ) );
2757 // Window closing
2758 if ( closing.state() !== 'rejected' ) {
2759 if ( this.opening ) {
2760 // If the window is currently opening, close it when it's done
2761 preparing.push( this.opening );
2764 // Close the window
2765 $.when.apply( $, preparing ).done( function () {
2766 manager.closing = closing;
2767 manager.emit( 'closing', win, closing, data );
2768 manager.opened = null;
2769 opened.resolve( closing.promise(), data );
2770 setTimeout( function () {
2771 win.hold( data ).then( function () {
2772 closing.notify( { state: 'hold' } );
2773 setTimeout( function () {
2774 win.teardown( data ).then( function () {
2775 closing.notify( { state: 'teardown' } );
2776 if ( manager.modal ) {
2777 manager.$( manager.getElementDocument() ).off( {
2778 // Allow scrolling by keys in top-level window
2779 keydown: manager.onDocumentKeyDownHandler
2780 } );
2781 manager.$( manager.getElementWindow() ).off( {
2782 // Allow scrolling by wheel in top-level window
2783 mousewheel: manager.onWindowMouseWheelHandler,
2784 // Stop listening for top-level window dimension changes
2785 'orientationchange resize': manager.onWindowResizeHandler
2786 } );
2788 // Restore screen reader visiblity
2789 if ( manager.$ariaHidden ) {
2790 manager.$ariaHidden.removeAttr( 'aria-hidden' );
2791 manager.$ariaHidden = null;
2793 manager.closing = null;
2794 manager.currentWindow = null;
2795 closing.resolve( data );
2796 } );
2797 }, manager.getTeardownDelay() );
2798 } );
2799 }, manager.getHoldDelay() );
2800 } );
2803 return closing;
2807 * Add windows.
2809 * If the window manager is attached to the DOM then windows will be automatically loaded as they
2810 * are added.
2812 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
2813 * @return {jQuery.Promise} Promise resolved when all windows are added
2814 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
2815 * a statically configured symbolic name
2817 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
2818 var i, len, win, name, list,
2819 promises = [];
2821 if ( $.isArray( windows ) ) {
2822 // Convert to map of windows by looking up symbolic names from static configuration
2823 list = {};
2824 for ( i = 0, len = windows.length; i < len; i++ ) {
2825 name = windows[i].constructor.static.name;
2826 if ( typeof name !== 'string' ) {
2827 throw new Error( 'Cannot add window' );
2829 list[name] = windows[i];
2831 } else if ( $.isPlainObject( windows ) ) {
2832 list = windows;
2835 // Add windows
2836 for ( name in list ) {
2837 win = list[name];
2838 this.windows[name] = win;
2839 this.$element.append( win.$element );
2841 if ( this.isElementAttached() ) {
2842 promises.push( win.load() );
2846 return $.when.apply( $, promises );
2850 * Remove windows.
2852 * Windows will be closed before they are removed.
2854 * @param {string} name Symbolic name of window to remove
2855 * @return {jQuery.Promise} Promise resolved when window is closed and removed
2856 * @throws {Error} If windows being removed are not being managed
2858 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
2859 var i, len, win, name,
2860 manager = this,
2861 promises = [],
2862 cleanup = function ( name, win ) {
2863 delete manager.windows[name];
2864 win.$element.detach();
2867 for ( i = 0, len = names.length; i < len; i++ ) {
2868 name = names[i];
2869 win = this.windows[name];
2870 if ( !win ) {
2871 throw new Error( 'Cannot remove window' );
2873 promises.push( this.closeWindow( name ).then( OO.ui.bind( cleanup, null, name, win ) ) );
2876 return $.when.apply( $, promises );
2880 * Remove all windows.
2882 * Windows will be closed before they are removed.
2884 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
2886 OO.ui.WindowManager.prototype.clearWindows = function () {
2887 return this.removeWindows( Object.keys( this.windows ) );
2891 * Set dialog size.
2893 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
2895 * @chainable
2897 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
2898 // Bypass for non-current, and thus invisible, windows
2899 if ( win !== this.currentWindow ) {
2900 return;
2903 var viewport = OO.ui.Element.getDimensions( win.getElementWindow() ),
2904 sizes = this.constructor.static.sizes,
2905 size = win.getSize();
2907 if ( !sizes[size] ) {
2908 size = this.constructor.static.defaultSize;
2910 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[size].width ) {
2911 size = 'full';
2914 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
2915 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
2916 win.setDimensions( sizes[size] );
2918 return this;
2922 * @abstract
2923 * @class
2925 * @constructor
2926 * @param {string|jQuery} message Description of error
2927 * @param {Object} [config] Configuration options
2928 * @cfg {boolean} [recoverable=true] Error is recoverable
2930 OO.ui.Error = function OoUiElement( message, config ) {
2931 // Configuration initialization
2932 config = config || {};
2934 // Properties
2935 this.message = message instanceof jQuery ? message : String( message );
2936 this.recoverable = config.recoverable === undefined || !!config.recoverable;
2939 /* Setup */
2941 OO.initClass( OO.ui.Error );
2943 /* Methods */
2946 * Check if error can be recovered from.
2948 * @return {boolean} Error is recoverable
2950 OO.ui.Error.prototype.isRecoverable = function () {
2951 return this.recoverable;
2955 * Get error message as DOM nodes.
2957 * @return {jQuery} Error message in DOM nodes
2959 OO.ui.Error.prototype.getMessage = function () {
2960 return this.message instanceof jQuery ?
2961 this.message.clone() :
2962 $( '<div>' ).text( this.message ).contents();
2966 * Get error message as text.
2968 * @return {string} Error message
2970 OO.ui.Error.prototype.getMessageText = function () {
2971 return this.message instanceof jQuery ? this.message.text() : this.message;
2975 * A list of functions, called in sequence.
2977 * If a function added to a process returns boolean false the process will stop; if it returns an
2978 * object with a `promise` method the process will use the promise to either continue to the next
2979 * step when the promise is resolved or stop when the promise is rejected.
2981 * @class
2983 * @constructor
2984 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
2985 * call, see #createStep for more information
2986 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
2987 * or a promise
2988 * @return {Object} Step object, with `callback` and `context` properties
2990 OO.ui.Process = function ( step, context ) {
2991 // Properties
2992 this.steps = [];
2994 // Initialization
2995 if ( step !== undefined ) {
2996 this.next( step, context );
3000 /* Setup */
3002 OO.initClass( OO.ui.Process );
3004 /* Methods */
3007 * Start the process.
3009 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3010 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3011 * process, the remaining steps will not be taken
3013 OO.ui.Process.prototype.execute = function () {
3014 var i, len, promise;
3017 * Continue execution.
3019 * @ignore
3020 * @param {Array} step A function and the context it should be called in
3021 * @return {Function} Function that continues the process
3023 function proceed( step ) {
3024 return function () {
3025 // Execute step in the correct context
3026 var deferred,
3027 result = step.callback.call( step.context );
3029 if ( result === false ) {
3030 // Use rejected promise for boolean false results
3031 return $.Deferred().reject( [] ).promise();
3033 if ( typeof result === 'number' ) {
3034 if ( result < 0 ) {
3035 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3037 // Use a delayed promise for numbers, expecting them to be in milliseconds
3038 deferred = $.Deferred();
3039 setTimeout( deferred.resolve, result );
3040 return deferred.promise();
3042 if ( result instanceof OO.ui.Error ) {
3043 // Use rejected promise for error
3044 return $.Deferred().reject( [ result ] ).promise();
3046 if ( $.isArray( result ) && result.length && result[0] instanceof OO.ui.Error ) {
3047 // Use rejected promise for list of errors
3048 return $.Deferred().reject( result ).promise();
3050 // Duck-type the object to see if it can produce a promise
3051 if ( result && $.isFunction( result.promise ) ) {
3052 // Use a promise generated from the result
3053 return result.promise();
3055 // Use resolved promise for other results
3056 return $.Deferred().resolve().promise();
3060 if ( this.steps.length ) {
3061 // Generate a chain reaction of promises
3062 promise = proceed( this.steps[0] )();
3063 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3064 promise = promise.then( proceed( this.steps[i] ) );
3066 } else {
3067 promise = $.Deferred().resolve().promise();
3070 return promise;
3074 * Create a process step.
3076 * @private
3077 * @param {number|jQuery.Promise|Function} step
3079 * - Number of milliseconds to wait; or
3080 * - Promise to wait to be resolved; or
3081 * - Function to execute
3082 * - If it returns boolean false the process will stop
3083 * - If it returns an object with a `promise` method the process will use the promise to either
3084 * continue to the next step when the promise is resolved or stop when the promise is rejected
3085 * - If it returns a number, the process will wait for that number of milliseconds before
3086 * proceeding
3087 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3088 * or a promise
3089 * @return {Object} Step object, with `callback` and `context` properties
3091 OO.ui.Process.prototype.createStep = function ( step, context ) {
3092 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3093 return {
3094 callback: function () {
3095 return step;
3097 context: null
3100 if ( $.isFunction( step ) ) {
3101 return {
3102 callback: step,
3103 context: context
3106 throw new Error( 'Cannot create process step: number, promise or function expected' );
3110 * Add step to the beginning of the process.
3112 * @inheritdoc #createStep
3113 * @return {OO.ui.Process} this
3114 * @chainable
3116 OO.ui.Process.prototype.first = function ( step, context ) {
3117 this.steps.unshift( this.createStep( step, context ) );
3118 return this;
3122 * Add step to the end of the process.
3124 * @inheritdoc #createStep
3125 * @return {OO.ui.Process} this
3126 * @chainable
3128 OO.ui.Process.prototype.next = function ( step, context ) {
3129 this.steps.push( this.createStep( step, context ) );
3130 return this;
3134 * Factory for tools.
3136 * @class
3137 * @extends OO.Factory
3138 * @constructor
3140 OO.ui.ToolFactory = function OoUiToolFactory() {
3141 // Parent constructor
3142 OO.ui.ToolFactory.super.call( this );
3145 /* Setup */
3147 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3149 /* Methods */
3151 /** */
3152 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3153 var i, len, included, promoted, demoted,
3154 auto = [],
3155 used = {};
3157 // Collect included and not excluded tools
3158 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3160 // Promotion
3161 promoted = this.extract( promote, used );
3162 demoted = this.extract( demote, used );
3164 // Auto
3165 for ( i = 0, len = included.length; i < len; i++ ) {
3166 if ( !used[included[i]] ) {
3167 auto.push( included[i] );
3171 return promoted.concat( auto ).concat( demoted );
3175 * Get a flat list of names from a list of names or groups.
3177 * Tools can be specified in the following ways:
3179 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3180 * - All tools in a group: `{ group: 'group-name' }`
3181 * - All tools: `'*'`
3183 * @private
3184 * @param {Array|string} collection List of tools
3185 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3186 * names will be added as properties
3187 * @return {string[]} List of extracted names
3189 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3190 var i, len, item, name, tool,
3191 names = [];
3193 if ( collection === '*' ) {
3194 for ( name in this.registry ) {
3195 tool = this.registry[name];
3196 if (
3197 // Only add tools by group name when auto-add is enabled
3198 tool.static.autoAddToCatchall &&
3199 // Exclude already used tools
3200 ( !used || !used[name] )
3202 names.push( name );
3203 if ( used ) {
3204 used[name] = true;
3208 } else if ( $.isArray( collection ) ) {
3209 for ( i = 0, len = collection.length; i < len; i++ ) {
3210 item = collection[i];
3211 // Allow plain strings as shorthand for named tools
3212 if ( typeof item === 'string' ) {
3213 item = { name: item };
3215 if ( OO.isPlainObject( item ) ) {
3216 if ( item.group ) {
3217 for ( name in this.registry ) {
3218 tool = this.registry[name];
3219 if (
3220 // Include tools with matching group
3221 tool.static.group === item.group &&
3222 // Only add tools by group name when auto-add is enabled
3223 tool.static.autoAddToGroup &&
3224 // Exclude already used tools
3225 ( !used || !used[name] )
3227 names.push( name );
3228 if ( used ) {
3229 used[name] = true;
3233 // Include tools with matching name and exclude already used tools
3234 } else if ( item.name && ( !used || !used[item.name] ) ) {
3235 names.push( item.name );
3236 if ( used ) {
3237 used[item.name] = true;
3243 return names;
3247 * Factory for tool groups.
3249 * @class
3250 * @extends OO.Factory
3251 * @constructor
3253 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3254 // Parent constructor
3255 OO.Factory.call( this );
3257 var i, l,
3258 defaultClasses = this.constructor.static.getDefaultClasses();
3260 // Register default toolgroups
3261 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3262 this.register( defaultClasses[i] );
3266 /* Setup */
3268 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3270 /* Static Methods */
3273 * Get a default set of classes to be registered on construction
3275 * @return {Function[]} Default classes
3277 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3278 return [
3279 OO.ui.BarToolGroup,
3280 OO.ui.ListToolGroup,
3281 OO.ui.MenuToolGroup
3286 * Element with a button.
3288 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3289 * and access keys for accessibility purposes.
3291 * @abstract
3292 * @class
3294 * @constructor
3295 * @param {jQuery} $button Button node, assigned to #$button
3296 * @param {Object} [config] Configuration options
3297 * @cfg {boolean} [framed=true] Render button with a frame
3298 * @cfg {number} [tabIndex=0] Button's tab index, use null to have no tabIndex
3299 * @cfg {string} [accessKey] Button's access key
3301 OO.ui.ButtonedElement = function OoUiButtonedElement( $button, config ) {
3302 // Configuration initialization
3303 config = config || {};
3305 // Properties
3306 this.$button = $button;
3307 this.tabIndex = null;
3308 this.framed = null;
3309 this.active = false;
3310 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
3312 // Events
3313 this.$button.on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
3315 // Initialization
3316 this.$element.addClass( 'oo-ui-buttonedElement' );
3317 this.$button
3318 .addClass( 'oo-ui-buttonedElement-button' )
3319 .attr( 'role', 'button' );
3320 this.setTabIndex( config.tabIndex || 0 );
3321 this.setAccessKey( config.accessKey );
3322 this.toggleFramed( config.framed === undefined || config.framed );
3325 /* Setup */
3327 OO.initClass( OO.ui.ButtonedElement );
3329 /* Static Properties */
3332 * Cancel mouse down events.
3334 * @static
3335 * @inheritable
3336 * @property {boolean}
3338 OO.ui.ButtonedElement.static.cancelButtonMouseDownEvents = true;
3340 /* Methods */
3343 * Handles mouse down events.
3345 * @param {jQuery.Event} e Mouse down event
3347 OO.ui.ButtonedElement.prototype.onMouseDown = function ( e ) {
3348 if ( this.isDisabled() || e.which !== 1 ) {
3349 return false;
3351 // tabIndex should generally be interacted with via the property, but it's not possible to
3352 // reliably unset a tabIndex via a property so we use the (lowercase) "tabindex" attribute
3353 this.tabIndex = this.$button.attr( 'tabindex' );
3354 this.$button
3355 // Remove the tab-index while the button is down to prevent the button from stealing focus
3356 .removeAttr( 'tabindex' )
3357 .addClass( 'oo-ui-buttonedElement-pressed' );
3358 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3359 // reliably reapply the tabindex and remove the pressed class
3360 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3361 // Prevent change of focus unless specifically configured otherwise
3362 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3363 return false;
3368 * Handles mouse up events.
3370 * @param {jQuery.Event} e Mouse up event
3372 OO.ui.ButtonedElement.prototype.onMouseUp = function ( e ) {
3373 if ( this.isDisabled() || e.which !== 1 ) {
3374 return false;
3376 this.$button
3377 // Restore the tab-index after the button is up to restore the button's accesssibility
3378 .attr( 'tabindex', this.tabIndex )
3379 .removeClass( 'oo-ui-buttonedElement-pressed' );
3380 // Stop listening for mouseup, since we only needed this once
3381 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3385 * Toggle frame.
3387 * @param {boolean} [framed] Make button framed, omit to toggle
3388 * @chainable
3390 OO.ui.ButtonedElement.prototype.toggleFramed = function ( framed ) {
3391 framed = framed === undefined ? !this.framed : !!framed;
3392 if ( framed !== this.framed ) {
3393 this.framed = framed;
3394 this.$element
3395 .toggleClass( 'oo-ui-buttonedElement-frameless', !framed )
3396 .toggleClass( 'oo-ui-buttonedElement-framed', framed );
3399 return this;
3403 * Set tab index.
3405 * @param {number|null} tabIndex Button's tab index, use null to remove
3406 * @chainable
3408 OO.ui.ButtonedElement.prototype.setTabIndex = function ( tabIndex ) {
3409 if ( typeof tabIndex === 'number' && tabIndex >= 0 ) {
3410 this.$button.attr( 'tabindex', tabIndex );
3411 } else {
3412 this.$button.removeAttr( 'tabindex' );
3414 return this;
3418 * Set access key
3420 * @param {string} accessKey Button's access key, use empty string to remove
3421 * @chainable
3423 OO.ui.ButtonedElement.prototype.setAccessKey = function ( accessKey ) {
3424 if ( typeof accessKey === 'string' && accessKey.length ) {
3425 this.$button.attr( 'accesskey', accessKey );
3426 } else {
3427 this.$button.removeAttr( 'accesskey' );
3429 return this;
3433 * Set active state.
3435 * @param {boolean} [value] Make button active
3436 * @chainable
3438 OO.ui.ButtonedElement.prototype.setActive = function ( value ) {
3439 this.$button.toggleClass( 'oo-ui-buttonedElement-active', !!value );
3440 return this;
3444 * Element that can be automatically clipped to visible boundaies.
3446 * @abstract
3447 * @class
3449 * @constructor
3450 * @param {jQuery} $clippable Nodes to clip, assigned to #$clippable
3451 * @param {Object} [config] Configuration options
3453 OO.ui.ClippableElement = function OoUiClippableElement( $clippable, config ) {
3454 // Configuration initialization
3455 config = config || {};
3457 // Properties
3458 this.$clippable = $clippable;
3459 this.clipping = false;
3460 this.clipped = false;
3461 this.$clippableContainer = null;
3462 this.$clippableScroller = null;
3463 this.$clippableWindow = null;
3464 this.idealWidth = null;
3465 this.idealHeight = null;
3466 this.onClippableContainerScrollHandler = OO.ui.bind( this.clip, this );
3467 this.onClippableWindowResizeHandler = OO.ui.bind( this.clip, this );
3469 // Initialization
3470 this.$clippable.addClass( 'oo-ui-clippableElement-clippable' );
3473 /* Methods */
3476 * Set clipping.
3478 * @param {boolean} value Enable clipping
3479 * @chainable
3481 OO.ui.ClippableElement.prototype.setClipping = function ( value ) {
3482 value = !!value;
3484 if ( this.clipping !== value ) {
3485 this.clipping = value;
3486 if ( this.clipping ) {
3487 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
3488 // If the clippable container is the body, we have to listen to scroll events and check
3489 // jQuery.scrollTop on the window because of browser inconsistencies
3490 this.$clippableScroller = this.$clippableContainer.is( 'body' ) ?
3491 this.$( OO.ui.Element.getWindow( this.$clippableContainer ) ) :
3492 this.$clippableContainer;
3493 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
3494 this.$clippableWindow = this.$( this.getElementWindow() )
3495 .on( 'resize', this.onClippableWindowResizeHandler );
3496 // Initial clip after visible
3497 setTimeout( OO.ui.bind( this.clip, this ) );
3498 } else {
3499 this.$clippableContainer = null;
3500 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
3501 this.$clippableScroller = null;
3502 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
3503 this.$clippableWindow = null;
3507 return this;
3511 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
3513 * @return {boolean} Element will be clipped to the visible area
3515 OO.ui.ClippableElement.prototype.isClipping = function () {
3516 return this.clipping;
3520 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
3522 * @return {boolean} Part of the element is being clipped
3524 OO.ui.ClippableElement.prototype.isClipped = function () {
3525 return this.clipped;
3529 * Set the ideal size.
3531 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
3532 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
3534 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
3535 this.idealWidth = width;
3536 this.idealHeight = height;
3540 * Clip element to visible boundaries and allow scrolling when needed.
3542 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
3543 * overlapped by, the visible area of the nearest scrollable container.
3545 * @chainable
3547 OO.ui.ClippableElement.prototype.clip = function () {
3548 if ( !this.clipping ) {
3549 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
3550 return this;
3553 var buffer = 10,
3554 cOffset = this.$clippable.offset(),
3555 $container = this.$clippableContainer.is( 'body' ) ? this.$clippableWindow : this.$clippableContainer,
3556 ccOffset = $container.offset() || { top: 0, left: 0 },
3557 ccHeight = $container.innerHeight() - buffer,
3558 ccWidth = $container.innerWidth() - buffer,
3559 scrollTop = this.$clippableScroller.scrollTop(),
3560 scrollLeft = this.$clippableScroller.scrollLeft(),
3561 desiredWidth = ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
3562 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
3563 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
3564 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
3565 clipWidth = desiredWidth < naturalWidth,
3566 clipHeight = desiredHeight < naturalHeight;
3568 if ( clipWidth ) {
3569 this.$clippable.css( { overflowX: 'auto', width: desiredWidth } );
3570 } else {
3571 this.$clippable.css( 'width', this.idealWidth || '' );
3572 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
3573 this.$clippable.css( 'overflowX', '' );
3575 if ( clipHeight ) {
3576 this.$clippable.css( { overflowY: 'auto', height: desiredHeight } );
3577 } else {
3578 this.$clippable.css( 'height', this.idealHeight || '' );
3579 this.$clippable.height(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
3580 this.$clippable.css( 'overflowY', '' );
3583 this.clipped = clipWidth || clipHeight;
3585 return this;
3589 * Element with named flags that can be added, removed, listed and checked.
3591 * A flag, when set, adds a CSS class on the `$element` by combing `oo-ui-flaggableElement-` with
3592 * the flag name. Flags are primarily useful for styling.
3594 * @abstract
3595 * @class
3597 * @constructor
3598 * @param {Object} [config] Configuration options
3599 * @cfg {string[]} [flags=[]] Styling flags, e.g. 'primary', 'destructive' or 'constructive'
3601 OO.ui.FlaggableElement = function OoUiFlaggableElement( config ) {
3602 // Config initialization
3603 config = config || {};
3605 // Properties
3606 this.flags = {};
3608 // Initialization
3609 this.setFlags( config.flags );
3612 /* Events */
3615 * @event flag
3616 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
3617 * added/removed properties
3620 /* Methods */
3623 * Check if a flag is set.
3625 * @param {string} flag Name of flag
3626 * @return {boolean} Has flag
3628 OO.ui.FlaggableElement.prototype.hasFlag = function ( flag ) {
3629 return flag in this.flags;
3633 * Get the names of all flags set.
3635 * @return {string[]} flags Flag names
3637 OO.ui.FlaggableElement.prototype.getFlags = function () {
3638 return Object.keys( this.flags );
3642 * Clear all flags.
3644 * @chainable
3645 * @fires flag
3647 OO.ui.FlaggableElement.prototype.clearFlags = function () {
3648 var flag,
3649 changes = {},
3650 classPrefix = 'oo-ui-flaggableElement-';
3652 for ( flag in this.flags ) {
3653 changes[flag] = false;
3654 delete this.flags[flag];
3655 this.$element.removeClass( classPrefix + flag );
3658 this.emit( 'flag', changes );
3660 return this;
3664 * Add one or more flags.
3666 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
3667 * keyed by flag name containing boolean set/remove instructions.
3668 * @chainable
3669 * @fires flag
3671 OO.ui.FlaggableElement.prototype.setFlags = function ( flags ) {
3672 var i, len, flag,
3673 changes = {},
3674 classPrefix = 'oo-ui-flaggableElement-';
3676 if ( typeof flags === 'string' ) {
3677 // Set
3678 this.flags[flags] = true;
3679 this.$element.addClass( classPrefix + flags );
3680 } else if ( $.isArray( flags ) ) {
3681 for ( i = 0, len = flags.length; i < len; i++ ) {
3682 flag = flags[i];
3683 // Set
3684 changes[flag] = true;
3685 this.flags[flag] = true;
3686 this.$element.addClass( classPrefix + flag );
3688 } else if ( OO.isPlainObject( flags ) ) {
3689 for ( flag in flags ) {
3690 if ( flags[flag] ) {
3691 // Set
3692 changes[flag] = true;
3693 this.flags[flag] = true;
3694 this.$element.addClass( classPrefix + flag );
3695 } else {
3696 // Remove
3697 changes[flag] = false;
3698 delete this.flags[flag];
3699 this.$element.removeClass( classPrefix + flag );
3704 this.emit( 'flag', changes );
3706 return this;
3710 * Element containing a sequence of child elements.
3712 * @abstract
3713 * @class
3715 * @constructor
3716 * @param {jQuery} $group Container node, assigned to #$group
3717 * @param {Object} [config] Configuration options
3719 OO.ui.GroupElement = function OoUiGroupElement( $group, config ) {
3720 // Configuration
3721 config = config || {};
3723 // Properties
3724 this.$group = $group;
3725 this.items = [];
3726 this.aggregateItemEvents = {};
3729 /* Methods */
3732 * Get items.
3734 * @return {OO.ui.Element[]} Items
3736 OO.ui.GroupElement.prototype.getItems = function () {
3737 return this.items.slice( 0 );
3741 * Add an aggregate item event.
3743 * Aggregated events are listened to on each item and then emitted by the group under a new name,
3744 * and with an additional leading parameter containing the item that emitted the original event.
3745 * Other arguments that were emitted from the original event are passed through.
3747 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
3748 * event, use null value to remove aggregation
3749 * @throws {Error} If aggregation already exists
3751 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
3752 var i, len, item, add, remove, itemEvent, groupEvent;
3754 for ( itemEvent in events ) {
3755 groupEvent = events[itemEvent];
3757 // Remove existing aggregated event
3758 if ( itemEvent in this.aggregateItemEvents ) {
3759 // Don't allow duplicate aggregations
3760 if ( groupEvent ) {
3761 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
3763 // Remove event aggregation from existing items
3764 for ( i = 0, len = this.items.length; i < len; i++ ) {
3765 item = this.items[i];
3766 if ( item.connect && item.disconnect ) {
3767 remove = {};
3768 remove[itemEvent] = [ 'emit', groupEvent, item ];
3769 item.disconnect( this, remove );
3772 // Prevent future items from aggregating event
3773 delete this.aggregateItemEvents[itemEvent];
3776 // Add new aggregate event
3777 if ( groupEvent ) {
3778 // Make future items aggregate event
3779 this.aggregateItemEvents[itemEvent] = groupEvent;
3780 // Add event aggregation to existing items
3781 for ( i = 0, len = this.items.length; i < len; i++ ) {
3782 item = this.items[i];
3783 if ( item.connect && item.disconnect ) {
3784 add = {};
3785 add[itemEvent] = [ 'emit', groupEvent, item ];
3786 item.connect( this, add );
3794 * Add items.
3796 * @param {OO.ui.Element[]} items Item
3797 * @param {number} [index] Index to insert items at
3798 * @chainable
3800 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
3801 var i, len, item, event, events, currentIndex,
3802 itemElements = [];
3804 for ( i = 0, len = items.length; i < len; i++ ) {
3805 item = items[i];
3807 // Check if item exists then remove it first, effectively "moving" it
3808 currentIndex = $.inArray( item, this.items );
3809 if ( currentIndex >= 0 ) {
3810 this.removeItems( [ item ] );
3811 // Adjust index to compensate for removal
3812 if ( currentIndex < index ) {
3813 index--;
3816 // Add the item
3817 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
3818 events = {};
3819 for ( event in this.aggregateItemEvents ) {
3820 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
3822 item.connect( this, events );
3824 item.setElementGroup( this );
3825 itemElements.push( item.$element.get( 0 ) );
3828 if ( index === undefined || index < 0 || index >= this.items.length ) {
3829 this.$group.append( itemElements );
3830 this.items.push.apply( this.items, items );
3831 } else if ( index === 0 ) {
3832 this.$group.prepend( itemElements );
3833 this.items.unshift.apply( this.items, items );
3834 } else {
3835 this.items[index].$element.before( itemElements );
3836 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
3839 return this;
3843 * Remove items.
3845 * Items will be detached, not removed, so they can be used later.
3847 * @param {OO.ui.Element[]} items Items to remove
3848 * @chainable
3850 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
3851 var i, len, item, index, remove, itemEvent;
3853 // Remove specific items
3854 for ( i = 0, len = items.length; i < len; i++ ) {
3855 item = items[i];
3856 index = $.inArray( item, this.items );
3857 if ( index !== -1 ) {
3858 if (
3859 item.connect && item.disconnect &&
3860 !$.isEmptyObject( this.aggregateItemEvents )
3862 remove = {};
3863 if ( itemEvent in this.aggregateItemEvents ) {
3864 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
3866 item.disconnect( this, remove );
3868 item.setElementGroup( null );
3869 this.items.splice( index, 1 );
3870 item.$element.detach();
3874 return this;
3878 * Clear all items.
3880 * Items will be detached, not removed, so they can be used later.
3882 * @chainable
3884 OO.ui.GroupElement.prototype.clearItems = function () {
3885 var i, len, item, remove, itemEvent;
3887 // Remove all items
3888 for ( i = 0, len = this.items.length; i < len; i++ ) {
3889 item = this.items[i];
3890 if (
3891 item.connect && item.disconnect &&
3892 !$.isEmptyObject( this.aggregateItemEvents )
3894 remove = {};
3895 if ( itemEvent in this.aggregateItemEvents ) {
3896 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
3898 item.disconnect( this, remove );
3900 item.setElementGroup( null );
3901 item.$element.detach();
3904 this.items = [];
3905 return this;
3909 * Element containing an icon.
3911 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
3912 * a control or convey information in a more space efficient way. Icons should rarely be used
3913 * without labels; such as in a toolbar where space is at a premium or within a context where the
3914 * meaning is very clear to the user.
3916 * @abstract
3917 * @class
3919 * @constructor
3920 * @param {jQuery} $icon Icon node, assigned to #$icon
3921 * @param {Object} [config] Configuration options
3922 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
3923 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3924 * language
3926 OO.ui.IconedElement = function OoUiIconedElement( $icon, config ) {
3927 // Config intialization
3928 config = config || {};
3930 // Properties
3931 this.$icon = $icon;
3932 this.icon = null;
3934 // Initialization
3935 this.$icon.addClass( 'oo-ui-iconedElement-icon' );
3936 this.setIcon( config.icon || this.constructor.static.icon );
3939 /* Setup */
3941 OO.initClass( OO.ui.IconedElement );
3943 /* Static Properties */
3946 * Icon.
3948 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
3950 * For i18n purposes, this property can be an object containing a `default` icon name property and
3951 * additional icon names keyed by language code.
3953 * Example of i18n icon definition:
3954 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
3956 * @static
3957 * @inheritable
3958 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
3959 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3960 * language
3962 OO.ui.IconedElement.static.icon = null;
3964 /* Methods */
3967 * Set icon.
3969 * @param {Object|string} icon Symbolic icon name, or map of icon names keyed by language ID;
3970 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3971 * language
3972 * @chainable
3974 OO.ui.IconedElement.prototype.setIcon = function ( icon ) {
3975 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
3977 if ( this.icon ) {
3978 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
3980 if ( typeof icon === 'string' ) {
3981 icon = icon.trim();
3982 if ( icon.length ) {
3983 this.$icon.addClass( 'oo-ui-icon-' + icon );
3984 this.icon = icon;
3987 this.$element.toggleClass( 'oo-ui-iconedElement', !!this.icon );
3989 return this;
3993 * Get icon.
3995 * @return {string} Icon
3997 OO.ui.IconedElement.prototype.getIcon = function () {
3998 return this.icon;
4002 * Element containing an indicator.
4004 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4005 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4006 * instead of performing an action directly, or an item in a list which has errors that need to be
4007 * resolved.
4009 * @abstract
4010 * @class
4012 * @constructor
4013 * @param {jQuery} $indicator Indicator node, assigned to #$indicator
4014 * @param {Object} [config] Configuration options
4015 * @cfg {string} [indicator] Symbolic indicator name
4016 * @cfg {string} [indicatorTitle] Indicator title text or a function that return text
4018 OO.ui.IndicatedElement = function OoUiIndicatedElement( $indicator, config ) {
4019 // Config intialization
4020 config = config || {};
4022 // Properties
4023 this.$indicator = $indicator;
4024 this.indicator = null;
4025 this.indicatorLabel = null;
4027 // Initialization
4028 this.$indicator.addClass( 'oo-ui-indicatedElement-indicator' );
4029 this.setIndicator( config.indicator || this.constructor.static.indicator );
4030 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4033 /* Setup */
4035 OO.initClass( OO.ui.IndicatedElement );
4037 /* Static Properties */
4040 * indicator.
4042 * @static
4043 * @inheritable
4044 * @property {string|null} Symbolic indicator name or null for no indicator
4046 OO.ui.IndicatedElement.static.indicator = null;
4049 * Indicator title.
4051 * @static
4052 * @inheritable
4053 * @property {string|Function|null} Indicator title text, a function that return text or null for no
4054 * indicator title
4056 OO.ui.IndicatedElement.static.indicatorTitle = null;
4058 /* Methods */
4061 * Set indicator.
4063 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4064 * @chainable
4066 OO.ui.IndicatedElement.prototype.setIndicator = function ( indicator ) {
4067 if ( this.indicator ) {
4068 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4069 this.indicator = null;
4071 if ( typeof indicator === 'string' ) {
4072 indicator = indicator.trim();
4073 if ( indicator.length ) {
4074 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4075 this.indicator = indicator;
4078 this.$element.toggleClass( 'oo-ui-indicatedElement', !!this.indicator );
4080 return this;
4084 * Set indicator label.
4086 * @param {string|Function|null} indicator Indicator title text, a function that return text or null
4087 * for no indicator title
4088 * @chainable
4090 OO.ui.IndicatedElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4091 this.indicatorTitle = indicatorTitle = OO.ui.resolveMsg( indicatorTitle );
4093 if ( typeof indicatorTitle === 'string' && indicatorTitle.length ) {
4094 this.$indicator.attr( 'title', indicatorTitle );
4095 } else {
4096 this.$indicator.removeAttr( 'title' );
4099 return this;
4103 * Get indicator.
4105 * @return {string} title Symbolic name of indicator
4107 OO.ui.IndicatedElement.prototype.getIndicator = function () {
4108 return this.indicator;
4112 * Get indicator title.
4114 * @return {string} Indicator title text
4116 OO.ui.IndicatedElement.prototype.getIndicatorTitle = function () {
4117 return this.indicatorTitle;
4121 * Element containing a label.
4123 * @abstract
4124 * @class
4126 * @constructor
4127 * @param {jQuery} $label Label node, assigned to #$label
4128 * @param {Object} [config] Configuration options
4129 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4130 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4132 OO.ui.LabeledElement = function OoUiLabeledElement( $label, config ) {
4133 // Config intialization
4134 config = config || {};
4136 // Properties
4137 this.$label = $label;
4138 this.label = null;
4140 // Initialization
4141 this.$label.addClass( 'oo-ui-labeledElement-label' );
4142 this.setLabel( config.label || this.constructor.static.label );
4143 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4146 /* Setup */
4148 OO.initClass( OO.ui.LabeledElement );
4150 /* Static Properties */
4153 * Label.
4155 * @static
4156 * @inheritable
4157 * @property {string|Function|null} Label text; a function that returns a nodes or text; or null for
4158 * no label
4160 OO.ui.LabeledElement.static.label = null;
4162 /* Methods */
4165 * Set the label.
4167 * An empty string will result in the label being hidden. A string containing only whitespace will
4168 * be converted to a single &nbsp;
4170 * @param {jQuery|string|Function|null} label Label nodes; text; a function that retuns nodes or
4171 * text; or null for no label
4172 * @chainable
4174 OO.ui.LabeledElement.prototype.setLabel = function ( label ) {
4175 var empty = false;
4177 this.label = label = OO.ui.resolveMsg( label ) || null;
4178 if ( typeof label === 'string' && label.length ) {
4179 if ( label.match( /^\s*$/ ) ) {
4180 // Convert whitespace only string to a single non-breaking space
4181 this.$label.html( '&nbsp;' );
4182 } else {
4183 this.$label.text( label );
4185 } else if ( label instanceof jQuery ) {
4186 this.$label.empty().append( label );
4187 } else {
4188 this.$label.empty();
4189 empty = true;
4191 this.$element.toggleClass( 'oo-ui-labeledElement', !empty );
4192 this.$label.css( 'display', empty ? 'none' : '' );
4194 return this;
4198 * Get the label.
4200 * @return {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4201 * text; or null for no label
4203 OO.ui.LabeledElement.prototype.getLabel = function () {
4204 return this.label;
4208 * Fit the label.
4210 * @chainable
4212 OO.ui.LabeledElement.prototype.fitLabel = function () {
4213 if ( this.$label.autoEllipsis && this.autoFitLabel ) {
4214 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
4216 return this;
4220 * Element containing an OO.ui.PopupWidget object.
4222 * @abstract
4223 * @class
4225 * @constructor
4226 * @param {Object} [config] Configuration options
4227 * @cfg {Object} [popup] Configuration to pass to popup
4228 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
4230 OO.ui.PopuppableElement = function OoUiPopuppableElement( config ) {
4231 // Configuration initialization
4232 config = config || {};
4234 // Properties
4235 this.popup = new OO.ui.PopupWidget( $.extend(
4236 { autoClose: true },
4237 config.popup,
4238 { $: this.$, $autoCloseIgnore: this.$element }
4239 ) );
4242 /* Methods */
4245 * Get popup.
4247 * @return {OO.ui.PopupWidget} Popup widget
4249 OO.ui.PopuppableElement.prototype.getPopup = function () {
4250 return this.popup;
4254 * Element with a title.
4256 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
4257 * not visible on touch devices.
4259 * @abstract
4260 * @class
4262 * @constructor
4263 * @param {jQuery} $label Titled node, assigned to #$titled
4264 * @param {Object} [config] Configuration options
4265 * @cfg {string|Function} [title] Title text or a function that returns text
4267 OO.ui.TitledElement = function OoUiTitledElement( $titled, config ) {
4268 // Config intialization
4269 config = config || {};
4271 // Properties
4272 this.$titled = $titled;
4273 this.title = null;
4275 // Initialization
4276 this.setTitle( config.title || this.constructor.static.title );
4279 /* Setup */
4281 OO.initClass( OO.ui.TitledElement );
4283 /* Static Properties */
4286 * Title.
4288 * @static
4289 * @inheritable
4290 * @property {string|Function} Title text or a function that returns text
4292 OO.ui.TitledElement.static.title = null;
4294 /* Methods */
4297 * Set title.
4299 * @param {string|Function|null} title Title text, a function that returns text or null for no title
4300 * @chainable
4302 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
4303 this.title = title = OO.ui.resolveMsg( title ) || null;
4305 if ( typeof title === 'string' && title.length ) {
4306 this.$titled.attr( 'title', title );
4307 } else {
4308 this.$titled.removeAttr( 'title' );
4311 return this;
4315 * Get title.
4317 * @return {string} Title string
4319 OO.ui.TitledElement.prototype.getTitle = function () {
4320 return this.title;
4324 * Generic toolbar tool.
4326 * @abstract
4327 * @class
4328 * @extends OO.ui.Widget
4329 * @mixins OO.ui.IconedElement
4331 * @constructor
4332 * @param {OO.ui.ToolGroup} toolGroup
4333 * @param {Object} [config] Configuration options
4334 * @cfg {string|Function} [title] Title text or a function that returns text
4336 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
4337 // Config intialization
4338 config = config || {};
4340 // Parent constructor
4341 OO.ui.Tool.super.call( this, config );
4343 // Mixin constructors
4344 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
4346 // Properties
4347 this.toolGroup = toolGroup;
4348 this.toolbar = this.toolGroup.getToolbar();
4349 this.active = false;
4350 this.$title = this.$( '<span>' );
4351 this.$link = this.$( '<a>' );
4352 this.title = null;
4354 // Events
4355 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
4357 // Initialization
4358 this.$title.addClass( 'oo-ui-tool-title' );
4359 this.$link
4360 .addClass( 'oo-ui-tool-link' )
4361 .append( this.$icon, this.$title )
4362 .prop( 'tabIndex', 0 )
4363 .attr( 'role', 'button' );
4364 this.$element
4365 .data( 'oo-ui-tool', this )
4366 .addClass(
4367 'oo-ui-tool ' + 'oo-ui-tool-name-' +
4368 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
4370 .append( this.$link );
4371 this.setTitle( config.title || this.constructor.static.title );
4374 /* Setup */
4376 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
4377 OO.mixinClass( OO.ui.Tool, OO.ui.IconedElement );
4379 /* Events */
4382 * @event select
4385 /* Static Properties */
4388 * @static
4389 * @inheritdoc
4391 OO.ui.Tool.static.tagName = 'span';
4394 * Symbolic name of tool.
4396 * @abstract
4397 * @static
4398 * @inheritable
4399 * @property {string}
4401 OO.ui.Tool.static.name = '';
4404 * Tool group.
4406 * @abstract
4407 * @static
4408 * @inheritable
4409 * @property {string}
4411 OO.ui.Tool.static.group = '';
4414 * Tool title.
4416 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
4417 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
4418 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
4419 * appended to the title if the tool is part of a bar tool group.
4421 * @abstract
4422 * @static
4423 * @inheritable
4424 * @property {string|Function} Title text or a function that returns text
4426 OO.ui.Tool.static.title = '';
4429 * Tool can be automatically added to catch-all groups.
4431 * @static
4432 * @inheritable
4433 * @property {boolean}
4435 OO.ui.Tool.static.autoAddToCatchall = true;
4438 * Tool can be automatically added to named groups.
4440 * @static
4441 * @property {boolean}
4442 * @inheritable
4444 OO.ui.Tool.static.autoAddToGroup = true;
4447 * Check if this tool is compatible with given data.
4449 * @static
4450 * @inheritable
4451 * @param {Mixed} data Data to check
4452 * @return {boolean} Tool can be used with data
4454 OO.ui.Tool.static.isCompatibleWith = function () {
4455 return false;
4458 /* Methods */
4461 * Handle the toolbar state being updated.
4463 * This is an abstract method that must be overridden in a concrete subclass.
4465 * @abstract
4467 OO.ui.Tool.prototype.onUpdateState = function () {
4468 throw new Error(
4469 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
4474 * Handle the tool being selected.
4476 * This is an abstract method that must be overridden in a concrete subclass.
4478 * @abstract
4480 OO.ui.Tool.prototype.onSelect = function () {
4481 throw new Error(
4482 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
4487 * Check if the button is active.
4489 * @param {boolean} Button is active
4491 OO.ui.Tool.prototype.isActive = function () {
4492 return this.active;
4496 * Make the button appear active or inactive.
4498 * @param {boolean} state Make button appear active
4500 OO.ui.Tool.prototype.setActive = function ( state ) {
4501 this.active = !!state;
4502 if ( this.active ) {
4503 this.$element.addClass( 'oo-ui-tool-active' );
4504 } else {
4505 this.$element.removeClass( 'oo-ui-tool-active' );
4510 * Get the tool title.
4512 * @param {string|Function} title Title text or a function that returns text
4513 * @chainable
4515 OO.ui.Tool.prototype.setTitle = function ( title ) {
4516 this.title = OO.ui.resolveMsg( title );
4517 this.updateTitle();
4518 return this;
4522 * Get the tool title.
4524 * @return {string} Title text
4526 OO.ui.Tool.prototype.getTitle = function () {
4527 return this.title;
4531 * Get the tool's symbolic name.
4533 * @return {string} Symbolic name of tool
4535 OO.ui.Tool.prototype.getName = function () {
4536 return this.constructor.static.name;
4540 * Update the title.
4542 OO.ui.Tool.prototype.updateTitle = function () {
4543 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
4544 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
4545 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
4546 tooltipParts = [];
4548 this.$title.empty()
4549 .text( this.title )
4550 .append(
4551 this.$( '<span>' )
4552 .addClass( 'oo-ui-tool-accel' )
4553 .text( accel )
4556 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
4557 tooltipParts.push( this.title );
4559 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
4560 tooltipParts.push( accel );
4562 if ( tooltipParts.length ) {
4563 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
4564 } else {
4565 this.$link.removeAttr( 'title' );
4570 * Destroy tool.
4572 OO.ui.Tool.prototype.destroy = function () {
4573 this.toolbar.disconnect( this );
4574 this.$element.remove();
4578 * Collection of tool groups.
4580 * @class
4581 * @extends OO.ui.Element
4582 * @mixins OO.EventEmitter
4583 * @mixins OO.ui.GroupElement
4585 * @constructor
4586 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
4587 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
4588 * @param {Object} [config] Configuration options
4589 * @cfg {boolean} [actions] Add an actions section opposite to the tools
4590 * @cfg {boolean} [shadow] Add a shadow below the toolbar
4592 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
4593 // Configuration initialization
4594 config = config || {};
4596 // Parent constructor
4597 OO.ui.Toolbar.super.call( this, config );
4599 // Mixin constructors
4600 OO.EventEmitter.call( this );
4601 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
4603 // Properties
4604 this.toolFactory = toolFactory;
4605 this.toolGroupFactory = toolGroupFactory;
4606 this.groups = [];
4607 this.tools = {};
4608 this.$bar = this.$( '<div>' );
4609 this.$actions = this.$( '<div>' );
4610 this.initialized = false;
4612 // Events
4613 this.$element
4614 .add( this.$bar ).add( this.$group ).add( this.$actions )
4615 .on( 'mousedown touchstart', OO.ui.bind( this.onPointerDown, this ) );
4617 // Initialization
4618 this.$group.addClass( 'oo-ui-toolbar-tools' );
4619 this.$bar.addClass( 'oo-ui-toolbar-bar' ).append( this.$group );
4620 if ( config.actions ) {
4621 this.$actions.addClass( 'oo-ui-toolbar-actions' );
4622 this.$bar.append( this.$actions );
4624 this.$bar.append( '<div style="clear:both"></div>' );
4625 if ( config.shadow ) {
4626 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
4628 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
4631 /* Setup */
4633 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
4634 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
4635 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
4637 /* Methods */
4640 * Get the tool factory.
4642 * @return {OO.ui.ToolFactory} Tool factory
4644 OO.ui.Toolbar.prototype.getToolFactory = function () {
4645 return this.toolFactory;
4649 * Get the tool group factory.
4651 * @return {OO.Factory} Tool group factory
4653 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
4654 return this.toolGroupFactory;
4658 * Handles mouse down events.
4660 * @param {jQuery.Event} e Mouse down event
4662 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
4663 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
4664 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
4665 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
4666 return false;
4671 * Sets up handles and preloads required information for the toolbar to work.
4672 * This must be called immediately after it is attached to a visible document.
4674 OO.ui.Toolbar.prototype.initialize = function () {
4675 this.initialized = true;
4679 * Setup toolbar.
4681 * Tools can be specified in the following ways:
4683 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4684 * - All tools in a group: `{ group: 'group-name' }`
4685 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
4687 * @param {Object.<string,Array>} groups List of tool group configurations
4688 * @param {Array|string} [groups.include] Tools to include
4689 * @param {Array|string} [groups.exclude] Tools to exclude
4690 * @param {Array|string} [groups.promote] Tools to promote to the beginning
4691 * @param {Array|string} [groups.demote] Tools to demote to the end
4693 OO.ui.Toolbar.prototype.setup = function ( groups ) {
4694 var i, len, type, group,
4695 items = [],
4696 defaultType = 'bar';
4698 // Cleanup previous groups
4699 this.reset();
4701 // Build out new groups
4702 for ( i = 0, len = groups.length; i < len; i++ ) {
4703 group = groups[i];
4704 if ( group.include === '*' ) {
4705 // Apply defaults to catch-all groups
4706 if ( group.type === undefined ) {
4707 group.type = 'list';
4709 if ( group.label === undefined ) {
4710 group.label = 'ooui-toolbar-more';
4713 // Check type has been registered
4714 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
4715 items.push(
4716 this.getToolGroupFactory().create( type, this, $.extend( { $: this.$ }, group ) )
4719 this.addItems( items );
4723 * Remove all tools and groups from the toolbar.
4725 OO.ui.Toolbar.prototype.reset = function () {
4726 var i, len;
4728 this.groups = [];
4729 this.tools = {};
4730 for ( i = 0, len = this.items.length; i < len; i++ ) {
4731 this.items[i].destroy();
4733 this.clearItems();
4737 * Destroys toolbar, removing event handlers and DOM elements.
4739 * Call this whenever you are done using a toolbar.
4741 OO.ui.Toolbar.prototype.destroy = function () {
4742 this.reset();
4743 this.$element.remove();
4747 * Check if tool has not been used yet.
4749 * @param {string} name Symbolic name of tool
4750 * @return {boolean} Tool is available
4752 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
4753 return !this.tools[name];
4757 * Prevent tool from being used again.
4759 * @param {OO.ui.Tool} tool Tool to reserve
4761 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
4762 this.tools[tool.getName()] = tool;
4766 * Allow tool to be used again.
4768 * @param {OO.ui.Tool} tool Tool to release
4770 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
4771 delete this.tools[tool.getName()];
4775 * Get accelerator label for tool.
4777 * This is a stub that should be overridden to provide access to accelerator information.
4779 * @param {string} name Symbolic name of tool
4780 * @return {string|undefined} Tool accelerator label if available
4782 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
4783 return undefined;
4787 * Collection of tools.
4789 * Tools can be specified in the following ways:
4791 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
4792 * - All tools in a group: `{ group: 'group-name' }`
4793 * - All tools: `'*'`
4795 * @abstract
4796 * @class
4797 * @extends OO.ui.Widget
4798 * @mixins OO.ui.GroupElement
4800 * @constructor
4801 * @param {OO.ui.Toolbar} toolbar
4802 * @param {Object} [config] Configuration options
4803 * @cfg {Array|string} [include=[]] List of tools to include
4804 * @cfg {Array|string} [exclude=[]] List of tools to exclude
4805 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
4806 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
4808 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
4809 // Configuration initialization
4810 config = config || {};
4812 // Parent constructor
4813 OO.ui.ToolGroup.super.call( this, config );
4815 // Mixin constructors
4816 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
4818 // Properties
4819 this.toolbar = toolbar;
4820 this.tools = {};
4821 this.pressed = null;
4822 this.autoDisabled = false;
4823 this.include = config.include || [];
4824 this.exclude = config.exclude || [];
4825 this.promote = config.promote || [];
4826 this.demote = config.demote || [];
4827 this.onCapturedMouseUpHandler = OO.ui.bind( this.onCapturedMouseUp, this );
4829 // Events
4830 this.$element.on( {
4831 'mousedown touchstart': OO.ui.bind( this.onPointerDown, this ),
4832 'mouseup touchend': OO.ui.bind( this.onPointerUp, this ),
4833 mouseover: OO.ui.bind( this.onMouseOver, this ),
4834 mouseout: OO.ui.bind( this.onMouseOut, this )
4835 } );
4836 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
4837 this.aggregate( { disable: 'itemDisable' } );
4838 this.connect( this, { itemDisable: 'updateDisabled' } );
4840 // Initialization
4841 this.$group.addClass( 'oo-ui-toolGroup-tools' );
4842 this.$element
4843 .addClass( 'oo-ui-toolGroup' )
4844 .append( this.$group );
4845 this.populate();
4848 /* Setup */
4850 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
4851 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
4853 /* Events */
4856 * @event update
4859 /* Static Properties */
4862 * Show labels in tooltips.
4864 * @static
4865 * @inheritable
4866 * @property {boolean}
4868 OO.ui.ToolGroup.static.titleTooltips = false;
4871 * Show acceleration labels in tooltips.
4873 * @static
4874 * @inheritable
4875 * @property {boolean}
4877 OO.ui.ToolGroup.static.accelTooltips = false;
4880 * Automatically disable the toolgroup when all tools are disabled
4882 * @static
4883 * @inheritable
4884 * @property {boolean}
4886 OO.ui.ToolGroup.static.autoDisable = true;
4888 /* Methods */
4891 * @inheritdoc
4893 OO.ui.ToolGroup.prototype.isDisabled = function () {
4894 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
4898 * @inheritdoc
4900 OO.ui.ToolGroup.prototype.updateDisabled = function () {
4901 var i, item, allDisabled = true;
4903 if ( this.constructor.static.autoDisable ) {
4904 for ( i = this.items.length - 1; i >= 0; i-- ) {
4905 item = this.items[i];
4906 if ( !item.isDisabled() ) {
4907 allDisabled = false;
4908 break;
4911 this.autoDisabled = allDisabled;
4913 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
4917 * Handle mouse down events.
4919 * @param {jQuery.Event} e Mouse down event
4921 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
4922 // e.which is 0 for touch events, 1 for left mouse button
4923 if ( !this.isDisabled() && e.which <= 1 ) {
4924 this.pressed = this.getTargetTool( e );
4925 if ( this.pressed ) {
4926 this.pressed.setActive( true );
4927 this.getElementDocument().addEventListener(
4928 'mouseup', this.onCapturedMouseUpHandler, true
4932 return false;
4936 * Handle captured mouse up events.
4938 * @param {Event} e Mouse up event
4940 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
4941 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
4942 // onPointerUp may be called a second time, depending on where the mouse is when the button is
4943 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
4944 this.onPointerUp( e );
4948 * Handle mouse up events.
4950 * @param {jQuery.Event} e Mouse up event
4952 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
4953 var tool = this.getTargetTool( e );
4955 // e.which is 0 for touch events, 1 for left mouse button
4956 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
4957 this.pressed.onSelect();
4960 this.pressed = null;
4961 return false;
4965 * Handle mouse over events.
4967 * @param {jQuery.Event} e Mouse over event
4969 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
4970 var tool = this.getTargetTool( e );
4972 if ( this.pressed && this.pressed === tool ) {
4973 this.pressed.setActive( true );
4978 * Handle mouse out events.
4980 * @param {jQuery.Event} e Mouse out event
4982 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
4983 var tool = this.getTargetTool( e );
4985 if ( this.pressed && this.pressed === tool ) {
4986 this.pressed.setActive( false );
4991 * Get the closest tool to a jQuery.Event.
4993 * Only tool links are considered, which prevents other elements in the tool such as popups from
4994 * triggering tool group interactions.
4996 * @private
4997 * @param {jQuery.Event} e
4998 * @return {OO.ui.Tool|null} Tool, `null` if none was found
5000 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
5001 var tool,
5002 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
5004 if ( $item.length ) {
5005 tool = $item.parent().data( 'oo-ui-tool' );
5008 return tool && !tool.isDisabled() ? tool : null;
5012 * Handle tool registry register events.
5014 * If a tool is registered after the group is created, we must repopulate the list to account for:
5016 * - a tool being added that may be included
5017 * - a tool already included being overridden
5019 * @param {string} name Symbolic name of tool
5021 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
5022 this.populate();
5026 * Get the toolbar this group is in.
5028 * @return {OO.ui.Toolbar} Toolbar of group
5030 OO.ui.ToolGroup.prototype.getToolbar = function () {
5031 return this.toolbar;
5035 * Add and remove tools based on configuration.
5037 OO.ui.ToolGroup.prototype.populate = function () {
5038 var i, len, name, tool,
5039 toolFactory = this.toolbar.getToolFactory(),
5040 names = {},
5041 add = [],
5042 remove = [],
5043 list = this.toolbar.getToolFactory().getTools(
5044 this.include, this.exclude, this.promote, this.demote
5047 // Build a list of needed tools
5048 for ( i = 0, len = list.length; i < len; i++ ) {
5049 name = list[i];
5050 if (
5051 // Tool exists
5052 toolFactory.lookup( name ) &&
5053 // Tool is available or is already in this group
5054 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
5056 tool = this.tools[name];
5057 if ( !tool ) {
5058 // Auto-initialize tools on first use
5059 this.tools[name] = tool = toolFactory.create( name, this );
5060 tool.updateTitle();
5062 this.toolbar.reserveTool( tool );
5063 add.push( tool );
5064 names[name] = true;
5067 // Remove tools that are no longer needed
5068 for ( name in this.tools ) {
5069 if ( !names[name] ) {
5070 this.tools[name].destroy();
5071 this.toolbar.releaseTool( this.tools[name] );
5072 remove.push( this.tools[name] );
5073 delete this.tools[name];
5076 if ( remove.length ) {
5077 this.removeItems( remove );
5079 // Update emptiness state
5080 if ( add.length ) {
5081 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
5082 } else {
5083 this.$element.addClass( 'oo-ui-toolGroup-empty' );
5085 // Re-add tools (moving existing ones to new locations)
5086 this.addItems( add );
5087 // Disabled state may depend on items
5088 this.updateDisabled();
5092 * Destroy tool group.
5094 OO.ui.ToolGroup.prototype.destroy = function () {
5095 var name;
5097 this.clearItems();
5098 this.toolbar.getToolFactory().disconnect( this );
5099 for ( name in this.tools ) {
5100 this.toolbar.releaseTool( this.tools[name] );
5101 this.tools[name].disconnect( this ).destroy();
5102 delete this.tools[name];
5104 this.$element.remove();
5108 * Dialog for showing a message.
5110 * User interface:
5111 * - Registers two actions by default (safe and primary).
5112 * - Renders action widgets in the footer.
5114 * @class
5115 * @extends OO.ui.Dialog
5117 * @constructor
5118 * @param {Object} [config] Configuration options
5120 OO.ui.MessageDialog = function OoUiMessageDialog( manager, config ) {
5121 // Parent constructor
5122 OO.ui.MessageDialog.super.call( this, manager, config );
5124 // Properties
5125 this.verticalActionLayout = null;
5127 // Initialization
5128 this.$element.addClass( 'oo-ui-messageDialog' );
5131 /* Inheritance */
5133 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
5135 /* Static Properties */
5137 OO.ui.MessageDialog.static.name = 'message';
5139 OO.ui.MessageDialog.static.size = 'small';
5141 OO.ui.MessageDialog.static.verbose = false;
5144 * Dialog title.
5146 * A confirmation dialog's title should describe what the progressive action will do. An alert
5147 * dialog's title should describe what event occured.
5149 * @static
5150 * inheritable
5151 * @property {jQuery|string|Function|null}
5153 OO.ui.MessageDialog.static.title = null;
5156 * A confirmation dialog's message should describe the consequences of the progressive action. An
5157 * alert dialog's message should describe why the event occured.
5159 * @static
5160 * inheritable
5161 * @property {jQuery|string|Function|null}
5163 OO.ui.MessageDialog.static.message = null;
5165 OO.ui.MessageDialog.static.actions = [
5166 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
5167 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
5170 /* Methods */
5173 * @inheritdoc
5175 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
5176 this.fitActions();
5177 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
5181 * Toggle action layout between vertical and horizontal.
5183 * @param {boolean} [value] Layout actions vertically, omit to toggle
5184 * @chainable
5186 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
5187 value = value === undefined ? !this.verticalActionLayout : !!value;
5189 if ( value !== this.verticalActionLayout ) {
5190 this.verticalActionLayout = value;
5191 this.$actions
5192 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
5193 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
5196 return this;
5200 * @inheritdoc
5202 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
5203 if ( action ) {
5204 return new OO.ui.Process( function () {
5205 this.close( { action: action } );
5206 }, this );
5208 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
5212 * @inheritdoc
5214 * @param {Object} [data] Dialog opening data
5215 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
5216 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
5217 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
5218 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
5219 * action item
5221 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
5222 data = data || {};
5224 // Parent method
5225 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
5226 .next( function () {
5227 this.title.setLabel(
5228 data.title !== undefined ? data.title : this.constructor.static.title
5230 this.message.setLabel(
5231 data.message !== undefined ? data.message : this.constructor.static.message
5233 this.message.$element.toggleClass(
5234 'oo-ui-messageDialog-message-verbose',
5235 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
5237 }, this );
5241 * @inheritdoc
5243 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
5244 return Math.round( this.text.$element.outerHeight( true ) );
5248 * @inheritdoc
5250 OO.ui.MessageDialog.prototype.initialize = function () {
5251 // Parent method
5252 OO.ui.MessageDialog.super.prototype.initialize.call( this );
5254 // Properties
5255 this.$actions = this.$( '<div>' );
5256 this.container = new OO.ui.PanelLayout( {
5257 $: this.$, scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
5258 } );
5259 this.text = new OO.ui.PanelLayout( {
5260 $: this.$, padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
5261 } );
5262 this.message = new OO.ui.LabelWidget( {
5263 $: this.$, classes: [ 'oo-ui-messageDialog-message' ]
5264 } );
5266 // Initialization
5267 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
5268 this.frame.$content.addClass( 'oo-ui-messageDialog-content' );
5269 this.container.$element.append( this.text.$element );
5270 this.text.$element.append( this.title.$element, this.message.$element );
5271 this.$body.append( this.container.$element );
5272 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
5273 this.$foot.append( this.$actions );
5277 * @inheritdoc
5279 OO.ui.MessageDialog.prototype.attachActions = function () {
5280 var i, len, other, special, others;
5282 // Parent method
5283 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
5285 special = this.actions.getSpecial();
5286 others = this.actions.getOthers();
5287 if ( special.safe ) {
5288 this.$actions.append( special.safe.$element );
5289 special.safe.toggleFramed( false );
5291 if ( others.length ) {
5292 for ( i = 0, len = others.length; i < len; i++ ) {
5293 other = others[i];
5294 this.$actions.append( other.$element );
5295 other.toggleFramed( false );
5298 if ( special.primary ) {
5299 this.$actions.append( special.primary.$element );
5300 special.primary.toggleFramed( false );
5303 this.fitActions();
5304 if ( !this.isOpening() ) {
5305 this.manager.updateWindowSize( this );
5307 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
5311 * Fit action actions into columns or rows.
5313 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
5315 OO.ui.MessageDialog.prototype.fitActions = function () {
5316 var i, len, action,
5317 actions = this.actions.get();
5319 // Detect clipping
5320 this.toggleVerticalActionLayout( false );
5321 for ( i = 0, len = actions.length; i < len; i++ ) {
5322 action = actions[i];
5323 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
5324 this.toggleVerticalActionLayout( true );
5325 break;
5331 * Navigation dialog window.
5333 * Logic:
5334 * - Show and hide errors.
5335 * - Retry an action.
5337 * User interface:
5338 * - Renders header with dialog title and one action widget on either side
5339 * (a 'safe' button on the left, and a 'primary' button on the right, both of
5340 * which close the dialog).
5341 * - Displays any action widgets in the footer (none by default).
5342 * - Ability to dismiss errors.
5344 * Subclass responsibilities:
5345 * - Register a 'safe' action.
5346 * - Register a 'primary' action.
5347 * - Add content to the dialog.
5349 * @abstract
5350 * @class
5351 * @extends OO.ui.Dialog
5353 * @constructor
5354 * @param {Object} [config] Configuration options
5356 OO.ui.ProcessDialog = function OoUiProcessDialog( manager, config ) {
5357 // Parent constructor
5358 OO.ui.ProcessDialog.super.call( this, manager, config );
5360 // Initialization
5361 this.$element.addClass( 'oo-ui-processDialog' );
5364 /* Setup */
5366 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
5368 /* Methods */
5371 * Handle dismiss button click events.
5373 * Hides errors.
5375 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
5376 this.hideErrors();
5380 * Handle retry button click events.
5382 * Hides errors and then tries again.
5384 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
5385 this.hideErrors();
5386 this.executeAction( this.currentAction.getAction() );
5390 * @inheritdoc
5392 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
5393 if ( this.actions.isSpecial( action ) ) {
5394 this.fitLabel();
5396 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
5400 * @inheritdoc
5402 OO.ui.ProcessDialog.prototype.initialize = function () {
5403 // Parent method
5404 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
5406 // Properties
5407 this.$navigation = this.$( '<div>' );
5408 this.$location = this.$( '<div>' );
5409 this.$safeActions = this.$( '<div>' );
5410 this.$primaryActions = this.$( '<div>' );
5411 this.$otherActions = this.$( '<div>' );
5412 this.dismissButton = new OO.ui.ButtonWidget( {
5413 $: this.$,
5414 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
5415 } );
5416 this.retryButton = new OO.ui.ButtonWidget( {
5417 $: this.$,
5418 label: OO.ui.msg( 'ooui-dialog-process-retry' )
5419 } );
5420 this.$errors = this.$( '<div>' );
5421 this.$errorsTitle = this.$( '<div>' );
5423 // Events
5424 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
5425 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
5427 // Initialization
5428 this.title.$element.addClass( 'oo-ui-processDialog-title' );
5429 this.$location
5430 .append( this.title.$element )
5431 .addClass( 'oo-ui-processDialog-location' );
5432 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
5433 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
5434 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
5435 this.$errorsTitle
5436 .addClass( 'oo-ui-processDialog-errors-title' )
5437 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
5438 this.$errors
5439 .addClass( 'oo-ui-processDialog-errors' )
5440 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
5441 this.frame.$content
5442 .addClass( 'oo-ui-processDialog-content' )
5443 .append( this.$errors );
5444 this.$navigation
5445 .addClass( 'oo-ui-processDialog-navigation' )
5446 .append( this.$safeActions, this.$location, this.$primaryActions );
5447 this.$head.append( this.$navigation );
5448 this.$foot.append( this.$otherActions );
5452 * @inheritdoc
5454 OO.ui.ProcessDialog.prototype.attachActions = function () {
5455 var i, len, other, special, others;
5457 // Parent method
5458 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
5460 special = this.actions.getSpecial();
5461 others = this.actions.getOthers();
5462 if ( special.primary ) {
5463 this.$primaryActions.append( special.primary.$element );
5464 special.primary.toggleFramed( true );
5466 if ( others.length ) {
5467 for ( i = 0, len = others.length; i < len; i++ ) {
5468 other = others[i];
5469 this.$otherActions.append( other.$element );
5470 other.toggleFramed( true );
5473 if ( special.safe ) {
5474 this.$safeActions.append( special.safe.$element );
5475 special.safe.toggleFramed( true );
5478 this.fitLabel();
5479 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
5483 * @inheritdoc
5485 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
5486 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
5487 .fail( OO.ui.bind( this.showErrors, this ) );
5491 * Fit label between actions.
5493 * @chainable
5495 OO.ui.ProcessDialog.prototype.fitLabel = function () {
5496 var width = Math.max(
5497 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
5498 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
5500 this.$location.css( { paddingLeft: width, paddingRight: width } );
5502 return this;
5506 * Handle errors that occured durring accept or reject processes.
5508 * @param {OO.ui.Error[]} errors Errors to be handled
5510 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
5511 var i, len, $item,
5512 items = [],
5513 recoverable = true;
5515 for ( i = 0, len = errors.length; i < len; i++ ) {
5516 if ( !errors[i].isRecoverable() ) {
5517 recoverable = false;
5519 $item = this.$( '<div>' )
5520 .addClass( 'oo-ui-processDialog-error' )
5521 .append( errors[i].getMessage() );
5522 items.push( $item[0] );
5524 this.$errorItems = this.$( items );
5525 if ( recoverable ) {
5526 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
5527 } else {
5528 this.currentAction.setDisabled( true );
5530 this.retryButton.toggle( recoverable );
5531 this.$errorsTitle.after( this.$errorItems );
5532 this.$errors.show().scrollTop( 0 );
5536 * Hide errors.
5538 OO.ui.ProcessDialog.prototype.hideErrors = function () {
5539 this.$errors.hide();
5540 this.$errorItems.remove();
5541 this.$errorItems = null;
5545 * Layout containing a series of pages.
5547 * @class
5548 * @extends OO.ui.Layout
5550 * @constructor
5551 * @param {Object} [config] Configuration options
5552 * @cfg {boolean} [continuous=false] Show all pages, one after another
5553 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
5554 * @cfg {boolean} [outlined=false] Show an outline
5555 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
5557 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
5558 // Initialize configuration
5559 config = config || {};
5561 // Parent constructor
5562 OO.ui.BookletLayout.super.call( this, config );
5564 // Properties
5565 this.currentPageName = null;
5566 this.pages = {};
5567 this.ignoreFocus = false;
5568 this.stackLayout = new OO.ui.StackLayout( { $: this.$, continuous: !!config.continuous } );
5569 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
5570 this.outlineVisible = false;
5571 this.outlined = !!config.outlined;
5572 if ( this.outlined ) {
5573 this.editable = !!config.editable;
5574 this.outlineControlsWidget = null;
5575 this.outlineWidget = new OO.ui.OutlineWidget( { $: this.$ } );
5576 this.outlinePanel = new OO.ui.PanelLayout( { $: this.$, scrollable: true } );
5577 this.gridLayout = new OO.ui.GridLayout(
5578 [ this.outlinePanel, this.stackLayout ],
5579 { $: this.$, widths: [ 1, 2 ] }
5581 this.outlineVisible = true;
5582 if ( this.editable ) {
5583 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
5584 this.outlineWidget, { $: this.$ }
5589 // Events
5590 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
5591 if ( this.outlined ) {
5592 this.outlineWidget.connect( this, { select: 'onOutlineWidgetSelect' } );
5594 if ( this.autoFocus ) {
5595 // Event 'focus' does not bubble, but 'focusin' does
5596 this.stackLayout.onDOMEvent( 'focusin', OO.ui.bind( this.onStackLayoutFocus, this ) );
5599 // Initialization
5600 this.$element.addClass( 'oo-ui-bookletLayout' );
5601 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
5602 if ( this.outlined ) {
5603 this.outlinePanel.$element
5604 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
5605 .append( this.outlineWidget.$element );
5606 if ( this.editable ) {
5607 this.outlinePanel.$element
5608 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
5609 .append( this.outlineControlsWidget.$element );
5611 this.$element.append( this.gridLayout.$element );
5612 } else {
5613 this.$element.append( this.stackLayout.$element );
5617 /* Setup */
5619 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
5621 /* Events */
5624 * @event set
5625 * @param {OO.ui.PageLayout} page Current page
5629 * @event add
5630 * @param {OO.ui.PageLayout[]} page Added pages
5631 * @param {number} index Index pages were added at
5635 * @event remove
5636 * @param {OO.ui.PageLayout[]} pages Removed pages
5639 /* Methods */
5642 * Handle stack layout focus.
5644 * @param {jQuery.Event} e Focusin event
5646 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
5647 var name, $target;
5649 // Find the page that an element was focused within
5650 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
5651 for ( name in this.pages ) {
5652 // Check for page match, exclude current page to find only page changes
5653 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
5654 this.setPage( name );
5655 break;
5661 * Handle stack layout set events.
5663 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
5665 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
5666 var $input, layout = this;
5667 if ( page ) {
5668 page.scrollElementIntoView( { complete: function () {
5669 if ( layout.autoFocus ) {
5670 // Set focus to the first input if nothing on the page is focused yet
5671 if ( !page.$element.find( ':focus' ).length ) {
5672 $input = page.$element.find( ':input:first' );
5673 if ( $input.length ) {
5674 $input[0].focus();
5678 } } );
5683 * Handle outline widget select events.
5685 * @param {OO.ui.OptionWidget|null} item Selected item
5687 OO.ui.BookletLayout.prototype.onOutlineWidgetSelect = function ( item ) {
5688 if ( item ) {
5689 this.setPage( item.getData() );
5694 * Check if booklet has an outline.
5696 * @return {boolean}
5698 OO.ui.BookletLayout.prototype.isOutlined = function () {
5699 return this.outlined;
5703 * Check if booklet has editing controls.
5705 * @return {boolean}
5707 OO.ui.BookletLayout.prototype.isEditable = function () {
5708 return this.editable;
5712 * Check if booklet has a visible outline.
5714 * @return {boolean}
5716 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
5717 return this.outlined && this.outlineVisible;
5721 * Hide or show the outline.
5723 * @param {boolean} [show] Show outline, omit to invert current state
5724 * @chainable
5726 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
5727 if ( this.outlined ) {
5728 show = show === undefined ? !this.outlineVisible : !!show;
5729 this.outlineVisible = show;
5730 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
5733 return this;
5737 * Get the outline widget.
5739 * @param {OO.ui.PageLayout} page Page to be selected
5740 * @return {OO.ui.PageLayout|null} Closest page to another
5742 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
5743 var next, prev, level,
5744 pages = this.stackLayout.getItems(),
5745 index = $.inArray( page, pages );
5747 if ( index !== -1 ) {
5748 next = pages[index + 1];
5749 prev = pages[index - 1];
5750 // Prefer adjacent pages at the same level
5751 if ( this.outlined ) {
5752 level = this.outlineWidget.getItemFromData( page.getName() ).getLevel();
5753 if (
5754 prev &&
5755 level === this.outlineWidget.getItemFromData( prev.getName() ).getLevel()
5757 return prev;
5759 if (
5760 next &&
5761 level === this.outlineWidget.getItemFromData( next.getName() ).getLevel()
5763 return next;
5767 return prev || next || null;
5771 * Get the outline widget.
5773 * @return {OO.ui.OutlineWidget|null} Outline widget, or null if boolet has no outline
5775 OO.ui.BookletLayout.prototype.getOutline = function () {
5776 return this.outlineWidget;
5780 * Get the outline controls widget. If the outline is not editable, null is returned.
5782 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
5784 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
5785 return this.outlineControlsWidget;
5789 * Get a page by name.
5791 * @param {string} name Symbolic name of page
5792 * @return {OO.ui.PageLayout|undefined} Page, if found
5794 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
5795 return this.pages[name];
5799 * Get the current page name.
5801 * @return {string|null} Current page name
5803 OO.ui.BookletLayout.prototype.getPageName = function () {
5804 return this.currentPageName;
5808 * Add a page to the layout.
5810 * When pages are added with the same names as existing pages, the existing pages will be
5811 * automatically removed before the new pages are added.
5813 * @param {OO.ui.PageLayout[]} pages Pages to add
5814 * @param {number} index Index to insert pages after
5815 * @fires add
5816 * @chainable
5818 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
5819 var i, len, name, page, item, currentIndex,
5820 stackLayoutPages = this.stackLayout.getItems(),
5821 remove = [],
5822 items = [];
5824 // Remove pages with same names
5825 for ( i = 0, len = pages.length; i < len; i++ ) {
5826 page = pages[i];
5827 name = page.getName();
5829 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
5830 // Correct the insertion index
5831 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
5832 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
5833 index--;
5835 remove.push( this.pages[name] );
5838 if ( remove.length ) {
5839 this.removePages( remove );
5842 // Add new pages
5843 for ( i = 0, len = pages.length; i < len; i++ ) {
5844 page = pages[i];
5845 name = page.getName();
5846 this.pages[page.getName()] = page;
5847 if ( this.outlined ) {
5848 item = new OO.ui.OutlineItemWidget( name, page, { $: this.$ } );
5849 page.setOutlineItem( item );
5850 items.push( item );
5854 if ( this.outlined && items.length ) {
5855 this.outlineWidget.addItems( items, index );
5856 this.updateOutlineWidget();
5858 this.stackLayout.addItems( pages, index );
5859 this.emit( 'add', pages, index );
5861 return this;
5865 * Remove a page from the layout.
5867 * @fires remove
5868 * @chainable
5870 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
5871 var i, len, name, page,
5872 items = [];
5874 for ( i = 0, len = pages.length; i < len; i++ ) {
5875 page = pages[i];
5876 name = page.getName();
5877 delete this.pages[name];
5878 if ( this.outlined ) {
5879 items.push( this.outlineWidget.getItemFromData( name ) );
5880 page.setOutlineItem( null );
5883 if ( this.outlined && items.length ) {
5884 this.outlineWidget.removeItems( items );
5885 this.updateOutlineWidget();
5887 this.stackLayout.removeItems( pages );
5888 this.emit( 'remove', pages );
5890 return this;
5894 * Clear all pages from the layout.
5896 * @fires remove
5897 * @chainable
5899 OO.ui.BookletLayout.prototype.clearPages = function () {
5900 var i, len,
5901 pages = this.stackLayout.getItems();
5903 this.pages = {};
5904 this.currentPageName = null;
5905 if ( this.outlined ) {
5906 this.outlineWidget.clearItems();
5907 for ( i = 0, len = pages.length; i < len; i++ ) {
5908 pages[i].setOutlineItem( null );
5911 this.stackLayout.clearItems();
5913 this.emit( 'remove', pages );
5915 return this;
5919 * Set the current page by name.
5921 * @fires set
5922 * @param {string} name Symbolic name of page
5924 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
5925 var selectedItem,
5926 $focused,
5927 page = this.pages[name];
5929 if ( name !== this.currentPageName ) {
5930 if ( this.outlined ) {
5931 selectedItem = this.outlineWidget.getSelectedItem();
5932 if ( selectedItem && selectedItem.getData() !== name ) {
5933 this.outlineWidget.selectItem( this.outlineWidget.getItemFromData( name ) );
5936 if ( page ) {
5937 if ( this.currentPageName && this.pages[this.currentPageName] ) {
5938 this.pages[this.currentPageName].setActive( false );
5939 // Blur anything focused if the next page doesn't have anything focusable - this
5940 // is not needed if the next page has something focusable because once it is focused
5941 // this blur happens automatically
5942 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
5943 $focused = this.pages[this.currentPageName].$element.find( ':focus' );
5944 if ( $focused.length ) {
5945 $focused[0].blur();
5949 this.currentPageName = name;
5950 this.stackLayout.setItem( page );
5951 page.setActive( true );
5952 this.emit( 'set', page );
5958 * Call this after adding or removing items from the OutlineWidget.
5960 * @chainable
5962 OO.ui.BookletLayout.prototype.updateOutlineWidget = function () {
5963 // Auto-select first item when nothing is selected anymore
5964 if ( !this.outlineWidget.getSelectedItem() ) {
5965 this.outlineWidget.selectItem( this.outlineWidget.getFirstSelectableItem() );
5968 return this;
5972 * Layout made of a field and optional label.
5974 * @class
5975 * @extends OO.ui.Layout
5976 * @mixins OO.ui.LabeledElement
5978 * Available label alignment modes include:
5979 * - left: Label is before the field and aligned away from it, best for when the user will be
5980 * scanning for a specific label in a form with many fields
5981 * - right: Label is before the field and aligned toward it, best for forms the user is very
5982 * familiar with and will tab through field checking quickly to verify which field they are in
5983 * - top: Label is before the field and above it, best for when the use will need to fill out all
5984 * fields from top to bottom in a form with few fields
5985 * - inline: Label is after the field and aligned toward it, best for small boolean fields like
5986 * checkboxes or radio buttons
5988 * @constructor
5989 * @param {OO.ui.Widget} field Field widget
5990 * @param {Object} [config] Configuration options
5991 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
5992 * @cfg {string} [help] Explanatory text shown as a '?' icon.
5994 OO.ui.FieldLayout = function OoUiFieldLayout( field, config ) {
5995 var popupButtonWidget;
5996 // Config initialization
5997 config = $.extend( { align: 'left' }, config );
5999 // Parent constructor
6000 OO.ui.FieldLayout.super.call( this, config );
6002 // Mixin constructors
6003 this.$help = this.$( '<div>' );
6004 OO.ui.LabeledElement.call( this, this.$( '<label>' ), config );
6005 if ( config.help ) {
6006 popupButtonWidget = new OO.ui.PopupButtonWidget( $.extend(
6008 $: this.$,
6009 frameless: true,
6010 icon: 'info',
6011 title: config.help
6013 config,
6014 { label: null }
6015 ) );
6016 popupButtonWidget.getPopup().$body.append( this.getElementDocument().createTextNode( config.help ) );
6017 this.$help = popupButtonWidget.$element;
6020 // Properties
6021 this.$field = this.$( '<div>' );
6022 this.field = field;
6023 this.align = null;
6025 // Events
6026 if ( this.field instanceof OO.ui.InputWidget ) {
6027 this.$label.on( 'click', OO.ui.bind( this.onLabelClick, this ) );
6029 this.field.connect( this, { disable: 'onFieldDisable' } );
6031 // Initialization
6032 this.$element.addClass( 'oo-ui-fieldLayout' );
6033 this.$field
6034 .addClass( 'oo-ui-fieldLayout-field' )
6035 .toggleClass( 'oo-ui-fieldLayout-disable', this.field.isDisabled() )
6036 .append( this.field.$element );
6037 this.setAlignment( config.align );
6040 /* Setup */
6042 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
6043 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabeledElement );
6045 /* Methods */
6048 * Handle field disable events.
6050 * @param {boolean} value Field is disabled
6052 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
6053 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
6057 * Handle label mouse click events.
6059 * @param {jQuery.Event} e Mouse click event
6061 OO.ui.FieldLayout.prototype.onLabelClick = function () {
6062 this.field.simulateLabelClick();
6063 return false;
6067 * Get the field.
6069 * @return {OO.ui.Widget} Field widget
6071 OO.ui.FieldLayout.prototype.getField = function () {
6072 return this.field;
6076 * Set the field alignment mode.
6078 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
6079 * @chainable
6081 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
6082 if ( value !== this.align ) {
6083 // Default to 'left'
6084 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
6085 value = 'left';
6087 // Reorder elements
6088 if ( value === 'inline' ) {
6089 this.$element.append( this.$field, this.$label, this.$help );
6090 } else {
6091 this.$element.append( this.$help, this.$label, this.$field );
6093 // Set classes
6094 if ( this.align ) {
6095 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
6097 this.align = value;
6098 this.$element.addClass( 'oo-ui-fieldLayout-align-' + this.align );
6101 return this;
6105 * Layout made of a fieldset and optional legend.
6107 * Just add OO.ui.FieldLayout items.
6109 * @class
6110 * @extends OO.ui.Layout
6111 * @mixins OO.ui.LabeledElement
6112 * @mixins OO.ui.IconedElement
6113 * @mixins OO.ui.GroupElement
6115 * @constructor
6116 * @param {Object} [config] Configuration options
6117 * @cfg {string} [icon] Symbolic icon name
6118 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
6120 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
6121 // Config initialization
6122 config = config || {};
6124 // Parent constructor
6125 OO.ui.FieldsetLayout.super.call( this, config );
6127 // Mixin constructors
6128 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
6129 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
6130 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
6132 // Initialization
6133 this.$element
6134 .addClass( 'oo-ui-fieldsetLayout' )
6135 .prepend( this.$icon, this.$label, this.$group );
6136 if ( $.isArray( config.items ) ) {
6137 this.addItems( config.items );
6141 /* Setup */
6143 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
6144 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconedElement );
6145 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabeledElement );
6146 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
6148 /* Static Properties */
6150 OO.ui.FieldsetLayout.static.tagName = 'div';
6153 * Layout with an HTML form.
6155 * @class
6156 * @extends OO.ui.Layout
6158 * @constructor
6159 * @param {Object} [config] Configuration options
6161 OO.ui.FormLayout = function OoUiFormLayout( config ) {
6162 // Configuration initialization
6163 config = config || {};
6165 // Parent constructor
6166 OO.ui.FormLayout.super.call( this, config );
6168 // Events
6169 this.$element.on( 'submit', OO.ui.bind( this.onFormSubmit, this ) );
6171 // Initialization
6172 this.$element.addClass( 'oo-ui-formLayout' );
6175 /* Setup */
6177 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
6179 /* Events */
6182 * @event submit
6185 /* Static Properties */
6187 OO.ui.FormLayout.static.tagName = 'form';
6189 /* Methods */
6192 * Handle form submit events.
6194 * @param {jQuery.Event} e Submit event
6195 * @fires submit
6197 OO.ui.FormLayout.prototype.onFormSubmit = function () {
6198 this.emit( 'submit' );
6199 return false;
6203 * Layout made of proportionally sized columns and rows.
6205 * @class
6206 * @extends OO.ui.Layout
6208 * @constructor
6209 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
6210 * @param {Object} [config] Configuration options
6211 * @cfg {number[]} [widths] Widths of columns as ratios
6212 * @cfg {number[]} [heights] Heights of columns as ratios
6214 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
6215 var i, len, widths;
6217 // Config initialization
6218 config = config || {};
6220 // Parent constructor
6221 OO.ui.GridLayout.super.call( this, config );
6223 // Properties
6224 this.panels = [];
6225 this.widths = [];
6226 this.heights = [];
6228 // Initialization
6229 this.$element.addClass( 'oo-ui-gridLayout' );
6230 for ( i = 0, len = panels.length; i < len; i++ ) {
6231 this.panels.push( panels[i] );
6232 this.$element.append( panels[i].$element );
6234 if ( config.widths || config.heights ) {
6235 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
6236 } else {
6237 // Arrange in columns by default
6238 widths = [];
6239 for ( i = 0, len = this.panels.length; i < len; i++ ) {
6240 widths[i] = 1;
6242 this.layout( widths, [ 1 ] );
6246 /* Setup */
6248 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
6250 /* Events */
6253 * @event layout
6257 * @event update
6260 /* Static Properties */
6262 OO.ui.GridLayout.static.tagName = 'div';
6264 /* Methods */
6267 * Set grid dimensions.
6269 * @param {number[]} widths Widths of columns as ratios
6270 * @param {number[]} heights Heights of rows as ratios
6271 * @fires layout
6272 * @throws {Error} If grid is not large enough to fit all panels
6274 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
6275 var x, y,
6276 xd = 0,
6277 yd = 0,
6278 cols = widths.length,
6279 rows = heights.length;
6281 // Verify grid is big enough to fit panels
6282 if ( cols * rows < this.panels.length ) {
6283 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
6286 // Sum up denominators
6287 for ( x = 0; x < cols; x++ ) {
6288 xd += widths[x];
6290 for ( y = 0; y < rows; y++ ) {
6291 yd += heights[y];
6293 // Store factors
6294 this.widths = [];
6295 this.heights = [];
6296 for ( x = 0; x < cols; x++ ) {
6297 this.widths[x] = widths[x] / xd;
6299 for ( y = 0; y < rows; y++ ) {
6300 this.heights[y] = heights[y] / yd;
6302 // Synchronize view
6303 this.update();
6304 this.emit( 'layout' );
6308 * Update panel positions and sizes.
6310 * @fires update
6312 OO.ui.GridLayout.prototype.update = function () {
6313 var x, y, panel,
6314 i = 0,
6315 left = 0,
6316 top = 0,
6317 dimensions,
6318 width = 0,
6319 height = 0,
6320 cols = this.widths.length,
6321 rows = this.heights.length;
6323 for ( y = 0; y < rows; y++ ) {
6324 height = this.heights[y];
6325 for ( x = 0; x < cols; x++ ) {
6326 panel = this.panels[i];
6327 width = this.widths[x];
6328 dimensions = {
6329 width: Math.round( width * 100 ) + '%',
6330 height: Math.round( height * 100 ) + '%',
6331 top: Math.round( top * 100 ) + '%',
6332 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
6333 visibility: width === 0 || height === 0 ? 'hidden' : ''
6335 // If RTL, reverse:
6336 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
6337 dimensions.right = Math.round( left * 100 ) + '%';
6338 } else {
6339 dimensions.left = Math.round( left * 100 ) + '%';
6341 panel.$element.css( dimensions );
6342 i++;
6343 left += width;
6345 top += height;
6346 left = 0;
6349 this.emit( 'update' );
6353 * Get a panel at a given position.
6355 * The x and y position is affected by the current grid layout.
6357 * @param {number} x Horizontal position
6358 * @param {number} y Vertical position
6359 * @return {OO.ui.PanelLayout} The panel at the given postion
6361 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
6362 return this.panels[( x * this.widths.length ) + y];
6366 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
6368 * @class
6369 * @extends OO.ui.Layout
6371 * @constructor
6372 * @param {Object} [config] Configuration options
6373 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
6374 * @cfg {boolean} [padded=false] Pad the content from the edges
6375 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
6377 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
6378 // Config initialization
6379 config = config || {};
6381 // Parent constructor
6382 OO.ui.PanelLayout.super.call( this, config );
6384 // Initialization
6385 this.$element.addClass( 'oo-ui-panelLayout' );
6386 if ( config.scrollable ) {
6387 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
6390 if ( config.padded ) {
6391 this.$element.addClass( 'oo-ui-panelLayout-padded' );
6394 if ( config.expanded === undefined || config.expanded ) {
6395 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
6399 /* Setup */
6401 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
6404 * Page within an booklet layout.
6406 * @class
6407 * @extends OO.ui.PanelLayout
6409 * @constructor
6410 * @param {string} name Unique symbolic name of page
6411 * @param {Object} [config] Configuration options
6412 * @param {string} [outlineItem] Outline item widget
6414 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
6415 // Configuration initialization
6416 config = $.extend( { scrollable: true }, config );
6418 // Parent constructor
6419 OO.ui.PageLayout.super.call( this, config );
6421 // Properties
6422 this.name = name;
6423 this.outlineItem = config.outlineItem || null;
6424 this.active = false;
6426 // Initialization
6427 this.$element.addClass( 'oo-ui-pageLayout' );
6430 /* Setup */
6432 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
6434 /* Events */
6437 * @event active
6438 * @param {boolean} active Page is active
6441 /* Methods */
6444 * Get page name.
6446 * @return {string} Symbolic name of page
6448 OO.ui.PageLayout.prototype.getName = function () {
6449 return this.name;
6453 * Check if page is active.
6455 * @return {boolean} Page is active
6457 OO.ui.PageLayout.prototype.isActive = function () {
6458 return this.active;
6462 * Get outline item.
6464 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
6466 OO.ui.PageLayout.prototype.getOutlineItem = function () {
6467 return this.outlineItem;
6471 * Set outline item.
6473 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
6474 * outline item as desired; this method is called for setting (with an object) and unsetting
6475 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
6476 * operating on null instead of an OO.ui.OutlineItemWidget object.
6478 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
6479 * @chainable
6481 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
6482 this.outlineItem = outlineItem || null;
6483 if ( outlineItem ) {
6484 this.setupOutlineItem();
6486 return this;
6490 * Setup outline item.
6492 * @localdoc Subclasses should override this method to adjust the outline item as desired.
6494 * @param {OO.ui.OutlineItemWidget} outlineItem Outline item widget to setup
6495 * @chainable
6497 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
6498 return this;
6502 * Set page active state.
6504 * @param {boolean} Page is active
6505 * @fires active
6507 OO.ui.PageLayout.prototype.setActive = function ( active ) {
6508 active = !!active;
6510 if ( active !== this.active ) {
6511 this.active = active;
6512 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
6513 this.emit( 'active', this.active );
6518 * Layout containing a series of mutually exclusive pages.
6520 * @class
6521 * @extends OO.ui.PanelLayout
6522 * @mixins OO.ui.GroupElement
6524 * @constructor
6525 * @param {Object} [config] Configuration options
6526 * @cfg {boolean} [continuous=false] Show all pages, one after another
6527 * @cfg {string} [icon=''] Symbolic icon name
6528 * @cfg {OO.ui.Layout[]} [items] Layouts to add
6530 OO.ui.StackLayout = function OoUiStackLayout( config ) {
6531 // Config initialization
6532 config = $.extend( { scrollable: true }, config );
6534 // Parent constructor
6535 OO.ui.StackLayout.super.call( this, config );
6537 // Mixin constructors
6538 OO.ui.GroupElement.call( this, this.$element, config );
6540 // Properties
6541 this.currentItem = null;
6542 this.continuous = !!config.continuous;
6544 // Initialization
6545 this.$element.addClass( 'oo-ui-stackLayout' );
6546 if ( this.continuous ) {
6547 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
6549 if ( $.isArray( config.items ) ) {
6550 this.addItems( config.items );
6554 /* Setup */
6556 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
6557 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
6559 /* Events */
6562 * @event set
6563 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
6566 /* Methods */
6569 * Get the current item.
6571 * @return {OO.ui.Layout|null}
6573 OO.ui.StackLayout.prototype.getCurrentItem = function () {
6574 return this.currentItem;
6578 * Unset the current item.
6580 * @private
6581 * @param {OO.ui.StackLayout} layout
6582 * @fires set
6584 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
6585 var prevItem = this.currentItem;
6586 if ( prevItem === null ) {
6587 return;
6590 this.currentItem = null;
6591 this.emit( 'set', null );
6595 * Add items.
6597 * Adding an existing item (by value) will move it.
6599 * @param {OO.ui.Layout[]} items Items to add
6600 * @param {number} [index] Index to insert items after
6601 * @chainable
6603 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
6604 // Mixin method
6605 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
6607 if ( !this.currentItem && items.length ) {
6608 this.setItem( items[0] );
6611 return this;
6615 * Remove items.
6617 * Items will be detached, not removed, so they can be used later.
6619 * @param {OO.ui.Layout[]} items Items to remove
6620 * @chainable
6621 * @fires set
6623 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
6624 // Mixin method
6625 OO.ui.GroupElement.prototype.removeItems.call( this, items );
6627 if ( $.inArray( this.currentItem, items ) !== -1 ) {
6628 if ( this.items.length ) {
6629 this.setItem( this.items[0] );
6630 } else {
6631 this.unsetCurrentItem();
6635 return this;
6639 * Clear all items.
6641 * Items will be detached, not removed, so they can be used later.
6643 * @chainable
6644 * @fires set
6646 OO.ui.StackLayout.prototype.clearItems = function () {
6647 this.unsetCurrentItem();
6648 OO.ui.GroupElement.prototype.clearItems.call( this );
6650 return this;
6654 * Show item.
6656 * Any currently shown item will be hidden.
6658 * FIXME: If the passed item to show has not been added in the items list, then
6659 * this method drops it and unsets the current item.
6661 * @param {OO.ui.Layout} item Item to show
6662 * @chainable
6663 * @fires set
6665 OO.ui.StackLayout.prototype.setItem = function ( item ) {
6666 var i, len;
6668 if ( item !== this.currentItem ) {
6669 if ( !this.continuous ) {
6670 for ( i = 0, len = this.items.length; i < len; i++ ) {
6671 this.items[i].$element.css( 'display', '' );
6674 if ( $.inArray( item, this.items ) !== -1 ) {
6675 if ( !this.continuous ) {
6676 item.$element.css( 'display', 'block' );
6678 this.currentItem = item;
6679 this.emit( 'set', item );
6680 } else {
6681 this.unsetCurrentItem();
6685 return this;
6689 * Horizontal bar layout of tools as icon buttons.
6691 * @class
6692 * @extends OO.ui.ToolGroup
6694 * @constructor
6695 * @param {OO.ui.Toolbar} toolbar
6696 * @param {Object} [config] Configuration options
6698 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
6699 // Parent constructor
6700 OO.ui.BarToolGroup.super.call( this, toolbar, config );
6702 // Initialization
6703 this.$element.addClass( 'oo-ui-barToolGroup' );
6706 /* Setup */
6708 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
6710 /* Static Properties */
6712 OO.ui.BarToolGroup.static.titleTooltips = true;
6714 OO.ui.BarToolGroup.static.accelTooltips = true;
6716 OO.ui.BarToolGroup.static.name = 'bar';
6719 * Popup list of tools with an icon and optional label.
6721 * @abstract
6722 * @class
6723 * @extends OO.ui.ToolGroup
6724 * @mixins OO.ui.IconedElement
6725 * @mixins OO.ui.IndicatedElement
6726 * @mixins OO.ui.LabeledElement
6727 * @mixins OO.ui.TitledElement
6728 * @mixins OO.ui.ClippableElement
6730 * @constructor
6731 * @param {OO.ui.Toolbar} toolbar
6732 * @param {Object} [config] Configuration options
6733 * @cfg {string} [header] Text to display at the top of the pop-up
6735 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
6736 // Configuration initialization
6737 config = config || {};
6739 // Parent constructor
6740 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
6742 // Mixin constructors
6743 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
6744 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
6745 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
6746 OO.ui.TitledElement.call( this, this.$element, config );
6747 OO.ui.ClippableElement.call( this, this.$group, config );
6749 // Properties
6750 this.active = false;
6751 this.dragging = false;
6752 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
6753 this.$handle = this.$( '<span>' );
6755 // Events
6756 this.$handle.on( {
6757 'mousedown touchstart': OO.ui.bind( this.onHandlePointerDown, this ),
6758 'mouseup touchend': OO.ui.bind( this.onHandlePointerUp, this )
6759 } );
6761 // Initialization
6762 this.$handle
6763 .addClass( 'oo-ui-popupToolGroup-handle' )
6764 .append( this.$icon, this.$label, this.$indicator );
6765 // If the pop-up should have a header, add it to the top of the toolGroup.
6766 // Note: If this feature is useful for other widgets, we could abstract it into an
6767 // OO.ui.HeaderedElement mixin constructor.
6768 if ( config.header !== undefined ) {
6769 this.$group
6770 .prepend( this.$( '<span>' )
6771 .addClass( 'oo-ui-popupToolGroup-header' )
6772 .text( config.header )
6775 this.$element
6776 .addClass( 'oo-ui-popupToolGroup' )
6777 .prepend( this.$handle );
6780 /* Setup */
6782 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
6783 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconedElement );
6784 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatedElement );
6785 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabeledElement );
6786 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
6787 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
6789 /* Static Properties */
6791 /* Methods */
6794 * @inheritdoc
6796 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
6797 // Parent method
6798 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
6800 if ( this.isDisabled() && this.isElementAttached() ) {
6801 this.setActive( false );
6806 * Handle focus being lost.
6808 * The event is actually generated from a mouseup, so it is not a normal blur event object.
6810 * @param {jQuery.Event} e Mouse up event
6812 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
6813 // Only deactivate when clicking outside the dropdown element
6814 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
6815 this.setActive( false );
6820 * @inheritdoc
6822 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
6823 // e.which is 0 for touch events, 1 for left mouse button
6824 if ( !this.isDisabled() && e.which <= 1 ) {
6825 this.setActive( false );
6827 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
6831 * Handle mouse up events.
6833 * @param {jQuery.Event} e Mouse up event
6835 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
6836 return false;
6840 * Handle mouse down events.
6842 * @param {jQuery.Event} e Mouse down event
6844 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
6845 // e.which is 0 for touch events, 1 for left mouse button
6846 if ( !this.isDisabled() && e.which <= 1 ) {
6847 this.setActive( !this.active );
6849 return false;
6853 * Switch into active mode.
6855 * When active, mouseup events anywhere in the document will trigger deactivation.
6857 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
6858 value = !!value;
6859 if ( this.active !== value ) {
6860 this.active = value;
6861 if ( value ) {
6862 this.setClipping( true );
6863 this.$element.addClass( 'oo-ui-popupToolGroup-active' );
6864 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
6865 } else {
6866 this.setClipping( false );
6867 this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
6868 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
6874 * Drop down list layout of tools as labeled icon buttons.
6876 * @class
6877 * @extends OO.ui.PopupToolGroup
6879 * @constructor
6880 * @param {OO.ui.Toolbar} toolbar
6881 * @param {Object} [config] Configuration options
6883 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
6884 // Parent constructor
6885 OO.ui.ListToolGroup.super.call( this, toolbar, config );
6887 // Initialization
6888 this.$element.addClass( 'oo-ui-listToolGroup' );
6891 /* Setup */
6893 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
6895 /* Static Properties */
6897 OO.ui.ListToolGroup.static.accelTooltips = true;
6899 OO.ui.ListToolGroup.static.name = 'list';
6902 * Drop down menu layout of tools as selectable menu items.
6904 * @class
6905 * @extends OO.ui.PopupToolGroup
6907 * @constructor
6908 * @param {OO.ui.Toolbar} toolbar
6909 * @param {Object} [config] Configuration options
6911 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
6912 // Configuration initialization
6913 config = config || {};
6915 // Parent constructor
6916 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
6918 // Events
6919 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6921 // Initialization
6922 this.$element.addClass( 'oo-ui-menuToolGroup' );
6925 /* Setup */
6927 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
6929 /* Static Properties */
6931 OO.ui.MenuToolGroup.static.accelTooltips = true;
6933 OO.ui.MenuToolGroup.static.name = 'menu';
6935 /* Methods */
6938 * Handle the toolbar state being updated.
6940 * When the state changes, the title of each active item in the menu will be joined together and
6941 * used as a label for the group. The label will be empty if none of the items are active.
6943 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
6944 var name,
6945 labelTexts = [];
6947 for ( name in this.tools ) {
6948 if ( this.tools[name].isActive() ) {
6949 labelTexts.push( this.tools[name].getTitle() );
6953 this.setLabel( labelTexts.join( ', ' ) || ' ' );
6957 * Tool that shows a popup when selected.
6959 * @abstract
6960 * @class
6961 * @extends OO.ui.Tool
6962 * @mixins OO.ui.PopuppableElement
6964 * @constructor
6965 * @param {OO.ui.Toolbar} toolbar
6966 * @param {Object} [config] Configuration options
6968 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
6969 // Parent constructor
6970 OO.ui.PopupTool.super.call( this, toolbar, config );
6972 // Mixin constructors
6973 OO.ui.PopuppableElement.call( this, config );
6975 // Initialization
6976 this.$element
6977 .addClass( 'oo-ui-popupTool' )
6978 .append( this.popup.$element );
6981 /* Setup */
6983 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
6984 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopuppableElement );
6986 /* Methods */
6989 * Handle the tool being selected.
6991 * @inheritdoc
6993 OO.ui.PopupTool.prototype.onSelect = function () {
6994 if ( !this.isDisabled() ) {
6995 this.popup.toggle();
6997 this.setActive( false );
6998 return false;
7002 * Handle the toolbar state being updated.
7004 * @inheritdoc
7006 OO.ui.PopupTool.prototype.onUpdateState = function () {
7007 this.setActive( false );
7011 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
7013 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
7015 * @abstract
7016 * @class
7017 * @extends OO.ui.GroupElement
7019 * @constructor
7020 * @param {jQuery} $group Container node, assigned to #$group
7021 * @param {Object} [config] Configuration options
7023 OO.ui.GroupWidget = function OoUiGroupWidget( $element, config ) {
7024 // Parent constructor
7025 OO.ui.GroupWidget.super.call( this, $element, config );
7028 /* Setup */
7030 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
7032 /* Methods */
7035 * Set the disabled state of the widget.
7037 * This will also update the disabled state of child widgets.
7039 * @param {boolean} disabled Disable widget
7040 * @chainable
7042 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
7043 var i, len;
7045 // Parent method
7046 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
7047 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
7049 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
7050 if ( this.items ) {
7051 for ( i = 0, len = this.items.length; i < len; i++ ) {
7052 this.items[i].updateDisabled();
7056 return this;
7060 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
7062 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
7063 * allows bidrectional communication.
7065 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
7067 * @abstract
7068 * @class
7070 * @constructor
7072 OO.ui.ItemWidget = function OoUiItemWidget() {
7076 /* Methods */
7079 * Check if widget is disabled.
7081 * Checks parent if present, making disabled state inheritable.
7083 * @return {boolean} Widget is disabled
7085 OO.ui.ItemWidget.prototype.isDisabled = function () {
7086 return this.disabled ||
7087 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
7091 * Set group element is in.
7093 * @param {OO.ui.GroupElement|null} group Group element, null if none
7094 * @chainable
7096 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
7097 // Parent method
7098 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
7099 OO.ui.Element.prototype.setElementGroup.call( this, group );
7101 // Initialize item disabled states
7102 this.updateDisabled();
7104 return this;
7108 * Mixin that adds a menu showing suggested values for a text input.
7110 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
7112 * @class
7113 * @abstract
7115 * @constructor
7116 * @param {OO.ui.TextInputWidget} input Input widget
7117 * @param {Object} [config] Configuration options
7118 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
7120 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
7121 // Config intialization
7122 config = config || {};
7124 // Properties
7125 this.lookupInput = input;
7126 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
7127 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
7128 $: OO.ui.Element.getJQuery( this.$overlay ),
7129 input: this.lookupInput,
7130 $container: config.$container
7131 } );
7132 this.lookupCache = {};
7133 this.lookupQuery = null;
7134 this.lookupRequest = null;
7135 this.populating = false;
7137 // Events
7138 this.$overlay.append( this.lookupMenu.$element );
7140 this.lookupInput.$input.on( {
7141 focus: OO.ui.bind( this.onLookupInputFocus, this ),
7142 blur: OO.ui.bind( this.onLookupInputBlur, this ),
7143 mousedown: OO.ui.bind( this.onLookupInputMouseDown, this )
7144 } );
7145 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
7147 // Initialization
7148 this.$element.addClass( 'oo-ui-lookupWidget' );
7149 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
7152 /* Methods */
7155 * Handle input focus event.
7157 * @param {jQuery.Event} e Input focus event
7159 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
7160 this.openLookupMenu();
7164 * Handle input blur event.
7166 * @param {jQuery.Event} e Input blur event
7168 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
7169 this.lookupMenu.toggle( false );
7173 * Handle input mouse down event.
7175 * @param {jQuery.Event} e Input mouse down event
7177 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
7178 this.openLookupMenu();
7182 * Handle input change event.
7184 * @param {string} value New input value
7186 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
7187 this.openLookupMenu();
7191 * Get lookup menu.
7193 * @return {OO.ui.TextInputMenuWidget}
7195 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
7196 return this.lookupMenu;
7200 * Open the menu.
7202 * @chainable
7204 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
7205 var value = this.lookupInput.getValue();
7207 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
7208 this.populateLookupMenu();
7209 this.lookupMenu.toggle( true );
7210 } else {
7211 this.lookupMenu
7212 .clearItems()
7213 .toggle( false );
7216 return this;
7220 * Populate lookup menu with current information.
7222 * @chainable
7224 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
7225 var widget = this;
7227 if ( !this.populating ) {
7228 this.populating = true;
7229 this.getLookupMenuItems()
7230 .done( function ( items ) {
7231 widget.lookupMenu.clearItems();
7232 if ( items.length ) {
7233 widget.lookupMenu
7234 .addItems( items )
7235 .toggle( true );
7236 widget.initializeLookupMenuSelection();
7237 widget.openLookupMenu();
7238 } else {
7239 widget.lookupMenu.toggle( true );
7241 widget.populating = false;
7243 .fail( function () {
7244 widget.lookupMenu.clearItems();
7245 widget.populating = false;
7246 } );
7249 return this;
7253 * Set selection in the lookup menu with current information.
7255 * @chainable
7257 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
7258 if ( !this.lookupMenu.getSelectedItem() ) {
7259 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
7261 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
7265 * Get lookup menu items for the current query.
7267 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
7268 * of the done event
7270 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
7271 var widget = this,
7272 value = this.lookupInput.getValue(),
7273 deferred = $.Deferred();
7275 if ( value && value !== this.lookupQuery ) {
7276 // Abort current request if query has changed
7277 if ( this.lookupRequest ) {
7278 this.lookupRequest.abort();
7279 this.lookupQuery = null;
7280 this.lookupRequest = null;
7282 if ( value in this.lookupCache ) {
7283 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
7284 } else {
7285 this.lookupQuery = value;
7286 this.lookupRequest = this.getLookupRequest()
7287 .always( function () {
7288 widget.lookupQuery = null;
7289 widget.lookupRequest = null;
7291 .done( function ( data ) {
7292 widget.lookupCache[value] = widget.getLookupCacheItemFromData( data );
7293 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[value] ) );
7295 .fail( function () {
7296 deferred.reject();
7297 } );
7298 this.pushPending();
7299 this.lookupRequest.always( function () {
7300 widget.popPending();
7301 } );
7304 return deferred.promise();
7308 * Get a new request object of the current lookup query value.
7310 * @abstract
7311 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
7313 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
7314 // Stub, implemented in subclass
7315 return null;
7319 * Handle successful lookup request.
7321 * Overriding methods should call #populateLookupMenu when results are available and cache results
7322 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
7324 * @abstract
7325 * @param {Mixed} data Response from server
7327 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
7328 // Stub, implemented in subclass
7332 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
7334 * @abstract
7335 * @param {Mixed} data Cached result data, usually an array
7336 * @return {OO.ui.MenuItemWidget[]} Menu items
7338 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
7339 // Stub, implemented in subclass
7340 return [];
7344 * Set of controls for an OO.ui.OutlineWidget.
7346 * Controls include moving items up and down, removing items, and adding different kinds of items.
7348 * @class
7349 * @extends OO.ui.Widget
7350 * @mixins OO.ui.GroupElement
7351 * @mixins OO.ui.IconedElement
7353 * @constructor
7354 * @param {OO.ui.OutlineWidget} outline Outline to control
7355 * @param {Object} [config] Configuration options
7357 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7358 // Configuration initialization
7359 config = $.extend( { icon: 'add-item' }, config );
7361 // Parent constructor
7362 OO.ui.OutlineControlsWidget.super.call( this, config );
7364 // Mixin constructors
7365 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
7366 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
7368 // Properties
7369 this.outline = outline;
7370 this.$movers = this.$( '<div>' );
7371 this.upButton = new OO.ui.ButtonWidget( {
7372 $: this.$,
7373 framed: false,
7374 icon: 'collapse',
7375 title: OO.ui.msg( 'ooui-outline-control-move-up' )
7376 } );
7377 this.downButton = new OO.ui.ButtonWidget( {
7378 $: this.$,
7379 framed: false,
7380 icon: 'expand',
7381 title: OO.ui.msg( 'ooui-outline-control-move-down' )
7382 } );
7383 this.removeButton = new OO.ui.ButtonWidget( {
7384 $: this.$,
7385 framed: false,
7386 icon: 'remove',
7387 title: OO.ui.msg( 'ooui-outline-control-remove' )
7388 } );
7390 // Events
7391 outline.connect( this, {
7392 select: 'onOutlineChange',
7393 add: 'onOutlineChange',
7394 remove: 'onOutlineChange'
7395 } );
7396 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
7397 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
7398 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
7400 // Initialization
7401 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7402 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
7403 this.$movers
7404 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7405 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7406 this.$element.append( this.$icon, this.$group, this.$movers );
7409 /* Setup */
7411 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7412 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7413 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconedElement );
7415 /* Events */
7418 * @event move
7419 * @param {number} places Number of places to move
7423 * @event remove
7426 /* Methods */
7429 * Handle outline change events.
7431 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7432 var i, len, firstMovable, lastMovable,
7433 items = this.outline.getItems(),
7434 selectedItem = this.outline.getSelectedItem(),
7435 movable = selectedItem && selectedItem.isMovable(),
7436 removable = selectedItem && selectedItem.isRemovable();
7438 if ( movable ) {
7439 i = -1;
7440 len = items.length;
7441 while ( ++i < len ) {
7442 if ( items[i].isMovable() ) {
7443 firstMovable = items[i];
7444 break;
7447 i = len;
7448 while ( i-- ) {
7449 if ( items[i].isMovable() ) {
7450 lastMovable = items[i];
7451 break;
7455 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7456 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7457 this.removeButton.setDisabled( !removable );
7461 * Mixin for widgets with a boolean on/off state.
7463 * @abstract
7464 * @class
7466 * @constructor
7467 * @param {Object} [config] Configuration options
7468 * @cfg {boolean} [value=false] Initial value
7470 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
7471 // Configuration initialization
7472 config = config || {};
7474 // Properties
7475 this.value = null;
7477 // Initialization
7478 this.$element.addClass( 'oo-ui-toggleWidget' );
7479 this.setValue( !!config.value );
7482 /* Events */
7485 * @event change
7486 * @param {boolean} value Changed value
7489 /* Methods */
7492 * Get the value of the toggle.
7494 * @return {boolean}
7496 OO.ui.ToggleWidget.prototype.getValue = function () {
7497 return this.value;
7501 * Set the value of the toggle.
7503 * @param {boolean} value New value
7504 * @fires change
7505 * @chainable
7507 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
7508 value = !!value;
7509 if ( this.value !== value ) {
7510 this.value = value;
7511 this.emit( 'change', value );
7512 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
7513 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
7515 return this;
7519 * Group widget for multiple related buttons.
7521 * Use together with OO.ui.ButtonWidget.
7523 * @class
7524 * @extends OO.ui.Widget
7525 * @mixins OO.ui.GroupElement
7527 * @constructor
7528 * @param {Object} [config] Configuration options
7529 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
7531 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
7532 // Parent constructor
7533 OO.ui.ButtonGroupWidget.super.call( this, config );
7535 // Mixin constructors
7536 OO.ui.GroupElement.call( this, this.$element, config );
7538 // Initialization
7539 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
7540 if ( $.isArray( config.items ) ) {
7541 this.addItems( config.items );
7545 /* Setup */
7547 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
7548 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
7551 * Generic widget for buttons.
7553 * @class
7554 * @extends OO.ui.Widget
7555 * @mixins OO.ui.ButtonedElement
7556 * @mixins OO.ui.IconedElement
7557 * @mixins OO.ui.IndicatedElement
7558 * @mixins OO.ui.LabeledElement
7559 * @mixins OO.ui.TitledElement
7560 * @mixins OO.ui.FlaggableElement
7562 * @constructor
7563 * @param {Object} [config] Configuration options
7564 * @cfg {string} [href] Hyperlink to visit when clicked
7565 * @cfg {string} [target] Target to open hyperlink in
7567 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
7568 // Configuration initialization
7569 config = $.extend( { target: '_blank' }, config );
7571 // Parent constructor
7572 OO.ui.ButtonWidget.super.call( this, config );
7574 // Mixin constructors
7575 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
7576 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
7577 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
7578 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
7579 OO.ui.TitledElement.call( this, this.$button, config );
7580 OO.ui.FlaggableElement.call( this, config );
7582 // Properties
7583 this.href = null;
7584 this.target = null;
7585 this.isHyperlink = false;
7587 // Events
7588 this.$button.on( {
7589 click: OO.ui.bind( this.onClick, this ),
7590 keypress: OO.ui.bind( this.onKeyPress, this )
7591 } );
7593 // Initialization
7594 this.$button.append( this.$icon, this.$label, this.$indicator );
7595 this.$element
7596 .addClass( 'oo-ui-buttonWidget' )
7597 .append( this.$button );
7598 this.setHref( config.href );
7599 this.setTarget( config.target );
7602 /* Setup */
7604 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
7605 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonedElement );
7606 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconedElement );
7607 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatedElement );
7608 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabeledElement );
7609 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
7610 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggableElement );
7612 /* Events */
7615 * @event click
7618 /* Methods */
7621 * Handles mouse click events.
7623 * @param {jQuery.Event} e Mouse click event
7624 * @fires click
7626 OO.ui.ButtonWidget.prototype.onClick = function () {
7627 if ( !this.isDisabled() ) {
7628 this.emit( 'click' );
7629 if ( this.isHyperlink ) {
7630 return true;
7633 return false;
7637 * Handles keypress events.
7639 * @param {jQuery.Event} e Keypress event
7640 * @fires click
7642 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
7643 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
7644 this.onClick();
7645 if ( this.isHyperlink ) {
7646 return true;
7649 return false;
7653 * Get hyperlink location.
7655 * @return {string} Hyperlink location
7657 OO.ui.ButtonWidget.prototype.getHref = function () {
7658 return this.href;
7662 * Get hyperlink target.
7664 * @return {string} Hyperlink target
7666 OO.ui.ButtonWidget.prototype.getTarget = function () {
7667 return this.target;
7671 * Set hyperlink location.
7673 * @param {string|null} href Hyperlink location, null to remove
7675 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
7676 href = typeof href === 'string' ? href : null;
7678 if ( href !== this.href ) {
7679 this.href = href;
7680 if ( href !== null ) {
7681 this.$button.attr( 'href', href );
7682 this.isHyperlink = true;
7683 } else {
7684 this.$button.removeAttr( 'href' );
7685 this.isHyperlink = false;
7689 return this;
7693 * Set hyperlink target.
7695 * @param {string|null} target Hyperlink target, null to remove
7697 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
7698 target = typeof target === 'string' ? target : null;
7700 if ( target !== this.target ) {
7701 this.target = target;
7702 if ( target !== null ) {
7703 this.$button.attr( 'target', target );
7704 } else {
7705 this.$button.removeAttr( 'target' );
7709 return this;
7713 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
7715 * @class
7716 * @extends OO.ui.ButtonWidget
7718 * @constructor
7719 * @param {Object} [config] Configuration options
7720 * @cfg {string} [action] Symbolic action name
7721 * @cfg {string[]} [modes] Symbolic mode names
7723 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
7724 // Config intialization
7725 config = $.extend( { framed: false }, config );
7727 // Parent constructor
7728 OO.ui.ActionWidget.super.call( this, config );
7730 // Properties
7731 this.action = config.action || '';
7732 this.modes = config.modes || [];
7733 this.width = 0;
7734 this.height = 0;
7736 // Initialization
7737 this.$element.addClass( 'oo-ui-actionWidget' );
7740 /* Setup */
7742 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
7744 /* Events */
7747 * @event resize
7750 /* Methods */
7753 * Check if action is available in a certain mode.
7755 * @param {string} mode Name of mode
7756 * @return {boolean} Has mode
7758 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
7759 return this.modes.indexOf( mode ) !== -1;
7763 * Get symbolic action name.
7765 * @return {string}
7767 OO.ui.ActionWidget.prototype.getAction = function () {
7768 return this.action;
7772 * Get symbolic action name.
7774 * @return {string}
7776 OO.ui.ActionWidget.prototype.getModes = function () {
7777 return this.modes.slice();
7781 * Emit a resize event if the size has changed.
7783 * @chainable
7785 OO.ui.ActionWidget.prototype.propagateResize = function () {
7786 var width, height;
7788 if ( this.isElementAttached() ) {
7789 width = this.$element.width();
7790 height = this.$element.height();
7792 if ( width !== this.width || height !== this.height ) {
7793 this.width = width;
7794 this.height = height;
7795 this.emit( 'resize' );
7799 return this;
7803 * @inheritdoc
7805 OO.ui.ActionWidget.prototype.setIcon = function () {
7806 // Mixin method
7807 OO.ui.IconedElement.prototype.setIcon.apply( this, arguments );
7808 this.propagateResize();
7810 return this;
7814 * @inheritdoc
7816 OO.ui.ActionWidget.prototype.setLabel = function () {
7817 // Mixin method
7818 OO.ui.LabeledElement.prototype.setLabel.apply( this, arguments );
7819 this.propagateResize();
7821 return this;
7825 * @inheritdoc
7827 OO.ui.ActionWidget.prototype.setFlags = function () {
7828 // Mixin method
7829 OO.ui.FlaggableElement.prototype.setFlags.apply( this, arguments );
7830 this.propagateResize();
7832 return this;
7836 * @inheritdoc
7838 OO.ui.ActionWidget.prototype.clearFlags = function () {
7839 // Mixin method
7840 OO.ui.FlaggableElement.prototype.clearFlags.apply( this, arguments );
7841 this.propagateResize();
7843 return this;
7847 * Toggle visibility of button.
7849 * @param {boolean} [show] Show button, omit to toggle visibility
7850 * @chainable
7852 OO.ui.ActionWidget.prototype.toggle = function () {
7853 // Parent method
7854 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
7855 this.propagateResize();
7857 return this;
7861 * Button that shows and hides a popup.
7863 * @class
7864 * @extends OO.ui.ButtonWidget
7865 * @mixins OO.ui.PopuppableElement
7867 * @constructor
7868 * @param {Object} [config] Configuration options
7870 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
7871 // Parent constructor
7872 OO.ui.PopupButtonWidget.super.call( this, config );
7874 // Mixin constructors
7875 OO.ui.PopuppableElement.call( this, config );
7877 // Initialization
7878 this.$element
7879 .addClass( 'oo-ui-popupButtonWidget' )
7880 .append( this.popup.$element );
7883 /* Setup */
7885 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
7886 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopuppableElement );
7888 /* Methods */
7891 * Handles mouse click events.
7893 * @param {jQuery.Event} e Mouse click event
7895 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
7896 // Skip clicks within the popup
7897 if ( $.contains( this.popup.$element[0], e.target ) ) {
7898 return;
7901 if ( !this.isDisabled() ) {
7902 this.popup.toggle();
7903 // Parent method
7904 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
7906 return false;
7910 * Button that toggles on and off.
7912 * @class
7913 * @extends OO.ui.ButtonWidget
7914 * @mixins OO.ui.ToggleWidget
7916 * @constructor
7917 * @param {Object} [config] Configuration options
7918 * @cfg {boolean} [value=false] Initial value
7920 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
7921 // Configuration initialization
7922 config = config || {};
7924 // Parent constructor
7925 OO.ui.ToggleButtonWidget.super.call( this, config );
7927 // Mixin constructors
7928 OO.ui.ToggleWidget.call( this, config );
7930 // Initialization
7931 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
7934 /* Setup */
7936 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
7937 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
7939 /* Methods */
7942 * @inheritdoc
7944 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
7945 if ( !this.isDisabled() ) {
7946 this.setValue( !this.value );
7949 // Parent method
7950 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
7954 * @inheritdoc
7956 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
7957 value = !!value;
7958 if ( value !== this.value ) {
7959 this.setActive( value );
7962 // Parent method (from mixin)
7963 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
7965 return this;
7969 * Icon widget.
7971 * @class
7972 * @extends OO.ui.Widget
7973 * @mixins OO.ui.IconedElement
7974 * @mixins OO.ui.TitledElement
7976 * @constructor
7977 * @param {Object} [config] Configuration options
7979 OO.ui.IconWidget = function OoUiIconWidget( config ) {
7980 // Config intialization
7981 config = config || {};
7983 // Parent constructor
7984 OO.ui.IconWidget.super.call( this, config );
7986 // Mixin constructors
7987 OO.ui.IconedElement.call( this, this.$element, config );
7988 OO.ui.TitledElement.call( this, this.$element, config );
7990 // Initialization
7991 this.$element.addClass( 'oo-ui-iconWidget' );
7994 /* Setup */
7996 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
7997 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconedElement );
7998 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
8000 /* Static Properties */
8002 OO.ui.IconWidget.static.tagName = 'span';
8005 * Indicator widget.
8007 * See OO.ui.IndicatedElement for more information.
8009 * @class
8010 * @extends OO.ui.Widget
8011 * @mixins OO.ui.IndicatedElement
8012 * @mixins OO.ui.TitledElement
8014 * @constructor
8015 * @param {Object} [config] Configuration options
8017 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
8018 // Config intialization
8019 config = config || {};
8021 // Parent constructor
8022 OO.ui.IndicatorWidget.super.call( this, config );
8024 // Mixin constructors
8025 OO.ui.IndicatedElement.call( this, this.$element, config );
8026 OO.ui.TitledElement.call( this, this.$element, config );
8028 // Initialization
8029 this.$element.addClass( 'oo-ui-indicatorWidget' );
8032 /* Setup */
8034 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
8035 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatedElement );
8036 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
8038 /* Static Properties */
8040 OO.ui.IndicatorWidget.static.tagName = 'span';
8043 * Inline menu of options.
8045 * Inline menus provide a control for accessing a menu and compose a menu within the widget, which
8046 * can be accessed using the #getMenu method.
8048 * Use with OO.ui.MenuOptionWidget.
8050 * @class
8051 * @extends OO.ui.Widget
8052 * @mixins OO.ui.IconedElement
8053 * @mixins OO.ui.IndicatedElement
8054 * @mixins OO.ui.LabeledElement
8055 * @mixins OO.ui.TitledElement
8057 * @constructor
8058 * @param {Object} [config] Configuration options
8059 * @cfg {Object} [menu] Configuration options to pass to menu widget
8061 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
8062 // Configuration initialization
8063 config = $.extend( { indicator: 'down' }, config );
8065 // Parent constructor
8066 OO.ui.InlineMenuWidget.super.call( this, config );
8068 // Mixin constructors
8069 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
8070 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
8071 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
8072 OO.ui.TitledElement.call( this, this.$label, config );
8074 // Properties
8075 this.menu = new OO.ui.MenuWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
8076 this.$handle = this.$( '<span>' );
8078 // Events
8079 this.$element.on( { click: OO.ui.bind( this.onClick, this ) } );
8080 this.menu.connect( this, { select: 'onMenuSelect' } );
8082 // Initialization
8083 this.$handle
8084 .addClass( 'oo-ui-inlineMenuWidget-handle' )
8085 .append( this.$icon, this.$label, this.$indicator );
8086 this.$element
8087 .addClass( 'oo-ui-inlineMenuWidget' )
8088 .append( this.$handle, this.menu.$element );
8091 /* Setup */
8093 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
8094 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconedElement );
8095 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatedElement );
8096 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabeledElement );
8097 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
8099 /* Methods */
8102 * Get the menu.
8104 * @return {OO.ui.MenuWidget} Menu of widget
8106 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
8107 return this.menu;
8111 * Handles menu select events.
8113 * @param {OO.ui.MenuItemWidget} item Selected menu item
8115 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
8116 var selectedLabel;
8118 if ( !item ) {
8119 return;
8122 selectedLabel = item.getLabel();
8124 // If the label is a DOM element, clone it, because setLabel will append() it
8125 if ( selectedLabel instanceof jQuery ) {
8126 selectedLabel = selectedLabel.clone();
8129 this.setLabel( selectedLabel );
8133 * Handles mouse click events.
8135 * @param {jQuery.Event} e Mouse click event
8137 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
8138 // Skip clicks within the menu
8139 if ( $.contains( this.menu.$element[0], e.target ) ) {
8140 return;
8143 if ( !this.isDisabled() ) {
8144 if ( this.menu.isVisible() ) {
8145 this.menu.toggle( false );
8146 } else {
8147 this.menu.toggle( true );
8150 return false;
8154 * Base class for input widgets.
8156 * @abstract
8157 * @class
8158 * @extends OO.ui.Widget
8160 * @constructor
8161 * @param {Object} [config] Configuration options
8162 * @cfg {string} [name=''] HTML input name
8163 * @cfg {string} [value=''] Input value
8164 * @cfg {boolean} [readOnly=false] Prevent changes
8165 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
8167 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8168 // Config intialization
8169 config = $.extend( { readOnly: false }, config );
8171 // Parent constructor
8172 OO.ui.InputWidget.super.call( this, config );
8174 // Properties
8175 this.$input = this.getInputElement( config );
8176 this.value = '';
8177 this.readOnly = false;
8178 this.inputFilter = config.inputFilter;
8180 // Events
8181 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
8183 // Initialization
8184 this.$input
8185 .attr( 'name', config.name )
8186 .prop( 'disabled', this.isDisabled() );
8187 this.setReadOnly( config.readOnly );
8188 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
8189 this.setValue( config.value );
8192 /* Setup */
8194 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8196 /* Events */
8199 * @event change
8200 * @param value
8203 /* Methods */
8206 * Get input element.
8208 * @param {Object} [config] Configuration options
8209 * @return {jQuery} Input element
8211 OO.ui.InputWidget.prototype.getInputElement = function () {
8212 return this.$( '<input>' );
8216 * Handle potentially value-changing events.
8218 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8220 OO.ui.InputWidget.prototype.onEdit = function () {
8221 var widget = this;
8222 if ( !this.isDisabled() ) {
8223 // Allow the stack to clear so the value will be updated
8224 setTimeout( function () {
8225 widget.setValue( widget.$input.val() );
8226 } );
8231 * Get the value of the input.
8233 * @return {string} Input value
8235 OO.ui.InputWidget.prototype.getValue = function () {
8236 return this.value;
8240 * Sets the direction of the current input, either RTL or LTR
8242 * @param {boolean} isRTL
8244 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
8245 if ( isRTL ) {
8246 this.$input.removeClass( 'oo-ui-ltr' );
8247 this.$input.addClass( 'oo-ui-rtl' );
8248 } else {
8249 this.$input.removeClass( 'oo-ui-rtl' );
8250 this.$input.addClass( 'oo-ui-ltr' );
8255 * Set the value of the input.
8257 * @param {string} value New value
8258 * @fires change
8259 * @chainable
8261 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8262 value = this.sanitizeValue( value );
8263 if ( this.value !== value ) {
8264 this.value = value;
8265 this.emit( 'change', this.value );
8267 // Update the DOM if it has changed. Note that with sanitizeValue, it
8268 // is possible for the DOM value to change without this.value changing.
8269 if ( this.$input.val() !== this.value ) {
8270 this.$input.val( this.value );
8272 return this;
8276 * Sanitize incoming value.
8278 * Ensures value is a string, and converts undefined and null to empty strings.
8280 * @param {string} value Original value
8281 * @return {string} Sanitized value
8283 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
8284 if ( value === undefined || value === null ) {
8285 return '';
8286 } else if ( this.inputFilter ) {
8287 return this.inputFilter( String( value ) );
8288 } else {
8289 return String( value );
8294 * Simulate the behavior of clicking on a label bound to this input.
8296 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
8297 if ( !this.isDisabled() ) {
8298 if ( this.$input.is( ':checkbox,:radio' ) ) {
8299 this.$input.click();
8300 } else if ( this.$input.is( ':input' ) ) {
8301 this.$input[0].focus();
8307 * Check if the widget is read-only.
8309 * @return {boolean}
8311 OO.ui.InputWidget.prototype.isReadOnly = function () {
8312 return this.readOnly;
8316 * Set the read-only state of the widget.
8318 * This should probably change the widgets's appearance and prevent it from being used.
8320 * @param {boolean} state Make input read-only
8321 * @chainable
8323 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
8324 this.readOnly = !!state;
8325 this.$input.prop( 'readOnly', this.readOnly );
8326 return this;
8330 * @inheritdoc
8332 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8333 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
8334 if ( this.$input ) {
8335 this.$input.prop( 'disabled', this.isDisabled() );
8337 return this;
8341 * Focus the input.
8343 * @chainable
8345 OO.ui.InputWidget.prototype.focus = function () {
8346 this.$input[0].focus();
8347 return this;
8351 * Blur the input.
8353 * @chainable
8355 OO.ui.InputWidget.prototype.blur = function () {
8356 this.$input[0].blur();
8357 return this;
8361 * Checkbox input widget.
8363 * @class
8364 * @extends OO.ui.InputWidget
8366 * @constructor
8367 * @param {Object} [config] Configuration options
8369 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
8370 // Parent constructor
8371 OO.ui.CheckboxInputWidget.super.call( this, config );
8373 // Initialization
8374 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
8377 /* Setup */
8379 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
8381 /* Events */
8383 /* Methods */
8386 * Get input element.
8388 * @return {jQuery} Input element
8390 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
8391 return this.$( '<input type="checkbox" />' );
8395 * Get checked state of the checkbox
8397 * @return {boolean} If the checkbox is checked
8399 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
8400 return this.value;
8404 * Set value
8406 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
8407 value = !!value;
8408 if ( this.value !== value ) {
8409 this.value = value;
8410 this.$input.prop( 'checked', this.value );
8411 this.emit( 'change', this.value );
8416 * @inheritdoc
8418 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
8419 var widget = this;
8420 if ( !this.isDisabled() ) {
8421 // Allow the stack to clear so the value will be updated
8422 setTimeout( function () {
8423 widget.setValue( widget.$input.prop( 'checked' ) );
8424 } );
8429 * Input widget with a text field.
8431 * @class
8432 * @extends OO.ui.InputWidget
8434 * @constructor
8435 * @param {Object} [config] Configuration options
8436 * @cfg {string} [placeholder] Placeholder text
8437 * @cfg {string} [icon] Symbolic name of icon
8438 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8439 * @cfg {boolean} [autosize=false] Automatically resize to fit content
8440 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
8442 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
8443 var widget = this;
8444 config = $.extend( { maxRows: 10 }, config );
8446 // Parent constructor
8447 OO.ui.TextInputWidget.super.call( this, config );
8449 // Properties
8450 this.pending = 0;
8451 this.multiline = !!config.multiline;
8452 this.autosize = !!config.autosize;
8453 this.maxRows = config.maxRows;
8455 // Events
8456 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
8457 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
8459 // Initialization
8460 this.$element.addClass( 'oo-ui-textInputWidget' );
8461 if ( config.icon ) {
8462 this.$element.addClass( 'oo-ui-textInputWidget-decorated' );
8463 this.$element.append(
8464 this.$( '<span>' )
8465 .addClass( 'oo-ui-textInputWidget-icon oo-ui-icon-' + config.icon )
8466 .mousedown( function () {
8467 widget.$input[0].focus();
8468 return false;
8472 if ( config.placeholder ) {
8473 this.$input.attr( 'placeholder', config.placeholder );
8475 this.$element.attr( 'role', 'textbox' );
8478 /* Setup */
8480 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8482 /* Events */
8485 * User presses enter inside the text box.
8487 * Not called if input is multiline.
8489 * @event enter
8492 /* Methods */
8495 * Handle key press events.
8497 * @param {jQuery.Event} e Key press event
8498 * @fires enter If enter key is pressed and input is not multiline
8500 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8501 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8502 this.emit( 'enter' );
8507 * Handle element attach events.
8509 * @param {jQuery.Event} e Element attach event
8511 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8512 this.adjustSize();
8516 * @inheritdoc
8518 OO.ui.TextInputWidget.prototype.onEdit = function () {
8519 this.adjustSize();
8521 // Parent method
8522 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
8526 * @inheritdoc
8528 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
8529 // Parent method
8530 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
8532 this.adjustSize();
8533 return this;
8537 * Automatically adjust the size of the text input.
8539 * This only affects multi-line inputs that are auto-sized.
8541 * @chainable
8543 OO.ui.TextInputWidget.prototype.adjustSize = function () {
8544 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
8546 if ( this.multiline && this.autosize ) {
8547 $clone = this.$input.clone()
8548 .val( this.$input.val() )
8549 .css( { height: 0 } )
8550 .insertAfter( this.$input );
8551 // Set inline height property to 0 to measure scroll height
8552 scrollHeight = $clone[0].scrollHeight;
8553 // Remove inline height property to measure natural heights
8554 $clone.css( 'height', '' );
8555 innerHeight = $clone.innerHeight();
8556 outerHeight = $clone.outerHeight();
8557 // Measure max rows height
8558 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
8559 maxInnerHeight = $clone.innerHeight();
8560 $clone.removeAttr( 'rows' ).css( 'height', '' );
8561 $clone.remove();
8562 idealHeight = Math.min( maxInnerHeight, scrollHeight );
8563 // Only apply inline height when expansion beyond natural height is needed
8564 this.$input.css(
8565 'height',
8566 // Use the difference between the inner and outer height as a buffer
8567 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
8570 return this;
8574 * Get input element.
8576 * @param {Object} [config] Configuration options
8577 * @return {jQuery} Input element
8579 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
8580 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
8583 /* Methods */
8586 * Check if input supports multiple lines.
8588 * @return {boolean}
8590 OO.ui.TextInputWidget.prototype.isMultiline = function () {
8591 return !!this.multiline;
8595 * Check if input automatically adjusts its size.
8597 * @return {boolean}
8599 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
8600 return !!this.autosize;
8604 * Check if input is pending.
8606 * @return {boolean}
8608 OO.ui.TextInputWidget.prototype.isPending = function () {
8609 return !!this.pending;
8613 * Increase the pending stack.
8615 * @chainable
8617 OO.ui.TextInputWidget.prototype.pushPending = function () {
8618 if ( this.pending === 0 ) {
8619 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
8620 this.$input.addClass( 'oo-ui-texture-pending' );
8622 this.pending++;
8624 return this;
8628 * Reduce the pending stack.
8630 * Clamped at zero.
8632 * @chainable
8634 OO.ui.TextInputWidget.prototype.popPending = function () {
8635 if ( this.pending === 1 ) {
8636 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
8637 this.$input.removeClass( 'oo-ui-texture-pending' );
8639 this.pending = Math.max( 0, this.pending - 1 );
8641 return this;
8645 * Select the contents of the input.
8647 * @chainable
8649 OO.ui.TextInputWidget.prototype.select = function () {
8650 this.$input.select();
8651 return this;
8655 * Label widget.
8657 * @class
8658 * @extends OO.ui.Widget
8659 * @mixins OO.ui.LabeledElement
8661 * @constructor
8662 * @param {Object} [config] Configuration options
8664 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
8665 // Config intialization
8666 config = config || {};
8668 // Parent constructor
8669 OO.ui.LabelWidget.super.call( this, config );
8671 // Mixin constructors
8672 OO.ui.LabeledElement.call( this, this.$element, config );
8674 // Properties
8675 this.input = config.input;
8677 // Events
8678 if ( this.input instanceof OO.ui.InputWidget ) {
8679 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
8682 // Initialization
8683 this.$element.addClass( 'oo-ui-labelWidget' );
8686 /* Setup */
8688 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
8689 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabeledElement );
8691 /* Static Properties */
8693 OO.ui.LabelWidget.static.tagName = 'label';
8695 /* Methods */
8698 * Handles label mouse click events.
8700 * @param {jQuery.Event} e Mouse click event
8702 OO.ui.LabelWidget.prototype.onClick = function () {
8703 this.input.simulateLabelClick();
8704 return false;
8708 * Generic option widget for use with OO.ui.SelectWidget.
8710 * @class
8711 * @extends OO.ui.Widget
8712 * @mixins OO.ui.LabeledElement
8713 * @mixins OO.ui.FlaggableElement
8715 * @constructor
8716 * @param {Mixed} data Option data
8717 * @param {Object} [config] Configuration options
8718 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
8720 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
8721 // Config intialization
8722 config = config || {};
8724 // Parent constructor
8725 OO.ui.OptionWidget.super.call( this, config );
8727 // Mixin constructors
8728 OO.ui.ItemWidget.call( this );
8729 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
8730 OO.ui.FlaggableElement.call( this, config );
8732 // Properties
8733 this.data = data;
8734 this.selected = false;
8735 this.highlighted = false;
8736 this.pressed = false;
8738 // Initialization
8739 this.$element
8740 .data( 'oo-ui-optionWidget', this )
8741 .attr( 'rel', config.rel )
8742 .attr( 'role', 'option' )
8743 .addClass( 'oo-ui-optionWidget' )
8744 .append( this.$label );
8745 this.$element
8746 .prepend( this.$icon )
8747 .append( this.$indicator );
8750 /* Setup */
8752 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
8753 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
8754 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabeledElement );
8755 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggableElement );
8757 /* Static Properties */
8759 OO.ui.OptionWidget.static.tagName = 'li';
8761 OO.ui.OptionWidget.static.selectable = true;
8763 OO.ui.OptionWidget.static.highlightable = true;
8765 OO.ui.OptionWidget.static.pressable = true;
8767 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
8769 /* Methods */
8772 * Check if option can be selected.
8774 * @return {boolean} Item is selectable
8776 OO.ui.OptionWidget.prototype.isSelectable = function () {
8777 return this.constructor.static.selectable && !this.isDisabled();
8781 * Check if option can be highlighted.
8783 * @return {boolean} Item is highlightable
8785 OO.ui.OptionWidget.prototype.isHighlightable = function () {
8786 return this.constructor.static.highlightable && !this.isDisabled();
8790 * Check if option can be pressed.
8792 * @return {boolean} Item is pressable
8794 OO.ui.OptionWidget.prototype.isPressable = function () {
8795 return this.constructor.static.pressable && !this.isDisabled();
8799 * Check if option is selected.
8801 * @return {boolean} Item is selected
8803 OO.ui.OptionWidget.prototype.isSelected = function () {
8804 return this.selected;
8808 * Check if option is highlighted.
8810 * @return {boolean} Item is highlighted
8812 OO.ui.OptionWidget.prototype.isHighlighted = function () {
8813 return this.highlighted;
8817 * Check if option is pressed.
8819 * @return {boolean} Item is pressed
8821 OO.ui.OptionWidget.prototype.isPressed = function () {
8822 return this.pressed;
8826 * Set selected state.
8828 * @param {boolean} [state=false] Select option
8829 * @chainable
8831 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
8832 if ( this.constructor.static.selectable ) {
8833 this.selected = !!state;
8834 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
8835 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
8836 this.scrollElementIntoView();
8839 return this;
8843 * Set highlighted state.
8845 * @param {boolean} [state=false] Highlight option
8846 * @chainable
8848 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
8849 if ( this.constructor.static.highlightable ) {
8850 this.highlighted = !!state;
8851 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
8853 return this;
8857 * Set pressed state.
8859 * @param {boolean} [state=false] Press option
8860 * @chainable
8862 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
8863 if ( this.constructor.static.pressable ) {
8864 this.pressed = !!state;
8865 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
8867 return this;
8871 * Make the option's highlight flash.
8873 * While flashing, the visual style of the pressed state is removed if present.
8875 * @return {jQuery.Promise} Promise resolved when flashing is done
8877 OO.ui.OptionWidget.prototype.flash = function () {
8878 var widget = this,
8879 $element = this.$element,
8880 deferred = $.Deferred();
8882 if ( !this.isDisabled() && this.constructor.static.pressable ) {
8883 $element.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
8884 setTimeout( function () {
8885 // Restore original classes
8886 $element
8887 .toggleClass( 'oo-ui-optionWidget-highlighted', widget.highlighted )
8888 .toggleClass( 'oo-ui-optionWidget-pressed', widget.pressed );
8890 setTimeout( function () {
8891 deferred.resolve();
8892 }, 100 );
8894 }, 100 );
8897 return deferred.promise();
8901 * Get option data.
8903 * @return {Mixed} Option data
8905 OO.ui.OptionWidget.prototype.getData = function () {
8906 return this.data;
8910 * Option widget with an option icon and indicator.
8912 * Use together with OO.ui.SelectWidget.
8914 * @class
8915 * @extends OO.ui.OptionWidget
8916 * @mixins OO.ui.IconedElement
8917 * @mixins OO.ui.IndicatedElement
8919 * @constructor
8920 * @param {Mixed} data Option data
8921 * @param {Object} [config] Configuration options
8923 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( data, config ) {
8924 // Parent constructor
8925 OO.ui.DecoratedOptionWidget.super.call( this, data, config );
8927 // Mixin constructors
8928 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
8929 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
8931 // Initialization
8932 this.$element
8933 .addClass( 'oo-ui-decoratedOptionWidget' )
8934 .prepend( this.$icon )
8935 .append( this.$indicator );
8938 /* Setup */
8940 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
8941 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconedElement );
8942 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatedElement );
8945 * Option widget that looks like a button.
8947 * Use together with OO.ui.ButtonSelectWidget.
8949 * @class
8950 * @extends OO.ui.DecoratedOptionWidget
8951 * @mixins OO.ui.ButtonedElement
8953 * @constructor
8954 * @param {Mixed} data Option data
8955 * @param {Object} [config] Configuration options
8957 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
8958 // Parent constructor
8959 OO.ui.ButtonOptionWidget.super.call( this, data, config );
8961 // Mixin constructors
8962 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
8964 // Initialization
8965 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
8966 this.$button.append( this.$element.contents() );
8967 this.$element.append( this.$button );
8970 /* Setup */
8972 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
8973 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonedElement );
8975 /* Static Properties */
8977 // Allow button mouse down events to pass through so they can be handled by the parent select widget
8978 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
8980 /* Methods */
8983 * @inheritdoc
8985 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
8986 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
8988 if ( this.constructor.static.selectable ) {
8989 this.setActive( state );
8992 return this;
8996 * Item of an OO.ui.MenuWidget.
8998 * @class
8999 * @extends OO.ui.DecoratedOptionWidget
9001 * @constructor
9002 * @param {Mixed} data Item data
9003 * @param {Object} [config] Configuration options
9005 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
9006 // Configuration initialization
9007 config = $.extend( { icon: 'check' }, config );
9009 // Parent constructor
9010 OO.ui.MenuItemWidget.super.call( this, data, config );
9012 // Initialization
9013 this.$element
9014 .attr( 'role', 'menuitem' )
9015 .addClass( 'oo-ui-menuItemWidget' );
9018 /* Setup */
9020 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.DecoratedOptionWidget );
9023 * Section to group one or more items in a OO.ui.MenuWidget.
9025 * @class
9026 * @extends OO.ui.DecoratedOptionWidget
9028 * @constructor
9029 * @param {Mixed} data Item data
9030 * @param {Object} [config] Configuration options
9032 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
9033 // Parent constructor
9034 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
9036 // Initialization
9037 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
9040 /* Setup */
9042 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.DecoratedOptionWidget );
9044 /* Static Properties */
9046 OO.ui.MenuSectionItemWidget.static.selectable = false;
9048 OO.ui.MenuSectionItemWidget.static.highlightable = false;
9051 * Items for an OO.ui.OutlineWidget.
9053 * @class
9054 * @extends OO.ui.DecoratedOptionWidget
9056 * @constructor
9057 * @param {Mixed} data Item data
9058 * @param {Object} [config] Configuration options
9059 * @cfg {number} [level] Indentation level
9060 * @cfg {boolean} [movable] Allow modification from outline controls
9062 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
9063 // Config intialization
9064 config = config || {};
9066 // Parent constructor
9067 OO.ui.OutlineItemWidget.super.call( this, data, config );
9069 // Properties
9070 this.level = 0;
9071 this.movable = !!config.movable;
9072 this.removable = !!config.removable;
9074 // Initialization
9075 this.$element.addClass( 'oo-ui-outlineItemWidget' );
9076 this.setLevel( config.level );
9079 /* Setup */
9081 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.DecoratedOptionWidget );
9083 /* Static Properties */
9085 OO.ui.OutlineItemWidget.static.highlightable = false;
9087 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
9089 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
9091 OO.ui.OutlineItemWidget.static.levels = 3;
9093 /* Methods */
9096 * Check if item is movable.
9098 * Movablilty is used by outline controls.
9100 * @return {boolean} Item is movable
9102 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
9103 return this.movable;
9107 * Check if item is removable.
9109 * Removablilty is used by outline controls.
9111 * @return {boolean} Item is removable
9113 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
9114 return this.removable;
9118 * Get indentation level.
9120 * @return {number} Indentation level
9122 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
9123 return this.level;
9127 * Set movability.
9129 * Movablilty is used by outline controls.
9131 * @param {boolean} movable Item is movable
9132 * @chainable
9134 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
9135 this.movable = !!movable;
9136 return this;
9140 * Set removability.
9142 * Removablilty is used by outline controls.
9144 * @param {boolean} movable Item is removable
9145 * @chainable
9147 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
9148 this.removable = !!removable;
9149 return this;
9153 * Set indentation level.
9155 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
9156 * @chainable
9158 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
9159 var levels = this.constructor.static.levels,
9160 levelClass = this.constructor.static.levelClass,
9161 i = levels;
9163 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
9164 while ( i-- ) {
9165 if ( this.level === i ) {
9166 this.$element.addClass( levelClass + i );
9167 } else {
9168 this.$element.removeClass( levelClass + i );
9172 return this;
9176 * Container for content that is overlaid and positioned absolutely.
9178 * @class
9179 * @extends OO.ui.Widget
9180 * @mixins OO.ui.LabeledElement
9182 * @constructor
9183 * @param {Object} [config] Configuration options
9184 * @cfg {number} [width=320] Width of popup in pixels
9185 * @cfg {number} [height] Height of popup, omit to use automatic height
9186 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
9187 * @cfg {string} [align='center'] Alignment of popup to origin
9188 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
9189 * @cfg {jQuery} [$content] Content to append to the popup's body
9190 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
9191 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
9192 * @cfg {boolean} [head] Show label and close button at the top
9193 * @cfg {boolean} [padded] Add padding to the body
9195 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
9196 // Config intialization
9197 config = config || {};
9199 // Parent constructor
9200 OO.ui.PopupWidget.super.call( this, config );
9202 // Mixin constructors
9203 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
9204 OO.ui.ClippableElement.call( this, this.$( '<div>' ), config );
9206 // Properties
9207 this.visible = false;
9208 this.$popup = this.$( '<div>' );
9209 this.$head = this.$( '<div>' );
9210 this.$body = this.$clippable;
9211 this.$anchor = this.$( '<div>' );
9212 this.$container = config.$container || this.$( 'body' );
9213 this.autoClose = !!config.autoClose;
9214 this.$autoCloseIgnore = config.$autoCloseIgnore;
9215 this.transitionTimeout = null;
9216 this.anchor = null;
9217 this.width = config.width !== undefined ? config.width : 320;
9218 this.height = config.height !== undefined ? config.height : null;
9219 this.align = config.align || 'center';
9220 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
9221 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
9223 // Events
9224 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
9226 // Initialization
9227 this.toggleAnchor( config.anchor === undefined || config.anchor );
9228 this.$body.addClass( 'oo-ui-popupWidget-body' );
9229 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
9230 this.$head
9231 .addClass( 'oo-ui-popupWidget-head' )
9232 .append( this.$label, this.closeButton.$element );
9233 if ( !config.head ) {
9234 this.$head.hide();
9236 this.$popup
9237 .addClass( 'oo-ui-popupWidget-popup' )
9238 .append( this.$head, this.$body );
9239 this.$element
9240 .hide()
9241 .addClass( 'oo-ui-popupWidget' )
9242 .append( this.$popup, this.$anchor );
9243 // Move content, which was added to #$element by OO.ui.Widget, to the body
9244 if ( config.$content instanceof jQuery ) {
9245 this.$body.append( config.$content );
9247 if ( config.padded ) {
9248 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
9252 /* Setup */
9254 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
9255 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabeledElement );
9256 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
9258 /* Events */
9261 * @event hide
9265 * @event show
9268 /* Methods */
9271 * Handles mouse down events.
9273 * @param {jQuery.Event} e Mouse down event
9275 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
9276 if (
9277 this.isVisible() &&
9278 !$.contains( this.$element[0], e.target ) &&
9279 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
9281 this.toggle( false );
9286 * Bind mouse down listener.
9288 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
9289 // Capture clicks outside popup
9290 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
9294 * Handles close button click events.
9296 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
9297 if ( this.isVisible() ) {
9298 this.toggle( false );
9303 * Unbind mouse down listener.
9305 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
9306 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
9310 * Set whether to show a anchor.
9312 * @param {boolean} [show] Show anchor, omit to toggle
9314 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
9315 show = show === undefined ? !this.anchored : !!show;
9317 if ( this.anchored !== show ) {
9318 if ( show ) {
9319 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
9320 } else {
9321 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
9323 this.anchored = show;
9328 * Check if showing a anchor.
9330 * @return {boolean} anchor is visible
9332 OO.ui.PopupWidget.prototype.hasAnchor = function () {
9333 return this.anchor;
9337 * @inheritdoc
9339 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
9340 show = show === undefined ? !this.isVisible() : !!show;
9342 var change = show !== this.isVisible();
9344 // Parent method
9345 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
9347 if ( change ) {
9348 if ( show ) {
9349 this.setClipping( true );
9350 if ( this.autoClose ) {
9351 this.bindMouseDownListener();
9353 this.updateDimensions();
9354 } else {
9355 this.setClipping( false );
9356 if ( this.autoClose ) {
9357 this.unbindMouseDownListener();
9362 return this;
9366 * Set the size of the popup.
9368 * Changing the size may also change the popup's position depending on the alignment.
9370 * @param {number} width Width
9371 * @param {number} height Height
9372 * @param {boolean} [transition=false] Use a smooth transition
9373 * @chainable
9375 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
9376 this.width = width;
9377 this.height = height !== undefined ? height : null;
9378 if ( this.isVisible() ) {
9379 this.updateDimensions( transition );
9384 * Update the size and position.
9386 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
9387 * be called automatically.
9389 * @param {boolean} [transition=false] Use a smooth transition
9390 * @chainable
9392 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
9393 var widget = this,
9394 padding = 10,
9395 originOffset = Math.round( this.$element.offset().left ),
9396 containerLeft = Math.round( this.$container.offset().left ),
9397 containerWidth = this.$container.innerWidth(),
9398 containerRight = containerLeft + containerWidth,
9399 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[this.align],
9400 anchorWidth = this.$anchor.width(),
9401 popupLeft = popupOffset - padding,
9402 popupRight = popupOffset + padding + this.width + padding,
9403 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
9404 overlapRight = containerRight - ( originOffset + popupRight );
9406 // Prevent transition from being interrupted
9407 clearTimeout( this.transitionTimeout );
9408 if ( transition ) {
9409 // Enable transition
9410 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
9413 if ( overlapRight < 0 ) {
9414 popupOffset += overlapRight;
9415 } else if ( overlapLeft < 0 ) {
9416 popupOffset -= overlapLeft;
9419 // Adjust offset to avoid anchor being rendered too close to the edge
9420 if ( this.align === 'right' ) {
9421 popupOffset += anchorWidth;
9422 } else if ( this.align === 'left' ) {
9423 popupOffset -= anchorWidth;
9426 // Position body relative to anchor and resize
9427 this.$popup.css( {
9428 left: popupOffset,
9429 width: this.width,
9430 height: this.height !== null ? this.height : 'auto'
9431 } );
9433 if ( transition ) {
9434 // Prevent transitioning after transition is complete
9435 this.transitionTimeout = setTimeout( function () {
9436 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
9437 }, 200 );
9438 } else {
9439 // Prevent transitioning immediately
9440 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
9443 return this;
9447 * Search widget.
9449 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
9450 * Results are cleared and populated each time the query is changed.
9452 * @class
9453 * @extends OO.ui.Widget
9455 * @constructor
9456 * @param {Object} [config] Configuration options
9457 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
9458 * @cfg {string} [value] Initial query value
9460 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
9461 // Configuration intialization
9462 config = config || {};
9464 // Parent constructor
9465 OO.ui.SearchWidget.super.call( this, config );
9467 // Properties
9468 this.query = new OO.ui.TextInputWidget( {
9469 $: this.$,
9470 icon: 'search',
9471 placeholder: config.placeholder,
9472 value: config.value
9473 } );
9474 this.results = new OO.ui.SelectWidget( { $: this.$ } );
9475 this.$query = this.$( '<div>' );
9476 this.$results = this.$( '<div>' );
9478 // Events
9479 this.query.connect( this, {
9480 change: 'onQueryChange',
9481 enter: 'onQueryEnter'
9482 } );
9483 this.results.connect( this, {
9484 highlight: 'onResultsHighlight',
9485 select: 'onResultsSelect'
9486 } );
9487 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
9489 // Initialization
9490 this.$query
9491 .addClass( 'oo-ui-searchWidget-query' )
9492 .append( this.query.$element );
9493 this.$results
9494 .addClass( 'oo-ui-searchWidget-results' )
9495 .append( this.results.$element );
9496 this.$element
9497 .addClass( 'oo-ui-searchWidget' )
9498 .append( this.$results, this.$query );
9501 /* Setup */
9503 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
9505 /* Events */
9508 * @event highlight
9509 * @param {Object|null} item Item data or null if no item is highlighted
9513 * @event select
9514 * @param {Object|null} item Item data or null if no item is selected
9517 /* Methods */
9520 * Handle query key down events.
9522 * @param {jQuery.Event} e Key down event
9524 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
9525 var highlightedItem, nextItem,
9526 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
9528 if ( dir ) {
9529 highlightedItem = this.results.getHighlightedItem();
9530 if ( !highlightedItem ) {
9531 highlightedItem = this.results.getSelectedItem();
9533 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
9534 this.results.highlightItem( nextItem );
9535 nextItem.scrollElementIntoView();
9540 * Handle select widget select events.
9542 * Clears existing results. Subclasses should repopulate items according to new query.
9544 * @param {string} value New value
9546 OO.ui.SearchWidget.prototype.onQueryChange = function () {
9547 // Reset
9548 this.results.clearItems();
9552 * Handle select widget enter key events.
9554 * Selects highlighted item.
9556 * @param {string} value New value
9558 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
9559 // Reset
9560 this.results.selectItem( this.results.getHighlightedItem() );
9564 * Handle select widget highlight events.
9566 * @param {OO.ui.OptionWidget} item Highlighted item
9567 * @fires highlight
9569 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
9570 this.emit( 'highlight', item ? item.getData() : null );
9574 * Handle select widget select events.
9576 * @param {OO.ui.OptionWidget} item Selected item
9577 * @fires select
9579 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
9580 this.emit( 'select', item ? item.getData() : null );
9584 * Get the query input.
9586 * @return {OO.ui.TextInputWidget} Query input
9588 OO.ui.SearchWidget.prototype.getQuery = function () {
9589 return this.query;
9593 * Get the results list.
9595 * @return {OO.ui.SelectWidget} Select list
9597 OO.ui.SearchWidget.prototype.getResults = function () {
9598 return this.results;
9602 * Generic selection of options.
9604 * Items can contain any rendering, and are uniquely identified by a has of thier data. Any widget
9605 * that provides options, from which the user must choose one, should be built on this class.
9607 * Use together with OO.ui.OptionWidget.
9609 * @class
9610 * @extends OO.ui.Widget
9611 * @mixins OO.ui.GroupElement
9613 * @constructor
9614 * @param {Object} [config] Configuration options
9615 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
9617 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
9618 // Config intialization
9619 config = config || {};
9621 // Parent constructor
9622 OO.ui.SelectWidget.super.call( this, config );
9624 // Mixin constructors
9625 OO.ui.GroupWidget.call( this, this.$element, config );
9627 // Properties
9628 this.pressed = false;
9629 this.selecting = null;
9630 this.hashes = {};
9631 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
9632 this.onMouseMoveHandler = OO.ui.bind( this.onMouseMove, this );
9634 // Events
9635 this.$element.on( {
9636 mousedown: OO.ui.bind( this.onMouseDown, this ),
9637 mouseover: OO.ui.bind( this.onMouseOver, this ),
9638 mouseleave: OO.ui.bind( this.onMouseLeave, this )
9639 } );
9641 // Initialization
9642 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
9643 if ( $.isArray( config.items ) ) {
9644 this.addItems( config.items );
9648 /* Setup */
9650 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
9652 // Need to mixin base class as well
9653 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
9654 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
9656 /* Events */
9659 * @event highlight
9660 * @param {OO.ui.OptionWidget|null} item Highlighted item
9664 * @event press
9665 * @param {OO.ui.OptionWidget|null} item Pressed item
9669 * @event select
9670 * @param {OO.ui.OptionWidget|null} item Selected item
9674 * @event choose
9675 * @param {OO.ui.OptionWidget|null} item Chosen item
9679 * @event add
9680 * @param {OO.ui.OptionWidget[]} items Added items
9681 * @param {number} index Index items were added at
9685 * @event remove
9686 * @param {OO.ui.OptionWidget[]} items Removed items
9689 /* Static Properties */
9691 OO.ui.SelectWidget.static.tagName = 'ul';
9693 /* Methods */
9696 * Handle mouse down events.
9698 * @private
9699 * @param {jQuery.Event} e Mouse down event
9701 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
9702 var item;
9704 if ( !this.isDisabled() && e.which === 1 ) {
9705 this.togglePressed( true );
9706 item = this.getTargetItem( e );
9707 if ( item && item.isSelectable() ) {
9708 this.pressItem( item );
9709 this.selecting = item;
9710 this.getElementDocument().addEventListener(
9711 'mouseup',
9712 this.onMouseUpHandler,
9713 true
9715 this.getElementDocument().addEventListener(
9716 'mousemove',
9717 this.onMouseMoveHandler,
9718 true
9722 return false;
9726 * Handle mouse up events.
9728 * @private
9729 * @param {jQuery.Event} e Mouse up event
9731 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
9732 var item;
9734 this.togglePressed( false );
9735 if ( !this.selecting ) {
9736 item = this.getTargetItem( e );
9737 if ( item && item.isSelectable() ) {
9738 this.selecting = item;
9741 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
9742 this.pressItem( null );
9743 this.chooseItem( this.selecting );
9744 this.selecting = null;
9747 this.getElementDocument().removeEventListener(
9748 'mouseup',
9749 this.onMouseUpHandler,
9750 true
9752 this.getElementDocument().removeEventListener(
9753 'mousemove',
9754 this.onMouseMoveHandler,
9755 true
9758 return false;
9762 * Handle mouse move events.
9764 * @private
9765 * @param {jQuery.Event} e Mouse move event
9767 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
9768 var item;
9770 if ( !this.isDisabled() && this.pressed ) {
9771 item = this.getTargetItem( e );
9772 if ( item && item !== this.selecting && item.isSelectable() ) {
9773 this.pressItem( item );
9774 this.selecting = item;
9777 return false;
9781 * Handle mouse over events.
9783 * @private
9784 * @param {jQuery.Event} e Mouse over event
9786 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
9787 var item;
9789 if ( !this.isDisabled() ) {
9790 item = this.getTargetItem( e );
9791 this.highlightItem( item && item.isHighlightable() ? item : null );
9793 return false;
9797 * Handle mouse leave events.
9799 * @private
9800 * @param {jQuery.Event} e Mouse over event
9802 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
9803 if ( !this.isDisabled() ) {
9804 this.highlightItem( null );
9806 return false;
9810 * Get the closest item to a jQuery.Event.
9812 * @private
9813 * @param {jQuery.Event} e
9814 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
9816 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
9817 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
9818 if ( $item.length ) {
9819 return $item.data( 'oo-ui-optionWidget' );
9821 return null;
9825 * Get selected item.
9827 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
9829 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
9830 var i, len;
9832 for ( i = 0, len = this.items.length; i < len; i++ ) {
9833 if ( this.items[i].isSelected() ) {
9834 return this.items[i];
9837 return null;
9841 * Get highlighted item.
9843 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
9845 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
9846 var i, len;
9848 for ( i = 0, len = this.items.length; i < len; i++ ) {
9849 if ( this.items[i].isHighlighted() ) {
9850 return this.items[i];
9853 return null;
9857 * Get an existing item with equivilant data.
9859 * @param {Object} data Item data to search for
9860 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
9862 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
9863 var hash = OO.getHash( data );
9865 if ( hash in this.hashes ) {
9866 return this.hashes[hash];
9869 return null;
9873 * Toggle pressed state.
9875 * @param {boolean} pressed An option is being pressed
9877 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
9878 if ( pressed === undefined ) {
9879 pressed = !this.pressed;
9881 if ( pressed !== this.pressed ) {
9882 this.$element
9883 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
9884 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
9885 this.pressed = pressed;
9890 * Highlight an item.
9892 * Highlighting is mutually exclusive.
9894 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
9895 * @fires highlight
9896 * @chainable
9898 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
9899 var i, len, highlighted,
9900 changed = false;
9902 for ( i = 0, len = this.items.length; i < len; i++ ) {
9903 highlighted = this.items[i] === item;
9904 if ( this.items[i].isHighlighted() !== highlighted ) {
9905 this.items[i].setHighlighted( highlighted );
9906 changed = true;
9909 if ( changed ) {
9910 this.emit( 'highlight', item );
9913 return this;
9917 * Select an item.
9919 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
9920 * @fires select
9921 * @chainable
9923 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
9924 var i, len, selected,
9925 changed = false;
9927 for ( i = 0, len = this.items.length; i < len; i++ ) {
9928 selected = this.items[i] === item;
9929 if ( this.items[i].isSelected() !== selected ) {
9930 this.items[i].setSelected( selected );
9931 changed = true;
9934 if ( changed ) {
9935 this.emit( 'select', item );
9938 return this;
9942 * Press an item.
9944 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
9945 * @fires press
9946 * @chainable
9948 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
9949 var i, len, pressed,
9950 changed = false;
9952 for ( i = 0, len = this.items.length; i < len; i++ ) {
9953 pressed = this.items[i] === item;
9954 if ( this.items[i].isPressed() !== pressed ) {
9955 this.items[i].setPressed( pressed );
9956 changed = true;
9959 if ( changed ) {
9960 this.emit( 'press', item );
9963 return this;
9967 * Choose an item.
9969 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
9970 * an item is selected using the keyboard or mouse.
9972 * @param {OO.ui.OptionWidget} item Item to choose
9973 * @fires choose
9974 * @chainable
9976 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
9977 this.selectItem( item );
9978 this.emit( 'choose', item );
9980 return this;
9984 * Get an item relative to another one.
9986 * @param {OO.ui.OptionWidget} item Item to start at
9987 * @param {number} direction Direction to move in
9988 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
9990 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
9991 var inc = direction > 0 ? 1 : -1,
9992 len = this.items.length,
9993 index = item instanceof OO.ui.OptionWidget ?
9994 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
9995 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
9996 i = inc > 0 ?
9997 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
9998 Math.max( index, -1 ) :
9999 // Default to n-1 instead of -1, if nothing is selected let's start at the end
10000 Math.min( index, len );
10002 while ( true ) {
10003 i = ( i + inc + len ) % len;
10004 item = this.items[i];
10005 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
10006 return item;
10008 // Stop iterating when we've looped all the way around
10009 if ( i === stopAt ) {
10010 break;
10013 return null;
10017 * Get the next selectable item.
10019 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
10021 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
10022 var i, len, item;
10024 for ( i = 0, len = this.items.length; i < len; i++ ) {
10025 item = this.items[i];
10026 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
10027 return item;
10031 return null;
10035 * Add items.
10037 * When items are added with the same values as existing items, the existing items will be
10038 * automatically removed before the new items are added.
10040 * @param {OO.ui.OptionWidget[]} items Items to add
10041 * @param {number} [index] Index to insert items after
10042 * @fires add
10043 * @chainable
10045 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
10046 var i, len, item, hash,
10047 remove = [];
10049 for ( i = 0, len = items.length; i < len; i++ ) {
10050 item = items[i];
10051 hash = OO.getHash( item.getData() );
10052 if ( hash in this.hashes ) {
10053 // Remove item with same value
10054 remove.push( this.hashes[hash] );
10056 this.hashes[hash] = item;
10058 if ( remove.length ) {
10059 this.removeItems( remove );
10062 // Mixin method
10063 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
10065 // Always provide an index, even if it was omitted
10066 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
10068 return this;
10072 * Remove items.
10074 * Items will be detached, not removed, so they can be used later.
10076 * @param {OO.ui.OptionWidget[]} items Items to remove
10077 * @fires remove
10078 * @chainable
10080 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
10081 var i, len, item, hash;
10083 for ( i = 0, len = items.length; i < len; i++ ) {
10084 item = items[i];
10085 hash = OO.getHash( item.getData() );
10086 if ( hash in this.hashes ) {
10087 // Remove existing item
10088 delete this.hashes[hash];
10090 if ( item.isSelected() ) {
10091 this.selectItem( null );
10095 // Mixin method
10096 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
10098 this.emit( 'remove', items );
10100 return this;
10104 * Clear all items.
10106 * Items will be detached, not removed, so they can be used later.
10108 * @fires remove
10109 * @chainable
10111 OO.ui.SelectWidget.prototype.clearItems = function () {
10112 var items = this.items.slice();
10114 // Clear all items
10115 this.hashes = {};
10116 // Mixin method
10117 OO.ui.GroupWidget.prototype.clearItems.call( this );
10118 this.selectItem( null );
10120 this.emit( 'remove', items );
10122 return this;
10126 * Select widget containing button options.
10128 * Use together with OO.ui.ButtonOptionWidget.
10130 * @class
10131 * @extends OO.ui.SelectWidget
10133 * @constructor
10134 * @param {Object} [config] Configuration options
10136 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
10137 // Parent constructor
10138 OO.ui.ButtonSelectWidget.super.call( this, config );
10140 // Initialization
10141 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
10144 /* Setup */
10146 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
10149 * Overlaid menu of options.
10151 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
10152 * the menu.
10154 * Use together with OO.ui.MenuItemWidget.
10156 * @class
10157 * @extends OO.ui.SelectWidget
10158 * @mixins OO.ui.ClippableElement
10160 * @constructor
10161 * @param {Object} [config] Configuration options
10162 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
10163 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
10164 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
10166 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
10167 // Config intialization
10168 config = config || {};
10170 // Parent constructor
10171 OO.ui.MenuWidget.super.call( this, config );
10173 // Mixin constructors
10174 OO.ui.ClippableElement.call( this, this.$group, config );
10176 // Properties
10177 this.flashing = false;
10178 this.visible = false;
10179 this.newItems = null;
10180 this.autoHide = config.autoHide === undefined || !!config.autoHide;
10181 this.$input = config.input ? config.input.$input : null;
10182 this.$widget = config.widget ? config.widget.$element : null;
10183 this.$previousFocus = null;
10184 this.isolated = !config.input;
10185 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
10186 this.onDocumentMouseDownHandler = OO.ui.bind( this.onDocumentMouseDown, this );
10188 // Initialization
10189 this.$element
10190 .hide()
10191 .attr( 'role', 'menu' )
10192 .addClass( 'oo-ui-menuWidget' );
10195 /* Setup */
10197 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
10198 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
10200 /* Methods */
10203 * Handles document mouse down events.
10205 * @param {jQuery.Event} e Key down event
10207 OO.ui.MenuWidget.prototype.onDocumentMouseDown = function ( e ) {
10208 if ( !$.contains( this.$element[0], e.target ) && ( !this.$widget || !$.contains( this.$widget[0], e.target ) ) ) {
10209 this.toggle( false );
10214 * Handles key down events.
10216 * @param {jQuery.Event} e Key down event
10218 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
10219 var nextItem,
10220 handled = false,
10221 highlightItem = this.getHighlightedItem();
10223 if ( !this.isDisabled() && this.isVisible() ) {
10224 if ( !highlightItem ) {
10225 highlightItem = this.getSelectedItem();
10227 switch ( e.keyCode ) {
10228 case OO.ui.Keys.ENTER:
10229 this.chooseItem( highlightItem );
10230 handled = true;
10231 break;
10232 case OO.ui.Keys.UP:
10233 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
10234 handled = true;
10235 break;
10236 case OO.ui.Keys.DOWN:
10237 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
10238 handled = true;
10239 break;
10240 case OO.ui.Keys.ESCAPE:
10241 if ( highlightItem ) {
10242 highlightItem.setHighlighted( false );
10244 this.toggle( false );
10245 handled = true;
10246 break;
10249 if ( nextItem ) {
10250 this.highlightItem( nextItem );
10251 nextItem.scrollElementIntoView();
10254 if ( handled ) {
10255 e.preventDefault();
10256 e.stopPropagation();
10257 return false;
10263 * Bind key down listener.
10265 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
10266 if ( this.$input ) {
10267 this.$input.on( 'keydown', this.onKeyDownHandler );
10268 } else {
10269 // Capture menu navigation keys
10270 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
10275 * Unbind key down listener.
10277 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
10278 if ( this.$input ) {
10279 this.$input.off( 'keydown' );
10280 } else {
10281 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
10286 * Choose an item.
10288 * This will close the menu when done, unlike selectItem which only changes selection.
10290 * @param {OO.ui.OptionWidget} item Item to choose
10291 * @chainable
10293 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
10294 var widget = this;
10296 // Parent method
10297 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
10299 if ( item && !this.flashing ) {
10300 this.flashing = true;
10301 item.flash().done( function () {
10302 widget.toggle( false );
10303 widget.flashing = false;
10304 } );
10305 } else {
10306 this.toggle( false );
10309 return this;
10313 * Add items.
10315 * Adding an existing item (by value) will move it.
10317 * @param {OO.ui.MenuItemWidget[]} items Items to add
10318 * @param {number} [index] Index to insert items after
10319 * @chainable
10321 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
10322 var i, len, item;
10324 // Parent method
10325 OO.ui.MenuWidget.super.prototype.addItems.call( this, items, index );
10327 // Auto-initialize
10328 if ( !this.newItems ) {
10329 this.newItems = [];
10332 for ( i = 0, len = items.length; i < len; i++ ) {
10333 item = items[i];
10334 if ( this.isVisible() ) {
10335 // Defer fitting label until
10336 item.fitLabel();
10337 } else {
10338 this.newItems.push( item );
10342 return this;
10346 * @inheritdoc
10348 OO.ui.MenuWidget.prototype.toggle = function ( visible ) {
10349 visible = !!visible && !!this.items.length;
10351 var i, len,
10352 change = visible !== this.isVisible();
10354 // Parent method
10355 OO.ui.MenuWidget.super.prototype.toggle.call( this, visible );
10357 if ( change ) {
10358 if ( visible ) {
10359 this.bindKeyDownListener();
10361 // Change focus to enable keyboard navigation
10362 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
10363 this.$previousFocus = this.$( ':focus' );
10364 this.$input[0].focus();
10366 if ( this.newItems && this.newItems.length ) {
10367 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
10368 this.newItems[i].fitLabel();
10370 this.newItems = null;
10372 this.setClipping( true );
10374 // Auto-hide
10375 if ( this.autoHide ) {
10376 this.getElementDocument().addEventListener(
10377 'mousedown', this.onDocumentMouseDownHandler, true
10380 } else {
10381 this.unbindKeyDownListener();
10382 if ( this.isolated && this.$previousFocus ) {
10383 this.$previousFocus[0].focus();
10384 this.$previousFocus = null;
10386 this.getElementDocument().removeEventListener(
10387 'mousedown', this.onDocumentMouseDownHandler, true
10389 this.setClipping( false );
10393 return this;
10397 * Menu for a text input widget.
10399 * This menu is specially designed to be positioned beneeth the text input widget. Even if the input
10400 * is in a different frame, the menu's position is automatically calulated and maintained when the
10401 * menu is toggled or the window is resized.
10403 * @class
10404 * @extends OO.ui.MenuWidget
10406 * @constructor
10407 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
10408 * @param {Object} [config] Configuration options
10409 * @cfg {jQuery} [$container=input.$element] Element to render menu under
10411 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
10412 // Parent constructor
10413 OO.ui.TextInputMenuWidget.super.call( this, config );
10415 // Properties
10416 this.input = input;
10417 this.$container = config.$container || this.input.$element;
10418 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
10420 // Initialization
10421 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
10424 /* Setup */
10426 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
10428 /* Methods */
10431 * Handle window resize event.
10433 * @param {jQuery.Event} e Window resize event
10435 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
10436 this.position();
10440 * @inheritdoc
10442 OO.ui.TextInputMenuWidget.prototype.toggle = function ( visible ) {
10443 visible = !!visible;
10445 var change = visible !== this.isVisible();
10447 // Parent method
10448 OO.ui.TextInputMenuWidget.super.prototype.toggle.call( this, visible );
10450 if ( change ) {
10451 if ( this.isVisible() ) {
10452 this.position();
10453 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
10454 } else {
10455 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
10458 return this;
10462 * Position the menu.
10464 * @chainable
10466 OO.ui.TextInputMenuWidget.prototype.position = function () {
10467 var frameOffset,
10468 $container = this.$container,
10469 dimensions = $container.offset();
10471 // Position under input
10472 dimensions.top += $container.height();
10474 // Compensate for frame position if in a differnt frame
10475 if ( this.input.$.frame && this.input.$.context !== this.$element[0].ownerDocument ) {
10476 frameOffset = OO.ui.Element.getRelativePosition(
10477 this.input.$.frame.$element, this.$element.offsetParent()
10479 dimensions.left += frameOffset.left;
10480 dimensions.top += frameOffset.top;
10481 } else {
10482 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
10483 if ( this.$element.css( 'direction' ) === 'rtl' ) {
10484 dimensions.right = this.$element.parent().position().left -
10485 $container.width() - dimensions.left;
10486 // Erase the value for 'left':
10487 delete dimensions.left;
10490 this.$element.css( dimensions );
10491 this.setIdealSize( $container.width() );
10493 return this;
10497 * Structured list of items.
10499 * Use with OO.ui.OutlineItemWidget.
10501 * @class
10502 * @extends OO.ui.SelectWidget
10504 * @constructor
10505 * @param {Object} [config] Configuration options
10507 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
10508 // Config intialization
10509 config = config || {};
10511 // Parent constructor
10512 OO.ui.OutlineWidget.super.call( this, config );
10514 // Initialization
10515 this.$element.addClass( 'oo-ui-outlineWidget' );
10518 /* Setup */
10520 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
10523 * Switch that slides on and off.
10525 * @class
10526 * @extends OO.ui.Widget
10527 * @mixins OO.ui.ToggleWidget
10529 * @constructor
10530 * @param {Object} [config] Configuration options
10531 * @cfg {boolean} [value=false] Initial value
10533 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
10534 // Parent constructor
10535 OO.ui.ToggleSwitchWidget.super.call( this, config );
10537 // Mixin constructors
10538 OO.ui.ToggleWidget.call( this, config );
10540 // Properties
10541 this.dragging = false;
10542 this.dragStart = null;
10543 this.sliding = false;
10544 this.$glow = this.$( '<span>' );
10545 this.$grip = this.$( '<span>' );
10547 // Events
10548 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
10550 // Initialization
10551 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
10552 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
10553 this.$element
10554 .addClass( 'oo-ui-toggleSwitchWidget' )
10555 .append( this.$glow, this.$grip );
10558 /* Setup */
10560 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
10561 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
10563 /* Methods */
10566 * Handle mouse down events.
10568 * @param {jQuery.Event} e Mouse down event
10570 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
10571 if ( !this.isDisabled() && e.which === 1 ) {
10572 this.setValue( !this.value );
10576 }( OO ) );