Merge "Make update.php file executable"
[mediawiki.git] / resources / lib / oojs-ui / oojs-ui.js
blob495056f15273835c42c5bdbae55e0480eaefb557
1 /*!
2 * OOjs UI v0.1.0-pre (7b3672591f)
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: Fri May 09 2014 13:27:04 GMT+0200 (CEST)
11 ( function ( OO ) {
13 'use strict';
14 /**
15 * Namespace for all classes, static methods and static properties.
17 * @class
18 * @singleton
20 OO.ui = {};
22 OO.ui.bind = $.proxy;
24 /**
25 * @property {Object}
27 OO.ui.Keys = {
28 'UNDEFINED': 0,
29 'BACKSPACE': 8,
30 'DELETE': 46,
31 'LEFT': 37,
32 'RIGHT': 39,
33 'UP': 38,
34 'DOWN': 40,
35 'ENTER': 13,
36 'END': 35,
37 'HOME': 36,
38 'TAB': 9,
39 'PAGEUP': 33,
40 'PAGEDOWN': 34,
41 'ESCAPE': 27,
42 'SHIFT': 16,
43 'SPACE': 32
46 /**
47 * Get the user's language and any fallback languages.
49 * These language codes are used to localize user interface elements in the user's language.
51 * In environments that provide a localization system, this function should be overridden to
52 * return the user's language(s). The default implementation returns English (en) only.
54 * @return {string[]} Language codes, in descending order of priority
56 OO.ui.getUserLanguages = function () {
57 return [ 'en' ];
60 /**
61 * Get a value in an object keyed by language code.
63 * @param {Object.<string,Mixed>} obj Object keyed by language code
64 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
65 * @param {string} [fallback] Fallback code, used if no matching language can be found
66 * @return {Mixed} Local value
68 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
69 var i, len, langs;
71 // Requested language
72 if ( obj[lang] ) {
73 return obj[lang];
75 // Known user language
76 langs = OO.ui.getUserLanguages();
77 for ( i = 0, len = langs.length; i < len; i++ ) {
78 lang = langs[i];
79 if ( obj[lang] ) {
80 return obj[lang];
83 // Fallback language
84 if ( obj[fallback] ) {
85 return obj[fallback];
87 // First existing language
88 for ( lang in obj ) {
89 return obj[lang];
92 return undefined;
95 ( 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 // Label text for button to exit from dialog
107 'ooui-dialog-action-close': 'Close',
108 // Tool tip for a button that moves items in a list down one place
109 'ooui-outline-control-move-down': 'Move item down',
110 // Tool tip for a button that moves items in a list up one place
111 'ooui-outline-control-move-up': 'Move item up',
112 // Tool tip for a button that removes items from a list
113 'ooui-outline-control-remove': 'Remove item',
114 // Label for the toolbar group that contains a list of all other available tools
115 'ooui-toolbar-more': 'More'
119 * Get a localized message.
121 * In environments that provide a localization system, this function should be overridden to
122 * return the message translated in the user's language. The default implementation always returns
123 * English messages.
125 * After the message key, message parameters may optionally be passed. In the default implementation,
126 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
127 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
128 * they support unnamed, ordered message parameters.
130 * @abstract
131 * @param {string} key Message key
132 * @param {Mixed...} [params] Message parameters
133 * @return {string} Translated message with parameters substituted
135 OO.ui.msg = function ( key ) {
136 var message = messages[key], params = Array.prototype.slice.call( arguments, 1 );
137 if ( typeof message === 'string' ) {
138 // Perform $1 substitution
139 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
140 var i = parseInt( n, 10 );
141 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
142 } );
143 } else {
144 // Return placeholder if message not found
145 message = '[' + key + ']';
147 return message;
150 /** */
151 OO.ui.deferMsg = function ( key ) {
152 return function () {
153 return OO.ui.msg( key );
157 /** */
158 OO.ui.resolveMsg = function ( msg ) {
159 if ( $.isFunction( msg ) ) {
160 return msg();
162 return msg;
165 } )();
167 * DOM element abstraction.
169 * @abstract
170 * @class
172 * @constructor
173 * @param {Object} [config] Configuration options
174 * @cfg {Function} [$] jQuery for the frame the widget is in
175 * @cfg {string[]} [classes] CSS class names
176 * @cfg {string} [text] Text to insert
177 * @cfg {jQuery} [$content] Content elements to append (after text)
179 OO.ui.Element = function OoUiElement( config ) {
180 // Configuration initialization
181 config = config || {};
183 // Properties
184 this.$ = config.$ || OO.ui.Element.getJQuery( document );
185 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
186 this.elementGroup = null;
188 // Initialization
189 if ( $.isArray( config.classes ) ) {
190 this.$element.addClass( config.classes.join( ' ' ) );
192 if ( config.text ) {
193 this.$element.text( config.text );
195 if ( config.$content ) {
196 this.$element.append( config.$content );
200 /* Setup */
202 OO.initClass( OO.ui.Element );
204 /* Static Properties */
207 * HTML tag name.
209 * This may be ignored if getTagName is overridden.
211 * @static
212 * @inheritable
213 * @property {string}
215 OO.ui.Element.static.tagName = 'div';
217 /* Static Methods */
220 * Get a jQuery function within a specific document.
222 * @static
223 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
224 * @param {OO.ui.Frame} [frame] Frame of the document context
225 * @return {Function} Bound jQuery function
227 OO.ui.Element.getJQuery = function ( context, frame ) {
228 function wrapper( selector ) {
229 return $( selector, wrapper.context );
232 wrapper.context = this.getDocument( context );
234 if ( frame ) {
235 wrapper.frame = frame;
238 return wrapper;
242 * Get the document of an element.
244 * @static
245 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
246 * @return {HTMLDocument|null} Document object
248 OO.ui.Element.getDocument = function ( obj ) {
249 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
250 return ( obj[0] && obj[0].ownerDocument ) ||
251 // Empty jQuery selections might have a context
252 obj.context ||
253 // HTMLElement
254 obj.ownerDocument ||
255 // Window
256 obj.document ||
257 // HTMLDocument
258 ( obj.nodeType === 9 && obj ) ||
259 null;
263 * Get the window of an element or document.
265 * @static
266 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
267 * @return {Window} Window object
269 OO.ui.Element.getWindow = function ( obj ) {
270 var doc = this.getDocument( obj );
271 return doc.parentWindow || doc.defaultView;
275 * Get the direction of an element or document.
277 * @static
278 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
279 * @return {string} Text direction, either `ltr` or `rtl`
281 OO.ui.Element.getDir = function ( obj ) {
282 var isDoc, isWin;
284 if ( obj instanceof jQuery ) {
285 obj = obj[0];
287 isDoc = obj.nodeType === 9;
288 isWin = obj.document !== undefined;
289 if ( isDoc || isWin ) {
290 if ( isWin ) {
291 obj = obj.document;
293 obj = obj.body;
295 return $( obj ).css( 'direction' );
299 * Get the offset between two frames.
301 * TODO: Make this function not use recursion.
303 * @static
304 * @param {Window} from Window of the child frame
305 * @param {Window} [to=window] Window of the parent frame
306 * @param {Object} [offset] Offset to start with, used internally
307 * @return {Object} Offset object, containing left and top properties
309 OO.ui.Element.getFrameOffset = function ( from, to, offset ) {
310 var i, len, frames, frame, rect;
312 if ( !to ) {
313 to = window;
315 if ( !offset ) {
316 offset = { 'top': 0, 'left': 0 };
318 if ( from.parent === from ) {
319 return offset;
322 // Get iframe element
323 frames = from.parent.document.getElementsByTagName( 'iframe' );
324 for ( i = 0, len = frames.length; i < len; i++ ) {
325 if ( frames[i].contentWindow === from ) {
326 frame = frames[i];
327 break;
331 // Recursively accumulate offset values
332 if ( frame ) {
333 rect = frame.getBoundingClientRect();
334 offset.left += rect.left;
335 offset.top += rect.top;
336 if ( from !== to ) {
337 this.getFrameOffset( from.parent, offset );
340 return offset;
344 * Get the offset between two elements.
346 * @static
347 * @param {jQuery} $from
348 * @param {jQuery} $to
349 * @return {Object} Translated position coordinates, containing top and left properties
351 OO.ui.Element.getRelativePosition = function ( $from, $to ) {
352 var from = $from.offset(),
353 to = $to.offset();
354 return { 'top': Math.round( from.top - to.top ), 'left': Math.round( from.left - to.left ) };
358 * Get element border sizes.
360 * @static
361 * @param {HTMLElement} el Element to measure
362 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
364 OO.ui.Element.getBorders = function ( el ) {
365 var doc = el.ownerDocument,
366 win = doc.parentWindow || doc.defaultView,
367 style = win && win.getComputedStyle ?
368 win.getComputedStyle( el, null ) :
369 el.currentStyle,
370 $el = $( el ),
371 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
372 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
373 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
374 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
376 return {
377 'top': Math.round( top ),
378 'left': Math.round( left ),
379 'bottom': Math.round( bottom ),
380 'right': Math.round( right )
385 * Get dimensions of an element or window.
387 * @static
388 * @param {HTMLElement|Window} el Element to measure
389 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
391 OO.ui.Element.getDimensions = function ( el ) {
392 var $el, $win,
393 doc = el.ownerDocument || el.document,
394 win = doc.parentWindow || doc.defaultView;
396 if ( win === el || el === doc.documentElement ) {
397 $win = $( win );
398 return {
399 'borders': { 'top': 0, 'left': 0, 'bottom': 0, 'right': 0 },
400 'scroll': {
401 'top': $win.scrollTop(),
402 'left': $win.scrollLeft()
404 'scrollbar': { 'right': 0, 'bottom': 0 },
405 'rect': {
406 'top': 0,
407 'left': 0,
408 'bottom': $win.innerHeight(),
409 'right': $win.innerWidth()
412 } else {
413 $el = $( el );
414 return {
415 'borders': this.getBorders( el ),
416 'scroll': {
417 'top': $el.scrollTop(),
418 'left': $el.scrollLeft()
420 'scrollbar': {
421 'right': $el.innerWidth() - el.clientWidth,
422 'bottom': $el.innerHeight() - el.clientHeight
424 'rect': el.getBoundingClientRect()
430 * Get closest scrollable container.
432 * Traverses up until either a scrollable element or the root is reached, in which case the window
433 * will be returned.
435 * @static
436 * @param {HTMLElement} el Element to find scrollable container for
437 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
438 * @return {HTMLElement|Window} Closest scrollable container
440 OO.ui.Element.getClosestScrollableContainer = function ( el, dimension ) {
441 var i, val,
442 props = [ 'overflow' ],
443 $parent = $( el ).parent();
445 if ( dimension === 'x' || dimension === 'y' ) {
446 props.push( 'overflow-' + dimension );
449 while ( $parent.length ) {
450 if ( $parent[0] === el.ownerDocument.body ) {
451 return $parent[0];
453 i = props.length;
454 while ( i-- ) {
455 val = $parent.css( props[i] );
456 if ( val === 'auto' || val === 'scroll' ) {
457 return $parent[0];
460 $parent = $parent.parent();
462 return this.getDocument( el ).body;
466 * Scroll element into view.
468 * @static
469 * @param {HTMLElement} el Element to scroll into view
470 * @param {Object} [config={}] Configuration config
471 * @param {string} [config.duration] jQuery animation duration value
472 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
473 * to scroll in both directions
474 * @param {Function} [config.complete] Function to call when scrolling completes
476 OO.ui.Element.scrollIntoView = function ( el, config ) {
477 // Configuration initialization
478 config = config || {};
480 var anim = {},
481 callback = typeof config.complete === 'function' && config.complete,
482 sc = this.getClosestScrollableContainer( el, config.direction ),
483 $sc = $( sc ),
484 eld = this.getDimensions( el ),
485 scd = this.getDimensions( sc ),
486 rel = {
487 'top': eld.rect.top - ( scd.rect.top + scd.borders.top ),
488 'bottom': scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
489 'left': eld.rect.left - ( scd.rect.left + scd.borders.left ),
490 'right': scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
493 if ( !config.direction || config.direction === 'y' ) {
494 if ( rel.top < 0 ) {
495 anim.scrollTop = scd.scroll.top + rel.top;
496 } else if ( rel.top > 0 && rel.bottom < 0 ) {
497 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
500 if ( !config.direction || config.direction === 'x' ) {
501 if ( rel.left < 0 ) {
502 anim.scrollLeft = scd.scroll.left + rel.left;
503 } else if ( rel.left > 0 && rel.right < 0 ) {
504 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
507 if ( !$.isEmptyObject( anim ) ) {
508 $sc.stop( true ).animate( anim, config.duration || 'fast' );
509 if ( callback ) {
510 $sc.queue( function ( next ) {
511 callback();
512 next();
513 } );
515 } else {
516 if ( callback ) {
517 callback();
522 /* Methods */
525 * Get the HTML tag name.
527 * Override this method to base the result on instance information.
529 * @return {string} HTML tag name
531 OO.ui.Element.prototype.getTagName = function () {
532 return this.constructor.static.tagName;
536 * Check if the element is attached to the DOM
537 * @return {boolean} The element is attached to the DOM
539 OO.ui.Element.prototype.isElementAttached = function () {
540 return $.contains( this.getElementDocument(), this.$element[0] );
544 * Get the DOM document.
546 * @return {HTMLDocument} Document object
548 OO.ui.Element.prototype.getElementDocument = function () {
549 return OO.ui.Element.getDocument( this.$element );
553 * Get the DOM window.
555 * @return {Window} Window object
557 OO.ui.Element.prototype.getElementWindow = function () {
558 return OO.ui.Element.getWindow( this.$element );
562 * Get closest scrollable container.
564 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
565 return OO.ui.Element.getClosestScrollableContainer( this.$element[0] );
569 * Get group element is in.
571 * @return {OO.ui.GroupElement|null} Group element, null if none
573 OO.ui.Element.prototype.getElementGroup = function () {
574 return this.elementGroup;
578 * Set group element is in.
580 * @param {OO.ui.GroupElement|null} group Group element, null if none
581 * @chainable
583 OO.ui.Element.prototype.setElementGroup = function ( group ) {
584 this.elementGroup = group;
585 return this;
589 * Scroll element into view.
591 * @param {Object} [config={}]
593 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
594 return OO.ui.Element.scrollIntoView( this.$element[0], config );
598 * Bind a handler for an event on this.$element
600 * @param {string} event
601 * @param {Function} callback
603 OO.ui.Element.prototype.onDOMEvent = function ( event, callback ) {
604 OO.ui.Element.onDOMEvent( this.$element, event, callback );
608 * Unbind a handler bound with #offDOMEvent
610 * @param {string} event
611 * @param {Function} callback
613 OO.ui.Element.prototype.offDOMEvent = function ( event, callback ) {
614 OO.ui.Element.offDOMEvent( this.$element, event, callback );
617 ( function () {
618 // Static
620 // jQuery 1.8.3 has a bug with handling focusin/focusout events inside iframes.
621 // Firefox doesn't support focusin/focusout at all, so we listen for 'focus'/'blur' on the
622 // document, and simulate a 'focusin'/'focusout' event on the target element and make
623 // it bubble from there.
625 // - http://jsfiddle.net/sw3hr/
626 // - http://bugs.jquery.com/ticket/14180
627 // - https://github.com/jquery/jquery/commit/1cecf64e5aa4153
628 function specialEvent( simulatedName, realName ) {
629 function handler( e ) {
630 jQuery.event.simulate(
631 simulatedName,
632 e.target,
633 jQuery.event.fix( e ),
634 /* bubble = */ true
638 return {
639 setup: function () {
640 var doc = this.ownerDocument || this,
641 attaches = $.data( doc, 'ooui-' + simulatedName + '-attaches' );
642 if ( !attaches ) {
643 doc.addEventListener( realName, handler, true );
645 $.data( doc, 'ooui-' + simulatedName + '-attaches', ( attaches || 0 ) + 1 );
647 teardown: function () {
648 var doc = this.ownerDocument || this,
649 attaches = $.data( doc, 'ooui-' + simulatedName + '-attaches' ) - 1;
650 if ( !attaches ) {
651 doc.removeEventListener( realName, handler, true );
652 $.removeData( doc, 'ooui-' + simulatedName + '-attaches' );
653 } else {
654 $.data( doc, 'ooui-' + simulatedName + '-attaches', attaches );
660 var hasOwn = Object.prototype.hasOwnProperty,
661 specialEvents = {
662 focusin: specialEvent( 'focusin', 'focus' ),
663 focusout: specialEvent( 'focusout', 'blur' )
667 * Bind a handler for an event on a DOM element.
669 * Uses jQuery internally for everything except for events which are
670 * known to have issues in the browser or in jQuery. This method
671 * should become obsolete eventually.
673 * @static
674 * @param {HTMLElement|jQuery} el DOM element
675 * @param {string} event Event to bind
676 * @param {Function} callback Callback to call when the event fires
678 OO.ui.Element.onDOMEvent = function ( el, event, callback ) {
679 var orig;
681 if ( hasOwn.call( specialEvents, event ) ) {
682 // Replace jQuery's override with our own
683 orig = $.event.special[event];
684 $.event.special[event] = specialEvents[event];
686 $( el ).on( event, callback );
688 // Restore
689 $.event.special[event] = orig;
690 } else {
691 $( el ).on( event, callback );
696 * Unbind a handler bound with #static-method-onDOMEvent.
698 * @static
699 * @param {HTMLElement|jQuery} el DOM element
700 * @param {string} event Event to unbind
701 * @param {Function} [callback] Callback to unbind
703 OO.ui.Element.offDOMEvent = function ( el, event, callback ) {
704 var orig;
705 if ( hasOwn.call( specialEvents, event ) ) {
706 // Replace jQuery's override with our own
707 orig = $.event.special[event];
708 $.event.special[event] = specialEvents[event];
710 $( el ).off( event, callback );
712 // Restore
713 $.event.special[event] = orig;
714 } else {
715 $( el ).off( event, callback );
718 }() );
720 * Embedded iframe with the same styles as its parent.
722 * @class
723 * @extends OO.ui.Element
724 * @mixins OO.EventEmitter
726 * @constructor
727 * @param {Object} [config] Configuration options
729 OO.ui.Frame = function OoUiFrame( config ) {
730 // Parent constructor
731 OO.ui.Frame.super.call( this, config );
733 // Mixin constructors
734 OO.EventEmitter.call( this );
736 // Properties
737 this.loading = false;
738 this.loaded = false;
739 this.config = config;
741 // Initialize
742 this.$element
743 .addClass( 'oo-ui-frame' )
744 .attr( { 'frameborder': 0, 'scrolling': 'no' } );
748 /* Setup */
750 OO.inheritClass( OO.ui.Frame, OO.ui.Element );
751 OO.mixinClass( OO.ui.Frame, OO.EventEmitter );
753 /* Static Properties */
756 * @static
757 * @inheritdoc
759 OO.ui.Frame.static.tagName = 'iframe';
761 /* Events */
764 * @event load
767 /* Static Methods */
770 * Transplant the CSS styles from as parent document to a frame's document.
772 * This loops over the style sheets in the parent document, and copies their nodes to the
773 * frame's document. It then polls the document to see when all styles have loaded, and once they
774 * have, invokes the callback.
776 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
777 * and invoke the callback anyway. This protects against cases like a display: none; iframe in
778 * Firefox, where the styles won't load until the iframe becomes visible.
780 * For details of how we arrived at the strategy used in this function, see #load.
782 * @static
783 * @inheritable
784 * @param {HTMLDocument} parentDoc Document to transplant styles from
785 * @param {HTMLDocument} frameDoc Document to transplant styles to
786 * @param {Function} [callback] Callback to execute once styles have loaded
787 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
789 OO.ui.Frame.static.transplantStyles = function ( parentDoc, frameDoc, callback, timeout ) {
790 var i, numSheets, styleNode, newNode, timeoutID, pollNodeId, $pendingPollNodes,
791 $pollNodes = $( [] ),
792 // Fake font-family value
793 fontFamily = 'oo-ui-frame-transplantStyles-loaded';
795 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
796 styleNode = parentDoc.styleSheets[i].ownerNode;
797 if ( callback && styleNode.nodeName.toLowerCase() === 'link' ) {
798 // External stylesheet
799 // Create a node with a unique ID that we're going to monitor to see when the CSS
800 // has loaded
801 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + i;
802 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
803 .attr( 'id', pollNodeId )
804 .appendTo( frameDoc.body )
807 // Add <style>@import url(...); #pollNodeId { font-family: ... }</style>
808 // The font-family rule will only take effect once the @import finishes
809 newNode = frameDoc.createElement( 'style' );
810 newNode.textContent = '@import url(' + styleNode.href + ');\n' +
811 '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
812 } else {
813 // Not an external stylesheet, or no polling required; just copy the node over
814 newNode = frameDoc.importNode( styleNode, true );
816 frameDoc.head.appendChild( newNode );
819 if ( callback ) {
820 // Poll every 100ms until all external stylesheets have loaded
821 $pendingPollNodes = $pollNodes;
822 timeoutID = setTimeout( function pollExternalStylesheets() {
823 while (
824 $pendingPollNodes.length > 0 &&
825 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
827 $pendingPollNodes = $pendingPollNodes.slice( 1 );
830 if ( $pendingPollNodes.length === 0 ) {
831 // We're done!
832 if ( timeoutID !== null ) {
833 timeoutID = null;
834 $pollNodes.remove();
835 callback();
837 } else {
838 timeoutID = setTimeout( pollExternalStylesheets, 100 );
840 }, 100 );
841 // ...but give up after a while
842 if ( timeout !== 0 ) {
843 setTimeout( function () {
844 if ( timeoutID ) {
845 clearTimeout( timeoutID );
846 timeoutID = null;
847 $pollNodes.remove();
848 callback();
850 }, timeout || 5000 );
855 /* Methods */
858 * Load the frame contents.
860 * Once the iframe's stylesheets are loaded, the `initialize` event will be emitted.
862 * Sounds simple right? Read on...
864 * When you create a dynamic iframe using open/write/close, the window.load event for the
865 * iframe is triggered when you call close, and there's no further load event to indicate that
866 * everything is actually loaded.
868 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
869 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
870 * are added to document.styleSheets immediately, and the only way you can determine whether they've
871 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
872 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
874 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>` tags.
875 * Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets until
876 * the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the `@import`
877 * has finished. And because the contents of the `<style>` tag are from the same origin, accessing
878 * .cssRules is allowed.
880 * However, now that we control the styles we're injecting, we might as well do away with
881 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
882 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
883 * and wait for its font-family to change to someValue. Because `@import` is blocking, the font-family
884 * rule is not applied until after the `@import` finishes.
886 * All this stylesheet injection and polling magic is in #transplantStyles.
888 * @private
889 * @fires load
891 OO.ui.Frame.prototype.load = function () {
892 var win = this.$element.prop( 'contentWindow' ),
893 doc = win.document,
894 frame = this;
896 this.loading = true;
898 // Figure out directionality:
899 this.dir = this.$element.closest( '[dir]' ).prop( 'dir' ) || 'ltr';
901 // Initialize contents
902 doc.open();
903 doc.write(
904 '<!doctype html>' +
905 '<html>' +
906 '<body class="oo-ui-frame-body oo-ui-' + this.dir + '" style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
907 '<div class="oo-ui-frame-content"></div>' +
908 '</body>' +
909 '</html>'
911 doc.close();
913 // Properties
914 this.$ = OO.ui.Element.getJQuery( doc, this );
915 this.$content = this.$( '.oo-ui-frame-content' ).attr( 'tabIndex', 0 );
916 this.$document = this.$( doc );
918 this.constructor.static.transplantStyles(
919 this.getElementDocument(),
920 this.$document[0],
921 function () {
922 frame.loading = false;
923 frame.loaded = true;
924 frame.emit( 'load' );
930 * Run a callback as soon as the frame has been loaded.
933 * This will start loading if it hasn't already, and runs
934 * immediately if the frame is already loaded.
936 * Don't call this until the element is attached.
938 * @param {Function} callback
940 OO.ui.Frame.prototype.run = function ( callback ) {
941 if ( this.loaded ) {
942 callback();
943 } else {
944 if ( !this.loading ) {
945 this.load();
947 this.once( 'load', callback );
952 * Set the size of the frame.
954 * @param {number} width Frame width in pixels
955 * @param {number} height Frame height in pixels
956 * @chainable
958 OO.ui.Frame.prototype.setSize = function ( width, height ) {
959 this.$element.css( { 'width': width, 'height': height } );
960 return this;
963 * Container for elements in a child frame.
965 * There are two ways to specify a title: set the static `title` property or provide a `title`
966 * property in the configuration options. The latter will override the former.
968 * @abstract
969 * @class
970 * @extends OO.ui.Element
971 * @mixins OO.EventEmitter
973 * @constructor
974 * @param {Object} [config] Configuration options
975 * @cfg {string|Function} [title] Title string or function that returns a string
976 * @cfg {string} [icon] Symbolic name of icon
977 * @fires initialize
979 OO.ui.Window = function OoUiWindow( config ) {
980 // Parent constructor
981 OO.ui.Window.super.call( this, config );
983 // Mixin constructors
984 OO.EventEmitter.call( this );
986 // Properties
987 this.visible = false;
988 this.opening = false;
989 this.closing = false;
990 this.title = OO.ui.resolveMsg( config.title || this.constructor.static.title );
991 this.icon = config.icon || this.constructor.static.icon;
992 this.frame = new OO.ui.Frame( { '$': this.$ } );
993 this.$frame = this.$( '<div>' );
994 this.$ = function () {
995 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
998 // Initialization
999 this.$element
1000 .addClass( 'oo-ui-window' )
1001 // Hide the window using visibility: hidden; while the iframe is still loading
1002 // Can't use display: none; because that prevents the iframe from loading in Firefox
1003 .css( 'visibility', 'hidden' )
1004 .append( this.$frame );
1005 this.$frame
1006 .addClass( 'oo-ui-window-frame' )
1007 .append( this.frame.$element );
1009 // Events
1010 this.frame.connect( this, { 'load': 'initialize' } );
1013 /* Setup */
1015 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1016 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1018 /* Events */
1021 * Initialize contents.
1023 * Fired asynchronously after construction when iframe is ready.
1025 * @event initialize
1029 * Open window.
1031 * Fired after window has been opened.
1033 * @event open
1034 * @param {Object} data Window opening data
1038 * Close window.
1040 * Fired after window has been closed.
1042 * @event close
1043 * @param {Object} data Window closing data
1046 /* Static Properties */
1049 * Symbolic name of icon.
1051 * @static
1052 * @inheritable
1053 * @property {string}
1055 OO.ui.Window.static.icon = 'window';
1058 * Window title.
1060 * Subclasses must implement this property before instantiating the window.
1061 * Alternatively, override #getTitle with an alternative implementation.
1063 * @static
1064 * @abstract
1065 * @inheritable
1066 * @property {string|Function} Title string or function that returns a string
1068 OO.ui.Window.static.title = null;
1070 /* Methods */
1073 * Check if window is visible.
1075 * @return {boolean} Window is visible
1077 OO.ui.Window.prototype.isVisible = function () {
1078 return this.visible;
1082 * Check if window is opening.
1084 * @return {boolean} Window is opening
1086 OO.ui.Window.prototype.isOpening = function () {
1087 return this.opening;
1091 * Check if window is closing.
1093 * @return {boolean} Window is closing
1095 OO.ui.Window.prototype.isClosing = function () {
1096 return this.closing;
1100 * Get the window frame.
1102 * @return {OO.ui.Frame} Frame of window
1104 OO.ui.Window.prototype.getFrame = function () {
1105 return this.frame;
1109 * Get the title of the window.
1111 * @return {string} Title text
1113 OO.ui.Window.prototype.getTitle = function () {
1114 return this.title;
1118 * Get the window icon.
1120 * @return {string} Symbolic name of icon
1122 OO.ui.Window.prototype.getIcon = function () {
1123 return this.icon;
1127 * Set the size of window frame.
1129 * @param {number} [width=auto] Custom width
1130 * @param {number} [height=auto] Custom height
1131 * @chainable
1133 OO.ui.Window.prototype.setSize = function ( width, height ) {
1134 if ( !this.frame.$content ) {
1135 return;
1138 this.frame.$element.css( {
1139 'width': width === undefined ? 'auto' : width,
1140 'height': height === undefined ? 'auto' : height
1141 } );
1143 return this;
1147 * Set the title of the window.
1149 * @param {string|Function} title Title text or a function that returns text
1150 * @chainable
1152 OO.ui.Window.prototype.setTitle = function ( title ) {
1153 this.title = OO.ui.resolveMsg( title );
1154 if ( this.$title ) {
1155 this.$title.text( title );
1157 return this;
1161 * Set the icon of the window.
1163 * @param {string} icon Symbolic name of icon
1164 * @chainable
1166 OO.ui.Window.prototype.setIcon = function ( icon ) {
1167 if ( this.$icon ) {
1168 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
1170 this.icon = icon;
1171 if ( this.$icon ) {
1172 this.$icon.addClass( 'oo-ui-icon-' + this.icon );
1175 return this;
1179 * Set the position of window to fit with contents.
1181 * @param {string} left Left offset
1182 * @param {string} top Top offset
1183 * @chainable
1185 OO.ui.Window.prototype.setPosition = function ( left, top ) {
1186 this.$element.css( { 'left': left, 'top': top } );
1187 return this;
1191 * Set the height of window to fit with contents.
1193 * @param {number} [min=0] Min height
1194 * @param {number} [max] Max height (defaults to content's outer height)
1195 * @chainable
1197 OO.ui.Window.prototype.fitHeightToContents = function ( min, max ) {
1198 var height = this.frame.$content.outerHeight();
1200 this.frame.$element.css(
1201 'height', Math.max( min || 0, max === undefined ? height : Math.min( max, height ) )
1204 return this;
1208 * Set the width of window to fit with contents.
1210 * @param {number} [min=0] Min height
1211 * @param {number} [max] Max height (defaults to content's outer width)
1212 * @chainable
1214 OO.ui.Window.prototype.fitWidthToContents = function ( min, max ) {
1215 var width = this.frame.$content.outerWidth();
1217 this.frame.$element.css(
1218 'width', Math.max( min || 0, max === undefined ? width : Math.min( max, width ) )
1221 return this;
1225 * Initialize window contents.
1227 * The first time the window is opened, #initialize is called when it's safe to begin populating
1228 * its contents. See #setup for a way to make changes each time the window opens.
1230 * Once this method is called, this.$$ can be used to create elements within the frame.
1232 * @fires initialize
1233 * @chainable
1235 OO.ui.Window.prototype.initialize = function () {
1236 // Properties
1237 this.$ = this.frame.$;
1238 this.$title = this.$( '<div class="oo-ui-window-title"></div>' )
1239 .text( this.title );
1240 this.$icon = this.$( '<div class="oo-ui-window-icon"></div>' )
1241 .addClass( 'oo-ui-icon-' + this.icon );
1242 this.$head = this.$( '<div class="oo-ui-window-head"></div>' );
1243 this.$body = this.$( '<div class="oo-ui-window-body"></div>' );
1244 this.$foot = this.$( '<div class="oo-ui-window-foot"></div>' );
1245 this.$overlay = this.$( '<div class="oo-ui-window-overlay"></div>' );
1247 // Initialization
1248 this.frame.$content.append(
1249 this.$head.append( this.$icon, this.$title ),
1250 this.$body,
1251 this.$foot,
1252 this.$overlay
1255 // Undo the visibility: hidden; hack from the constructor and apply display: none;
1256 // We can do this safely now that the iframe has initialized
1257 this.$element.hide().css( 'visibility', '' );
1259 this.emit( 'initialize' );
1261 return this;
1265 * Setup window for use.
1267 * Each time the window is opened, once it's ready to be interacted with, this will set it up for
1268 * use in a particular context, based on the `data` argument.
1270 * When you override this method, you must call the parent method at the very beginning.
1272 * @abstract
1273 * @param {Object} [data] Window opening data
1275 OO.ui.Window.prototype.setup = function () {
1276 // Override to do something
1280 * Tear down window after use.
1282 * Each time the window is closed, and it's done being interacted with, this will tear it down and
1283 * do something with the user's interactions within the window, based on the `data` argument.
1285 * When you override this method, you must call the parent method at the very end.
1287 * @abstract
1288 * @param {Object} [data] Window closing data
1290 OO.ui.Window.prototype.teardown = function () {
1291 // Override to do something
1295 * Open window.
1297 * Do not override this method. See #setup for a way to make changes each time the window opens.
1299 * @param {Object} [data] Window opening data
1300 * @fires opening
1301 * @fires open
1302 * @fires ready
1303 * @chainable
1305 OO.ui.Window.prototype.open = function ( data ) {
1306 if ( !this.opening && !this.closing && !this.visible ) {
1307 this.opening = true;
1308 this.frame.run( OO.ui.bind( function () {
1309 this.$element.show();
1310 this.visible = true;
1311 this.emit( 'opening', data );
1312 this.setup( data );
1313 this.emit( 'open', data );
1314 setTimeout( OO.ui.bind( function () {
1315 // Focus the content div (which has a tabIndex) to inactivate
1316 // (but not clear) selections in the parent frame.
1317 // Must happen after 'open' is emitted (to ensure it is visible)
1318 // but before 'ready' is emitted (so subclasses can give focus to something else)
1319 this.frame.$content.focus();
1320 this.emit( 'ready', data );
1321 this.opening = false;
1322 }, this ) );
1323 }, this ) );
1326 return this;
1330 * Close window.
1332 * See #teardown for a way to do something each time the window closes.
1334 * @param {Object} [data] Window closing data
1335 * @fires closing
1336 * @fires close
1337 * @chainable
1339 OO.ui.Window.prototype.close = function ( data ) {
1340 if ( !this.opening && !this.closing && this.visible ) {
1341 this.frame.$content.find( ':focus' ).blur();
1342 this.closing = true;
1343 this.$element.hide();
1344 this.visible = false;
1345 this.emit( 'closing', data );
1346 this.teardown( data );
1347 this.emit( 'close', data );
1348 this.closing = false;
1351 return this;
1354 * Set of mutually exclusive windows.
1356 * @class
1357 * @extends OO.ui.Element
1358 * @mixins OO.EventEmitter
1360 * @constructor
1361 * @param {OO.Factory} factory Window factory
1362 * @param {Object} [config] Configuration options
1364 OO.ui.WindowSet = function OoUiWindowSet( factory, config ) {
1365 // Parent constructor
1366 OO.ui.WindowSet.super.call( this, config );
1368 // Mixin constructors
1369 OO.EventEmitter.call( this );
1371 // Properties
1372 this.factory = factory;
1375 * List of all windows associated with this window set.
1377 * @property {OO.ui.Window[]}
1379 this.windowList = [];
1382 * Mapping of OO.ui.Window objects created by name from the #factory.
1384 * @property {Object}
1386 this.windows = {};
1387 this.currentWindow = null;
1389 // Initialization
1390 this.$element.addClass( 'oo-ui-windowSet' );
1393 /* Setup */
1395 OO.inheritClass( OO.ui.WindowSet, OO.ui.Element );
1396 OO.mixinClass( OO.ui.WindowSet, OO.EventEmitter );
1398 /* Events */
1401 * @event opening
1402 * @param {OO.ui.Window} win Window that's being opened
1403 * @param {Object} config Window opening information
1407 * @event open
1408 * @param {OO.ui.Window} win Window that's been opened
1409 * @param {Object} config Window opening information
1413 * @event closing
1414 * @param {OO.ui.Window} win Window that's being closed
1415 * @param {Object} config Window closing information
1419 * @event close
1420 * @param {OO.ui.Window} win Window that's been closed
1421 * @param {Object} config Window closing information
1424 /* Methods */
1427 * Handle a window that's being opened.
1429 * @param {OO.ui.Window} win Window that's being opened
1430 * @param {Object} [config] Window opening information
1431 * @fires opening
1433 OO.ui.WindowSet.prototype.onWindowOpening = function ( win, config ) {
1434 if ( this.currentWindow && this.currentWindow !== win ) {
1435 this.currentWindow.close();
1437 this.currentWindow = win;
1438 this.emit( 'opening', win, config );
1442 * Handle a window that's been opened.
1444 * @param {OO.ui.Window} win Window that's been opened
1445 * @param {Object} [config] Window opening information
1446 * @fires open
1448 OO.ui.WindowSet.prototype.onWindowOpen = function ( win, config ) {
1449 this.emit( 'open', win, config );
1453 * Handle a window that's being closed.
1455 * @param {OO.ui.Window} win Window that's being closed
1456 * @param {Object} [config] Window closing information
1457 * @fires closing
1459 OO.ui.WindowSet.prototype.onWindowClosing = function ( win, config ) {
1460 this.currentWindow = null;
1461 this.emit( 'closing', win, config );
1465 * Handle a window that's been closed.
1467 * @param {OO.ui.Window} win Window that's been closed
1468 * @param {Object} [config] Window closing information
1469 * @fires close
1471 OO.ui.WindowSet.prototype.onWindowClose = function ( win, config ) {
1472 this.emit( 'close', win, config );
1476 * Get the current window.
1478 * @return {OO.ui.Window|null} Current window or null if none open
1480 OO.ui.WindowSet.prototype.getCurrentWindow = function () {
1481 return this.currentWindow;
1485 * Return a given window.
1487 * @param {string} name Symbolic name of window
1488 * @return {OO.ui.Window} Window with specified name
1490 OO.ui.WindowSet.prototype.getWindow = function ( name ) {
1491 var win;
1493 if ( !this.factory.lookup( name ) ) {
1494 throw new Error( 'Unknown window: ' + name );
1496 if ( !( name in this.windows ) ) {
1497 win = this.windows[name] = this.createWindow( name );
1498 this.addWindow( win );
1500 return this.windows[name];
1504 * Create a window for use in this window set.
1506 * @param {string} name Symbolic name of window
1507 * @return {OO.ui.Window} Window with specified name
1509 OO.ui.WindowSet.prototype.createWindow = function ( name ) {
1510 return this.factory.create( name, { '$': this.$ } );
1514 * Add a given window to this window set.
1516 * Connects event handlers and attaches it to the DOM. Calling
1517 * OO.ui.Window#open will not work until the window is added to the set.
1519 * @param {OO.ui.Window} win
1521 OO.ui.WindowSet.prototype.addWindow = function ( win ) {
1522 if ( this.windowList.indexOf( win ) !== -1 ) {
1523 // Already set up
1524 return;
1526 this.windowList.push( win );
1528 win.connect( this, {
1529 'opening': [ 'onWindowOpening', win ],
1530 'open': [ 'onWindowOpen', win ],
1531 'closing': [ 'onWindowClosing', win ],
1532 'close': [ 'onWindowClose', win ]
1533 } );
1534 this.$element.append( win.$element );
1537 * Modal dialog window.
1539 * @abstract
1540 * @class
1541 * @extends OO.ui.Window
1543 * @constructor
1544 * @param {Object} [config] Configuration options
1545 * @cfg {boolean} [footless] Hide foot
1546 * @cfg {string} [size='large'] Symbolic name of dialog size, `small`, `medium` or `large`
1548 OO.ui.Dialog = function OoUiDialog( config ) {
1549 // Configuration initialization
1550 config = $.extend( { 'size': 'large' }, config );
1552 // Parent constructor
1553 OO.ui.Dialog.super.call( this, config );
1555 // Properties
1556 this.visible = false;
1557 this.footless = !!config.footless;
1558 this.size = null;
1559 this.pending = 0;
1560 this.onWindowMouseWheelHandler = OO.ui.bind( this.onWindowMouseWheel, this );
1561 this.onDocumentKeyDownHandler = OO.ui.bind( this.onDocumentKeyDown, this );
1563 // Events
1564 this.$element.on( 'mousedown', false );
1565 this.connect( this, { 'opening': 'onOpening' } );
1567 // Initialization
1568 this.$element.addClass( 'oo-ui-dialog' );
1569 this.setSize( config.size );
1572 /* Setup */
1574 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
1576 /* Static Properties */
1579 * Symbolic name of dialog.
1581 * @abstract
1582 * @static
1583 * @inheritable
1584 * @property {string}
1586 OO.ui.Dialog.static.name = '';
1589 * Map of symbolic size names and CSS classes.
1591 * @static
1592 * @inheritable
1593 * @property {Object}
1595 OO.ui.Dialog.static.sizeCssClasses = {
1596 'small': 'oo-ui-dialog-small',
1597 'medium': 'oo-ui-dialog-medium',
1598 'large': 'oo-ui-dialog-large'
1601 /* Methods */
1604 * Handle close button click events.
1606 OO.ui.Dialog.prototype.onCloseButtonClick = function () {
1607 this.close( { 'action': 'cancel' } );
1611 * Handle window mouse wheel events.
1613 * @param {jQuery.Event} e Mouse wheel event
1615 OO.ui.Dialog.prototype.onWindowMouseWheel = function () {
1616 return false;
1620 * Handle document key down events.
1622 * @param {jQuery.Event} e Key down event
1624 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
1625 switch ( e.which ) {
1626 case OO.ui.Keys.PAGEUP:
1627 case OO.ui.Keys.PAGEDOWN:
1628 case OO.ui.Keys.END:
1629 case OO.ui.Keys.HOME:
1630 case OO.ui.Keys.LEFT:
1631 case OO.ui.Keys.UP:
1632 case OO.ui.Keys.RIGHT:
1633 case OO.ui.Keys.DOWN:
1634 // Prevent any key events that might cause scrolling
1635 return false;
1640 * Handle frame document key down events.
1642 * @param {jQuery.Event} e Key down event
1644 OO.ui.Dialog.prototype.onFrameDocumentKeyDown = function ( e ) {
1645 if ( e.which === OO.ui.Keys.ESCAPE ) {
1646 this.close( { 'action': 'cancel' } );
1647 return false;
1651 /** */
1652 OO.ui.Dialog.prototype.onOpening = function () {
1653 this.$element.addClass( 'oo-ui-dialog-open' );
1657 * Set dialog size.
1659 * @param {string} [size='large'] Symbolic name of dialog size, `small`, `medium` or `large`
1661 OO.ui.Dialog.prototype.setSize = function ( size ) {
1662 var name, state, cssClass,
1663 sizeCssClasses = OO.ui.Dialog.static.sizeCssClasses;
1665 if ( !sizeCssClasses[size] ) {
1666 size = 'large';
1668 this.size = size;
1669 for ( name in sizeCssClasses ) {
1670 state = name === size;
1671 cssClass = sizeCssClasses[name];
1672 this.$element.toggleClass( cssClass, state );
1673 if ( this.frame.$content ) {
1674 this.frame.$content.toggleClass( cssClass, state );
1680 * @inheritdoc
1682 OO.ui.Dialog.prototype.initialize = function () {
1683 // Parent method
1684 OO.ui.Window.prototype.initialize.call( this );
1686 // Properties
1687 this.closeButton = new OO.ui.ButtonWidget( {
1688 '$': this.$,
1689 'frameless': true,
1690 'icon': 'close',
1691 'title': OO.ui.msg( 'ooui-dialog-action-close' )
1692 } );
1694 // Events
1695 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
1696 this.frame.$document.on( 'keydown', OO.ui.bind( this.onFrameDocumentKeyDown, this ) );
1698 // Initialization
1699 this.frame.$content.addClass( 'oo-ui-dialog-content' );
1700 if ( this.footless ) {
1701 this.frame.$content.addClass( 'oo-ui-dialog-content-footless' );
1703 this.closeButton.$element.addClass( 'oo-ui-window-closeButton' );
1704 this.$head.append( this.closeButton.$element );
1708 * @inheritdoc
1710 OO.ui.Dialog.prototype.setup = function ( data ) {
1711 // Parent method
1712 OO.ui.Window.prototype.setup.call( this, data );
1714 // Prevent scrolling in top-level window
1715 this.$( window ).on( 'mousewheel', this.onWindowMouseWheelHandler );
1716 this.$( document ).on( 'keydown', this.onDocumentKeyDownHandler );
1720 * @inheritdoc
1722 OO.ui.Dialog.prototype.teardown = function ( data ) {
1723 // Parent method
1724 OO.ui.Window.prototype.teardown.call( this, data );
1726 // Allow scrolling in top-level window
1727 this.$( window ).off( 'mousewheel', this.onWindowMouseWheelHandler );
1728 this.$( document ).off( 'keydown', this.onDocumentKeyDownHandler );
1732 * @inheritdoc
1734 OO.ui.Dialog.prototype.close = function ( data ) {
1735 var dialog = this;
1736 if ( !dialog.opening && !dialog.closing && dialog.visible ) {
1737 // Trigger transition
1738 dialog.$element.removeClass( 'oo-ui-dialog-open' );
1739 // Allow transition to complete before actually closing
1740 setTimeout( function () {
1741 // Parent method
1742 OO.ui.Window.prototype.close.call( dialog, data );
1743 }, 250 );
1748 * Check if input is pending.
1750 * @return {boolean}
1752 OO.ui.Dialog.prototype.isPending = function () {
1753 return !!this.pending;
1757 * Increase the pending stack.
1759 * @chainable
1761 OO.ui.Dialog.prototype.pushPending = function () {
1762 if ( this.pending === 0 ) {
1763 this.frame.$content.addClass( 'oo-ui-dialog-pending' );
1764 this.$head.addClass( 'oo-ui-texture-pending' );
1765 this.$foot.addClass( 'oo-ui-texture-pending' );
1767 this.pending++;
1769 return this;
1773 * Reduce the pending stack.
1775 * Clamped at zero.
1777 * @chainable
1779 OO.ui.Dialog.prototype.popPending = function () {
1780 if ( this.pending === 1 ) {
1781 this.frame.$content.removeClass( 'oo-ui-dialog-pending' );
1782 this.$head.removeClass( 'oo-ui-texture-pending' );
1783 this.$foot.removeClass( 'oo-ui-texture-pending' );
1785 this.pending = Math.max( 0, this.pending - 1 );
1787 return this;
1790 * Container for elements.
1792 * @abstract
1793 * @class
1794 * @extends OO.ui.Element
1795 * @mixins OO.EventEmitter
1797 * @constructor
1798 * @param {Object} [config] Configuration options
1800 OO.ui.Layout = function OoUiLayout( config ) {
1801 // Initialize config
1802 config = config || {};
1804 // Parent constructor
1805 OO.ui.Layout.super.call( this, config );
1807 // Mixin constructors
1808 OO.EventEmitter.call( this );
1810 // Initialization
1811 this.$element.addClass( 'oo-ui-layout' );
1814 /* Setup */
1816 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1817 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1819 * User interface control.
1821 * @abstract
1822 * @class
1823 * @extends OO.ui.Element
1824 * @mixins OO.EventEmitter
1826 * @constructor
1827 * @param {Object} [config] Configuration options
1828 * @cfg {boolean} [disabled=false] Disable
1830 OO.ui.Widget = function OoUiWidget( config ) {
1831 // Initialize config
1832 config = $.extend( { 'disabled': false }, config );
1834 // Parent constructor
1835 OO.ui.Widget.super.call( this, config );
1837 // Mixin constructors
1838 OO.EventEmitter.call( this );
1840 // Properties
1841 this.disabled = null;
1842 this.wasDisabled = null;
1844 // Initialization
1845 this.$element.addClass( 'oo-ui-widget' );
1846 this.setDisabled( !!config.disabled );
1849 /* Setup */
1851 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1852 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1854 /* Events */
1857 * @event disable
1858 * @param {boolean} disabled Widget is disabled
1861 /* Methods */
1864 * Check if the widget is disabled.
1866 * @param {boolean} Button is disabled
1868 OO.ui.Widget.prototype.isDisabled = function () {
1869 return this.disabled;
1873 * Update the disabled state, in case of changes in parent widget.
1875 * @chainable
1877 OO.ui.Widget.prototype.updateDisabled = function () {
1878 this.setDisabled( this.disabled );
1879 return this;
1883 * Set the disabled state of the widget.
1885 * This should probably change the widgets' appearance and prevent it from being used.
1887 * @param {boolean} disabled Disable widget
1888 * @chainable
1890 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1891 var isDisabled;
1893 this.disabled = !!disabled;
1894 isDisabled = this.isDisabled();
1895 if ( isDisabled !== this.wasDisabled ) {
1896 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1897 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1898 this.emit( 'disable', isDisabled );
1900 this.wasDisabled = isDisabled;
1901 return this;
1904 * Element with a button.
1906 * @abstract
1907 * @class
1909 * @constructor
1910 * @param {jQuery} $button Button node, assigned to #$button
1911 * @param {Object} [config] Configuration options
1912 * @cfg {boolean} [frameless] Render button without a frame
1913 * @cfg {number} [tabIndex=0] Button's tab index, use -1 to prevent tab focusing
1915 OO.ui.ButtonedElement = function OoUiButtonedElement( $button, config ) {
1916 // Configuration initialization
1917 config = config || {};
1919 // Properties
1920 this.$button = $button;
1921 this.tabIndex = null;
1922 this.active = false;
1923 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
1925 // Events
1926 this.$button.on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
1928 // Initialization
1929 this.$element.addClass( 'oo-ui-buttonedElement' );
1930 this.$button
1931 .addClass( 'oo-ui-buttonedElement-button' )
1932 .attr( 'role', 'button' )
1933 .prop( 'tabIndex', config.tabIndex || 0 );
1934 if ( config.frameless ) {
1935 this.$element.addClass( 'oo-ui-buttonedElement-frameless' );
1936 } else {
1937 this.$element.addClass( 'oo-ui-buttonedElement-framed' );
1941 /* Methods */
1944 * Handles mouse down events.
1946 * @param {jQuery.Event} e Mouse down event
1948 OO.ui.ButtonedElement.prototype.onMouseDown = function ( e ) {
1949 if ( this.isDisabled() || e.which !== 1 ) {
1950 return false;
1952 // tabIndex should generally be interacted with via the property,
1953 // but it's not possible to reliably unset a tabIndex via a property
1954 // so we use the (lowercase) "tabindex" attribute instead.
1955 this.tabIndex = this.$button.attr( 'tabindex' );
1956 // Remove the tab-index while the button is down to prevent the button from stealing focus
1957 this.$button
1958 .removeAttr( 'tabindex' )
1959 .addClass( 'oo-ui-buttonedElement-pressed' );
1960 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
1961 return false;
1965 * Handles mouse up events.
1967 * @param {jQuery.Event} e Mouse up event
1969 OO.ui.ButtonedElement.prototype.onMouseUp = function ( e ) {
1970 if ( this.isDisabled() || e.which !== 1 ) {
1971 return false;
1973 // Restore the tab-index after the button is up to restore the button's accesssibility
1974 this.$button
1975 .attr( 'tabindex', this.tabIndex )
1976 .removeClass( 'oo-ui-buttonedElement-pressed' );
1977 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
1981 * Set active state.
1983 * @param {boolean} [value] Make button active
1984 * @chainable
1986 OO.ui.ButtonedElement.prototype.setActive = function ( value ) {
1987 this.$button.toggleClass( 'oo-ui-buttonedElement-active', !!value );
1988 return this;
1991 * Element that can be automatically clipped to visible boundaies.
1993 * @abstract
1994 * @class
1996 * @constructor
1997 * @param {jQuery} $clippable Nodes to clip, assigned to #$clippable
1998 * @param {Object} [config] Configuration options
2000 OO.ui.ClippableElement = function OoUiClippableElement( $clippable, config ) {
2001 // Configuration initialization
2002 config = config || {};
2004 // Properties
2005 this.$clippable = $clippable;
2006 this.clipping = false;
2007 this.clipped = false;
2008 this.$clippableContainer = null;
2009 this.$clippableScroller = null;
2010 this.$clippableWindow = null;
2011 this.idealWidth = null;
2012 this.idealHeight = null;
2013 this.onClippableContainerScrollHandler = OO.ui.bind( this.clip, this );
2014 this.onClippableWindowResizeHandler = OO.ui.bind( this.clip, this );
2016 // Initialization
2017 this.$clippable.addClass( 'oo-ui-clippableElement-clippable' );
2020 /* Methods */
2023 * Set clipping.
2025 * @param {boolean} value Enable clipping
2026 * @chainable
2028 OO.ui.ClippableElement.prototype.setClipping = function ( value ) {
2029 value = !!value;
2031 if ( this.clipping !== value ) {
2032 this.clipping = value;
2033 if ( this.clipping ) {
2034 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
2035 // If the clippable container is the body, we have to listen to scroll events and check
2036 // jQuery.scrollTop on the window because of browser inconsistencies
2037 this.$clippableScroller = this.$clippableContainer.is( 'body' ) ?
2038 this.$( OO.ui.Element.getWindow( this.$clippableContainer ) ) :
2039 this.$clippableContainer;
2040 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
2041 this.$clippableWindow = this.$( this.getElementWindow() )
2042 .on( 'resize', this.onClippableWindowResizeHandler );
2043 // Initial clip after visible
2044 setTimeout( OO.ui.bind( this.clip, this ) );
2045 } else {
2046 this.$clippableContainer = null;
2047 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
2048 this.$clippableScroller = null;
2049 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
2050 this.$clippableWindow = null;
2054 return this;
2058 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
2060 * @return {boolean} Element will be clipped to the visible area
2062 OO.ui.ClippableElement.prototype.isClipping = function () {
2063 return this.clipping;
2067 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
2069 * @return {boolean} Part of the element is being clipped
2071 OO.ui.ClippableElement.prototype.isClipped = function () {
2072 return this.clipped;
2076 * Set the ideal size.
2078 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
2079 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
2081 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
2082 this.idealWidth = width;
2083 this.idealHeight = height;
2087 * Clip element to visible boundaries and allow scrolling when needed.
2089 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
2090 * overlapped by, the visible area of the nearest scrollable container.
2092 * @chainable
2094 OO.ui.ClippableElement.prototype.clip = function () {
2095 if ( !this.clipping ) {
2096 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
2097 return this;
2100 var buffer = 10,
2101 cOffset = this.$clippable.offset(),
2102 ccOffset = this.$clippableContainer.offset() || { 'top': 0, 'left': 0 },
2103 ccHeight = this.$clippableContainer.innerHeight() - buffer,
2104 ccWidth = this.$clippableContainer.innerWidth() - buffer,
2105 scrollTop = this.$clippableScroller.scrollTop(),
2106 scrollLeft = this.$clippableScroller.scrollLeft(),
2107 desiredWidth = ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
2108 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
2109 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
2110 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
2111 clipWidth = desiredWidth < naturalWidth,
2112 clipHeight = desiredHeight < naturalHeight;
2114 if ( clipWidth ) {
2115 this.$clippable.css( { 'overflow-x': 'auto', 'width': desiredWidth } );
2116 } else {
2117 this.$clippable.css( { 'overflow-x': '', 'width': this.idealWidth || '' } );
2119 if ( clipHeight ) {
2120 this.$clippable.css( { 'overflow-y': 'auto', 'height': desiredHeight } );
2121 } else {
2122 this.$clippable.css( { 'overflow-y': '', 'height': this.idealHeight || '' } );
2125 this.clipped = clipWidth || clipHeight;
2127 return this;
2130 * Element with named flags that can be added, removed, listed and checked.
2132 * A flag, when set, adds a CSS class on the `$element` by combing `oo-ui-flaggableElement-` with
2133 * the flag name. Flags are primarily useful for styling.
2135 * @abstract
2136 * @class
2138 * @constructor
2139 * @param {Object} [config] Configuration options
2140 * @cfg {string[]} [flags=[]] Styling flags, e.g. 'primary', 'destructive' or 'constructive'
2142 OO.ui.FlaggableElement = function OoUiFlaggableElement( config ) {
2143 // Config initialization
2144 config = config || {};
2146 // Properties
2147 this.flags = {};
2149 // Initialization
2150 this.setFlags( config.flags );
2153 /* Methods */
2156 * Check if a flag is set.
2158 * @param {string} flag Name of flag
2159 * @return {boolean} Has flag
2161 OO.ui.FlaggableElement.prototype.hasFlag = function ( flag ) {
2162 return flag in this.flags;
2166 * Get the names of all flags set.
2168 * @return {string[]} flags Flag names
2170 OO.ui.FlaggableElement.prototype.getFlags = function () {
2171 return Object.keys( this.flags );
2175 * Clear all flags.
2177 * @chainable
2179 OO.ui.FlaggableElement.prototype.clearFlags = function () {
2180 var flag,
2181 classPrefix = 'oo-ui-flaggableElement-';
2183 for ( flag in this.flags ) {
2184 delete this.flags[flag];
2185 this.$element.removeClass( classPrefix + flag );
2188 return this;
2192 * Add one or more flags.
2194 * @param {string[]|Object.<string, boolean>} flags List of flags to add, or list of set/remove
2195 * values, keyed by flag name
2196 * @chainable
2198 OO.ui.FlaggableElement.prototype.setFlags = function ( flags ) {
2199 var i, len, flag,
2200 classPrefix = 'oo-ui-flaggableElement-';
2202 if ( $.isArray( flags ) ) {
2203 for ( i = 0, len = flags.length; i < len; i++ ) {
2204 flag = flags[i];
2205 // Set
2206 this.flags[flag] = true;
2207 this.$element.addClass( classPrefix + flag );
2209 } else if ( OO.isPlainObject( flags ) ) {
2210 for ( flag in flags ) {
2211 if ( flags[flag] ) {
2212 // Set
2213 this.flags[flag] = true;
2214 this.$element.addClass( classPrefix + flag );
2215 } else {
2216 // Remove
2217 delete this.flags[flag];
2218 this.$element.removeClass( classPrefix + flag );
2222 return this;
2225 * Element containing a sequence of child elements.
2227 * @abstract
2228 * @class
2230 * @constructor
2231 * @param {jQuery} $group Container node, assigned to #$group
2232 * @param {Object} [config] Configuration options
2234 OO.ui.GroupElement = function OoUiGroupElement( $group, config ) {
2235 // Configuration
2236 config = config || {};
2238 // Properties
2239 this.$group = $group;
2240 this.items = [];
2241 this.$items = this.$( [] );
2242 this.aggregateItemEvents = {};
2245 /* Methods */
2248 * Get items.
2250 * @return {OO.ui.Element[]} Items
2252 OO.ui.GroupElement.prototype.getItems = function () {
2253 return this.items.slice( 0 );
2257 * Add an aggregate item event.
2259 * Aggregated events are listened to on each item and then emitted by the group under a new name,
2260 * and with an additional leading parameter containing the item that emitted the original event.
2261 * Other arguments that were emitted from the original event are passed through.
2263 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
2264 * event, use null value to remove aggregation
2265 * @throws {Error} If aggregation already exists
2267 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
2268 var i, len, item, add, remove, itemEvent, groupEvent;
2270 for ( itemEvent in events ) {
2271 groupEvent = events[itemEvent];
2273 // Remove existing aggregated event
2274 if ( itemEvent in this.aggregateItemEvents ) {
2275 // Don't allow duplicate aggregations
2276 if ( groupEvent ) {
2277 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
2279 // Remove event aggregation from existing items
2280 for ( i = 0, len = this.items.length; i < len; i++ ) {
2281 item = this.items[i];
2282 if ( item.connect && item.disconnect ) {
2283 remove = {};
2284 remove[itemEvent] = [ 'emit', groupEvent, item ];
2285 item.disconnect( this, remove );
2288 // Prevent future items from aggregating event
2289 delete this.aggregateItemEvents[itemEvent];
2292 // Add new aggregate event
2293 if ( groupEvent ) {
2294 // Make future items aggregate event
2295 this.aggregateItemEvents[itemEvent] = groupEvent;
2296 // Add event aggregation to existing items
2297 for ( i = 0, len = this.items.length; i < len; i++ ) {
2298 item = this.items[i];
2299 if ( item.connect && item.disconnect ) {
2300 add = {};
2301 add[itemEvent] = [ 'emit', groupEvent, item ];
2302 item.connect( this, add );
2310 * Add items.
2312 * @param {OO.ui.Element[]} items Item
2313 * @param {number} [index] Index to insert items at
2314 * @chainable
2316 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
2317 var i, len, item, event, events, currentIndex,
2318 $items = this.$( [] );
2320 for ( i = 0, len = items.length; i < len; i++ ) {
2321 item = items[i];
2323 // Check if item exists then remove it first, effectively "moving" it
2324 currentIndex = $.inArray( item, this.items );
2325 if ( currentIndex >= 0 ) {
2326 this.removeItems( [ item ] );
2327 // Adjust index to compensate for removal
2328 if ( currentIndex < index ) {
2329 index--;
2332 // Add the item
2333 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
2334 events = {};
2335 for ( event in this.aggregateItemEvents ) {
2336 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
2338 item.connect( this, events );
2340 item.setElementGroup( this );
2341 $items = $items.add( item.$element );
2344 if ( index === undefined || index < 0 || index >= this.items.length ) {
2345 this.$group.append( $items );
2346 this.items.push.apply( this.items, items );
2347 } else if ( index === 0 ) {
2348 this.$group.prepend( $items );
2349 this.items.unshift.apply( this.items, items );
2350 } else {
2351 this.$items.eq( index ).before( $items );
2352 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
2355 this.$items = this.$items.add( $items );
2357 return this;
2361 * Remove items.
2363 * Items will be detached, not removed, so they can be used later.
2365 * @param {OO.ui.Element[]} items Items to remove
2366 * @chainable
2368 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
2369 var i, len, item, index, remove, itemEvent;
2371 // Remove specific items
2372 for ( i = 0, len = items.length; i < len; i++ ) {
2373 item = items[i];
2374 index = $.inArray( item, this.items );
2375 if ( index !== -1 ) {
2376 if (
2377 item.connect && item.disconnect &&
2378 !$.isEmptyObject( this.aggregateItemEvents )
2380 remove = {};
2381 if ( itemEvent in this.aggregateItemEvents ) {
2382 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
2384 item.disconnect( this, remove );
2386 item.setElementGroup( null );
2387 this.items.splice( index, 1 );
2388 item.$element.detach();
2389 this.$items = this.$items.not( item.$element );
2393 return this;
2397 * Clear all items.
2399 * Items will be detached, not removed, so they can be used later.
2401 * @chainable
2403 OO.ui.GroupElement.prototype.clearItems = function () {
2404 var i, len, item, remove, itemEvent;
2406 // Remove all items
2407 for ( i = 0, len = this.items.length; i < len; i++ ) {
2408 item = this.items[i];
2409 if (
2410 item.connect && item.disconnect &&
2411 !$.isEmptyObject( this.aggregateItemEvents )
2413 remove = {};
2414 if ( itemEvent in this.aggregateItemEvents ) {
2415 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
2417 item.disconnect( this, remove );
2419 item.setElementGroup( null );
2421 this.items = [];
2422 this.$items.detach();
2423 this.$items = this.$( [] );
2425 return this;
2428 * Element containing an icon.
2430 * @abstract
2431 * @class
2433 * @constructor
2434 * @param {jQuery} $icon Icon node, assigned to #$icon
2435 * @param {Object} [config] Configuration options
2436 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
2437 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2438 * language
2440 OO.ui.IconedElement = function OoUiIconedElement( $icon, config ) {
2441 // Config intialization
2442 config = config || {};
2444 // Properties
2445 this.$icon = $icon;
2446 this.icon = null;
2448 // Initialization
2449 this.$icon.addClass( 'oo-ui-iconedElement-icon' );
2450 this.setIcon( config.icon || this.constructor.static.icon );
2453 /* Setup */
2455 OO.initClass( OO.ui.IconedElement );
2457 /* Static Properties */
2460 * Icon.
2462 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
2464 * For i18n purposes, this property can be an object containing a `default` icon name property and
2465 * additional icon names keyed by language code.
2467 * Example of i18n icon definition:
2468 * { 'default': 'bold-a', 'en': 'bold-b', 'de': 'bold-f' }
2470 * @static
2471 * @inheritable
2472 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
2473 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2474 * language
2476 OO.ui.IconedElement.static.icon = null;
2478 /* Methods */
2481 * Set icon.
2483 * @param {Object|string} icon Symbolic icon name, or map of icon names keyed by language ID;
2484 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2485 * language
2486 * @chainable
2488 OO.ui.IconedElement.prototype.setIcon = function ( icon ) {
2489 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2491 if ( this.icon ) {
2492 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2494 if ( typeof icon === 'string' ) {
2495 icon = icon.trim();
2496 if ( icon.length ) {
2497 this.$icon.addClass( 'oo-ui-icon-' + icon );
2498 this.icon = icon;
2501 this.$element.toggleClass( 'oo-ui-iconedElement', !!this.icon );
2503 return this;
2507 * Get icon.
2509 * @return {string} Icon
2511 OO.ui.IconedElement.prototype.getIcon = function () {
2512 return this.icon;
2515 * Element containing an indicator.
2517 * @abstract
2518 * @class
2520 * @constructor
2521 * @param {jQuery} $indicator Indicator node, assigned to #$indicator
2522 * @param {Object} [config] Configuration options
2523 * @cfg {string} [indicator] Symbolic indicator name
2524 * @cfg {string} [indicatorTitle] Indicator title text or a function that return text
2526 OO.ui.IndicatedElement = function OoUiIndicatedElement( $indicator, config ) {
2527 // Config intialization
2528 config = config || {};
2530 // Properties
2531 this.$indicator = $indicator;
2532 this.indicator = null;
2533 this.indicatorLabel = null;
2535 // Initialization
2536 this.$indicator.addClass( 'oo-ui-indicatedElement-indicator' );
2537 this.setIndicator( config.indicator || this.constructor.static.indicator );
2538 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2541 /* Setup */
2543 OO.initClass( OO.ui.IndicatedElement );
2545 /* Static Properties */
2548 * indicator.
2550 * @static
2551 * @inheritable
2552 * @property {string|null} Symbolic indicator name or null for no indicator
2554 OO.ui.IndicatedElement.static.indicator = null;
2557 * Indicator title.
2559 * @static
2560 * @inheritable
2561 * @property {string|Function|null} Indicator title text, a function that return text or null for no
2562 * indicator title
2564 OO.ui.IndicatedElement.static.indicatorTitle = null;
2566 /* Methods */
2569 * Set indicator.
2571 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
2572 * @chainable
2574 OO.ui.IndicatedElement.prototype.setIndicator = function ( indicator ) {
2575 if ( this.indicator ) {
2576 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2577 this.indicator = null;
2579 if ( typeof indicator === 'string' ) {
2580 indicator = indicator.trim();
2581 if ( indicator.length ) {
2582 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2583 this.indicator = indicator;
2586 this.$element.toggleClass( 'oo-ui-indicatedElement', !!this.indicator );
2588 return this;
2592 * Set indicator label.
2594 * @param {string|Function|null} indicator Indicator title text, a function that return text or null
2595 * for no indicator title
2596 * @chainable
2598 OO.ui.IndicatedElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2599 this.indicatorTitle = indicatorTitle = OO.ui.resolveMsg( indicatorTitle );
2601 if ( typeof indicatorTitle === 'string' && indicatorTitle.length ) {
2602 this.$indicator.attr( 'title', indicatorTitle );
2603 } else {
2604 this.$indicator.removeAttr( 'title' );
2607 return this;
2611 * Get indicator.
2613 * @return {string} title Symbolic name of indicator
2615 OO.ui.IndicatedElement.prototype.getIndicator = function () {
2616 return this.indicator;
2620 * Get indicator title.
2622 * @return {string} Indicator title text
2624 OO.ui.IndicatedElement.prototype.getIndicatorTitle = function () {
2625 return this.indicatorTitle;
2628 * Element containing a label.
2630 * @abstract
2631 * @class
2633 * @constructor
2634 * @param {jQuery} $label Label node, assigned to #$label
2635 * @param {Object} [config] Configuration options
2636 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
2637 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
2639 OO.ui.LabeledElement = function OoUiLabeledElement( $label, config ) {
2640 // Config intialization
2641 config = config || {};
2643 // Properties
2644 this.$label = $label;
2645 this.label = null;
2647 // Initialization
2648 this.$label.addClass( 'oo-ui-labeledElement-label' );
2649 this.setLabel( config.label || this.constructor.static.label );
2650 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
2653 /* Setup */
2655 OO.initClass( OO.ui.LabeledElement );
2657 /* Static Properties */
2660 * Label.
2662 * @static
2663 * @inheritable
2664 * @property {string|Function|null} Label text; a function that returns a nodes or text; or null for
2665 * no label
2667 OO.ui.LabeledElement.static.label = null;
2669 /* Methods */
2672 * Set the label.
2674 * An empty string will result in the label being hidden. A string containing only whitespace will
2675 * be converted to a single &nbsp;
2677 * @param {jQuery|string|Function|null} label Label nodes; text; a function that retuns nodes or
2678 * text; or null for no label
2679 * @chainable
2681 OO.ui.LabeledElement.prototype.setLabel = function ( label ) {
2682 var empty = false;
2684 this.label = label = OO.ui.resolveMsg( label ) || null;
2685 if ( typeof label === 'string' && label.length ) {
2686 if ( label.match( /^\s*$/ ) ) {
2687 // Convert whitespace only string to a single non-breaking space
2688 this.$label.html( '&nbsp;' );
2689 } else {
2690 this.$label.text( label );
2692 } else if ( label instanceof jQuery ) {
2693 this.$label.empty().append( label );
2694 } else {
2695 this.$label.empty();
2696 empty = true;
2698 this.$element.toggleClass( 'oo-ui-labeledElement', !empty );
2699 this.$label.css( 'display', empty ? 'none' : '' );
2701 return this;
2705 * Get the label.
2707 * @return {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2708 * text; or null for no label
2710 OO.ui.LabeledElement.prototype.getLabel = function () {
2711 return this.label;
2715 * Fit the label.
2717 * @chainable
2719 OO.ui.LabeledElement.prototype.fitLabel = function () {
2720 if ( this.$label.autoEllipsis && this.autoFitLabel ) {
2721 this.$label.autoEllipsis( { 'hasSpan': false, 'tooltip': true } );
2723 return this;
2726 * Popuppable element.
2728 * @abstract
2729 * @class
2731 * @constructor
2732 * @param {Object} [config] Configuration options
2733 * @cfg {number} [popupWidth=320] Width of popup
2734 * @cfg {number} [popupHeight] Height of popup
2735 * @cfg {Object} [popup] Configuration to pass to popup
2737 OO.ui.PopuppableElement = function OoUiPopuppableElement( config ) {
2738 // Configuration initialization
2739 config = $.extend( { 'popupWidth': 320 }, config );
2741 // Properties
2742 this.popup = new OO.ui.PopupWidget( $.extend(
2743 { 'align': 'center', 'autoClose': true },
2744 config.popup,
2745 { '$': this.$, '$autoCloseIgnore': this.$element }
2746 ) );
2747 this.popupWidth = config.popupWidth;
2748 this.popupHeight = config.popupHeight;
2751 /* Methods */
2754 * Get popup.
2756 * @return {OO.ui.PopupWidget} Popup widget
2758 OO.ui.PopuppableElement.prototype.getPopup = function () {
2759 return this.popup;
2763 * Show popup.
2765 OO.ui.PopuppableElement.prototype.showPopup = function () {
2766 this.popup.show().display( this.popupWidth, this.popupHeight );
2770 * Hide popup.
2772 OO.ui.PopuppableElement.prototype.hidePopup = function () {
2773 this.popup.hide();
2776 * Element with a title.
2778 * @abstract
2779 * @class
2781 * @constructor
2782 * @param {jQuery} $label Titled node, assigned to #$titled
2783 * @param {Object} [config] Configuration options
2784 * @cfg {string|Function} [title] Title text or a function that returns text
2786 OO.ui.TitledElement = function OoUiTitledElement( $titled, config ) {
2787 // Config intialization
2788 config = config || {};
2790 // Properties
2791 this.$titled = $titled;
2792 this.title = null;
2794 // Initialization
2795 this.setTitle( config.title || this.constructor.static.title );
2798 /* Setup */
2800 OO.initClass( OO.ui.TitledElement );
2802 /* Static Properties */
2805 * Title.
2807 * @static
2808 * @inheritable
2809 * @property {string|Function} Title text or a function that returns text
2811 OO.ui.TitledElement.static.title = null;
2813 /* Methods */
2816 * Set title.
2818 * @param {string|Function|null} title Title text, a function that returns text or null for no title
2819 * @chainable
2821 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
2822 this.title = title = OO.ui.resolveMsg( title ) || null;
2824 if ( typeof title === 'string' && title.length ) {
2825 this.$titled.attr( 'title', title );
2826 } else {
2827 this.$titled.removeAttr( 'title' );
2830 return this;
2834 * Get title.
2836 * @return {string} Title string
2838 OO.ui.TitledElement.prototype.getTitle = function () {
2839 return this.title;
2842 * Generic toolbar tool.
2844 * @abstract
2845 * @class
2846 * @extends OO.ui.Widget
2847 * @mixins OO.ui.IconedElement
2849 * @constructor
2850 * @param {OO.ui.ToolGroup} toolGroup
2851 * @param {Object} [config] Configuration options
2852 * @cfg {string|Function} [title] Title text or a function that returns text
2854 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
2855 // Config intialization
2856 config = config || {};
2858 // Parent constructor
2859 OO.ui.Tool.super.call( this, config );
2861 // Mixin constructors
2862 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
2864 // Properties
2865 this.toolGroup = toolGroup;
2866 this.toolbar = this.toolGroup.getToolbar();
2867 this.active = false;
2868 this.$title = this.$( '<span>' );
2869 this.$link = this.$( '<a>' );
2870 this.title = null;
2872 // Events
2873 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
2875 // Initialization
2876 this.$title.addClass( 'oo-ui-tool-title' );
2877 this.$link
2878 .addClass( 'oo-ui-tool-link' )
2879 .append( this.$icon, this.$title );
2880 this.$element
2881 .data( 'oo-ui-tool', this )
2882 .addClass(
2883 'oo-ui-tool ' + 'oo-ui-tool-name-' +
2884 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
2886 .append( this.$link );
2887 this.setTitle( config.title || this.constructor.static.title );
2890 /* Setup */
2892 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
2893 OO.mixinClass( OO.ui.Tool, OO.ui.IconedElement );
2895 /* Events */
2898 * @event select
2901 /* Static Properties */
2904 * @static
2905 * @inheritdoc
2907 OO.ui.Tool.static.tagName = 'span';
2910 * Symbolic name of tool.
2912 * @abstract
2913 * @static
2914 * @inheritable
2915 * @property {string}
2917 OO.ui.Tool.static.name = '';
2920 * Tool group.
2922 * @abstract
2923 * @static
2924 * @inheritable
2925 * @property {string}
2927 OO.ui.Tool.static.group = '';
2930 * Tool title.
2932 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
2933 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
2934 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
2935 * appended to the title if the tool is part of a bar tool group.
2937 * @abstract
2938 * @static
2939 * @inheritable
2940 * @property {string|Function} Title text or a function that returns text
2942 OO.ui.Tool.static.title = '';
2945 * Tool can be automatically added to catch-all groups.
2947 * @static
2948 * @inheritable
2949 * @property {boolean}
2951 OO.ui.Tool.static.autoAddToCatchall = true;
2954 * Tool can be automatically added to named groups.
2956 * @static
2957 * @property {boolean}
2958 * @inheritable
2960 OO.ui.Tool.static.autoAddToGroup = true;
2963 * Check if this tool is compatible with given data.
2965 * @static
2966 * @inheritable
2967 * @param {Mixed} data Data to check
2968 * @return {boolean} Tool can be used with data
2970 OO.ui.Tool.static.isCompatibleWith = function () {
2971 return false;
2974 /* Methods */
2977 * Handle the toolbar state being updated.
2979 * This is an abstract method that must be overridden in a concrete subclass.
2981 * @abstract
2983 OO.ui.Tool.prototype.onUpdateState = function () {
2984 throw new Error(
2985 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
2990 * Handle the tool being selected.
2992 * This is an abstract method that must be overridden in a concrete subclass.
2994 * @abstract
2996 OO.ui.Tool.prototype.onSelect = function () {
2997 throw new Error(
2998 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
3003 * Check if the button is active.
3005 * @param {boolean} Button is active
3007 OO.ui.Tool.prototype.isActive = function () {
3008 return this.active;
3012 * Make the button appear active or inactive.
3014 * @param {boolean} state Make button appear active
3016 OO.ui.Tool.prototype.setActive = function ( state ) {
3017 this.active = !!state;
3018 if ( this.active ) {
3019 this.$element.addClass( 'oo-ui-tool-active' );
3020 } else {
3021 this.$element.removeClass( 'oo-ui-tool-active' );
3026 * Get the tool title.
3028 * @param {string|Function} title Title text or a function that returns text
3029 * @chainable
3031 OO.ui.Tool.prototype.setTitle = function ( title ) {
3032 this.title = OO.ui.resolveMsg( title );
3033 this.updateTitle();
3034 return this;
3038 * Get the tool title.
3040 * @return {string} Title text
3042 OO.ui.Tool.prototype.getTitle = function () {
3043 return this.title;
3047 * Get the tool's symbolic name.
3049 * @return {string} Symbolic name of tool
3051 OO.ui.Tool.prototype.getName = function () {
3052 return this.constructor.static.name;
3056 * Update the title.
3058 OO.ui.Tool.prototype.updateTitle = function () {
3059 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
3060 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
3061 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
3062 tooltipParts = [];
3064 this.$title.empty()
3065 .text( this.title )
3066 .append(
3067 this.$( '<span>' )
3068 .addClass( 'oo-ui-tool-accel' )
3069 .text( accel )
3072 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
3073 tooltipParts.push( this.title );
3075 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
3076 tooltipParts.push( accel );
3078 if ( tooltipParts.length ) {
3079 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
3080 } else {
3081 this.$link.removeAttr( 'title' );
3086 * Destroy tool.
3088 OO.ui.Tool.prototype.destroy = function () {
3089 this.toolbar.disconnect( this );
3090 this.$element.remove();
3093 * Collection of tool groups.
3095 * @class
3096 * @extends OO.ui.Element
3097 * @mixins OO.EventEmitter
3098 * @mixins OO.ui.GroupElement
3100 * @constructor
3101 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
3102 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
3103 * @param {Object} [config] Configuration options
3104 * @cfg {boolean} [actions] Add an actions section opposite to the tools
3105 * @cfg {boolean} [shadow] Add a shadow below the toolbar
3107 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
3108 // Configuration initialization
3109 config = config || {};
3111 // Parent constructor
3112 OO.ui.Toolbar.super.call( this, config );
3114 // Mixin constructors
3115 OO.EventEmitter.call( this );
3116 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
3118 // Properties
3119 this.toolFactory = toolFactory;
3120 this.toolGroupFactory = toolGroupFactory;
3121 this.groups = [];
3122 this.tools = {};
3123 this.$bar = this.$( '<div>' );
3124 this.$actions = this.$( '<div>' );
3125 this.initialized = false;
3127 // Events
3128 this.$element
3129 .add( this.$bar ).add( this.$group ).add( this.$actions )
3130 .on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
3132 // Initialization
3133 this.$group.addClass( 'oo-ui-toolbar-tools' );
3134 this.$bar.addClass( 'oo-ui-toolbar-bar' ).append( this.$group );
3135 if ( config.actions ) {
3136 this.$actions.addClass( 'oo-ui-toolbar-actions' );
3137 this.$bar.append( this.$actions );
3139 this.$bar.append( '<div style="clear:both"></div>' );
3140 if ( config.shadow ) {
3141 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
3143 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
3146 /* Setup */
3148 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
3149 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
3150 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
3152 /* Methods */
3155 * Get the tool factory.
3157 * @return {OO.ui.ToolFactory} Tool factory
3159 OO.ui.Toolbar.prototype.getToolFactory = function () {
3160 return this.toolFactory;
3164 * Get the tool group factory.
3166 * @return {OO.Factory} Tool group factory
3168 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
3169 return this.toolGroupFactory;
3173 * Handles mouse down events.
3175 * @param {jQuery.Event} e Mouse down event
3177 OO.ui.Toolbar.prototype.onMouseDown = function ( e ) {
3178 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
3179 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
3180 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
3181 return false;
3186 * Sets up handles and preloads required information for the toolbar to work.
3187 * This must be called immediately after it is attached to a visible document.
3189 OO.ui.Toolbar.prototype.initialize = function () {
3190 this.initialized = true;
3194 * Setup toolbar.
3196 * Tools can be specified in the following ways:
3198 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3199 * - All tools in a group: `{ 'group': 'group-name' }`
3200 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
3202 * @param {Object.<string,Array>} groups List of tool group configurations
3203 * @param {Array|string} [groups.include] Tools to include
3204 * @param {Array|string} [groups.exclude] Tools to exclude
3205 * @param {Array|string} [groups.promote] Tools to promote to the beginning
3206 * @param {Array|string} [groups.demote] Tools to demote to the end
3208 OO.ui.Toolbar.prototype.setup = function ( groups ) {
3209 var i, len, type, group,
3210 items = [],
3211 defaultType = 'bar';
3213 // Cleanup previous groups
3214 this.reset();
3216 // Build out new groups
3217 for ( i = 0, len = groups.length; i < len; i++ ) {
3218 group = groups[i];
3219 if ( group.include === '*' ) {
3220 // Apply defaults to catch-all groups
3221 if ( group.type === undefined ) {
3222 group.type = 'list';
3224 if ( group.label === undefined ) {
3225 group.label = 'ooui-toolbar-more';
3228 // Check type has been registered
3229 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
3230 items.push(
3231 this.getToolGroupFactory().create( type, this, $.extend( { '$': this.$ }, group ) )
3234 this.addItems( items );
3238 * Remove all tools and groups from the toolbar.
3240 OO.ui.Toolbar.prototype.reset = function () {
3241 var i, len;
3243 this.groups = [];
3244 this.tools = {};
3245 for ( i = 0, len = this.items.length; i < len; i++ ) {
3246 this.items[i].destroy();
3248 this.clearItems();
3252 * Destroys toolbar, removing event handlers and DOM elements.
3254 * Call this whenever you are done using a toolbar.
3256 OO.ui.Toolbar.prototype.destroy = function () {
3257 this.reset();
3258 this.$element.remove();
3262 * Check if tool has not been used yet.
3264 * @param {string} name Symbolic name of tool
3265 * @return {boolean} Tool is available
3267 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
3268 return !this.tools[name];
3272 * Prevent tool from being used again.
3274 * @param {OO.ui.Tool} tool Tool to reserve
3276 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
3277 this.tools[tool.getName()] = tool;
3281 * Allow tool to be used again.
3283 * @param {OO.ui.Tool} tool Tool to release
3285 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
3286 delete this.tools[tool.getName()];
3290 * Get accelerator label for tool.
3292 * This is a stub that should be overridden to provide access to accelerator information.
3294 * @param {string} name Symbolic name of tool
3295 * @return {string|undefined} Tool accelerator label if available
3297 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
3298 return undefined;
3301 * Factory for tools.
3303 * @class
3304 * @extends OO.Factory
3305 * @constructor
3307 OO.ui.ToolFactory = function OoUiToolFactory() {
3308 // Parent constructor
3309 OO.ui.ToolFactory.super.call( this );
3312 /* Setup */
3314 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3316 /* Methods */
3318 /** */
3319 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3320 var i, len, included, promoted, demoted,
3321 auto = [],
3322 used = {};
3324 // Collect included and not excluded tools
3325 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3327 // Promotion
3328 promoted = this.extract( promote, used );
3329 demoted = this.extract( demote, used );
3331 // Auto
3332 for ( i = 0, len = included.length; i < len; i++ ) {
3333 if ( !used[included[i]] ) {
3334 auto.push( included[i] );
3338 return promoted.concat( auto ).concat( demoted );
3342 * Get a flat list of names from a list of names or groups.
3344 * Tools can be specified in the following ways:
3346 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3347 * - All tools in a group: `{ 'group': 'group-name' }`
3348 * - All tools: `'*'`
3350 * @private
3351 * @param {Array|string} collection List of tools
3352 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3353 * names will be added as properties
3354 * @return {string[]} List of extracted names
3356 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3357 var i, len, item, name, tool,
3358 names = [];
3360 if ( collection === '*' ) {
3361 for ( name in this.registry ) {
3362 tool = this.registry[name];
3363 if (
3364 // Only add tools by group name when auto-add is enabled
3365 tool.static.autoAddToCatchall &&
3366 // Exclude already used tools
3367 ( !used || !used[name] )
3369 names.push( name );
3370 if ( used ) {
3371 used[name] = true;
3375 } else if ( $.isArray( collection ) ) {
3376 for ( i = 0, len = collection.length; i < len; i++ ) {
3377 item = collection[i];
3378 // Allow plain strings as shorthand for named tools
3379 if ( typeof item === 'string' ) {
3380 item = { 'name': item };
3382 if ( OO.isPlainObject( item ) ) {
3383 if ( item.group ) {
3384 for ( name in this.registry ) {
3385 tool = this.registry[name];
3386 if (
3387 // Include tools with matching group
3388 tool.static.group === item.group &&
3389 // Only add tools by group name when auto-add is enabled
3390 tool.static.autoAddToGroup &&
3391 // Exclude already used tools
3392 ( !used || !used[name] )
3394 names.push( name );
3395 if ( used ) {
3396 used[name] = true;
3400 // Include tools with matching name and exclude already used tools
3401 } else if ( item.name && ( !used || !used[item.name] ) ) {
3402 names.push( item.name );
3403 if ( used ) {
3404 used[item.name] = true;
3410 return names;
3413 * Collection of tools.
3415 * Tools can be specified in the following ways:
3417 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3418 * - All tools in a group: `{ 'group': 'group-name' }`
3419 * - All tools: `'*'`
3421 * @abstract
3422 * @class
3423 * @extends OO.ui.Widget
3424 * @mixins OO.ui.GroupElement
3426 * @constructor
3427 * @param {OO.ui.Toolbar} toolbar
3428 * @param {Object} [config] Configuration options
3429 * @cfg {Array|string} [include=[]] List of tools to include
3430 * @cfg {Array|string} [exclude=[]] List of tools to exclude
3431 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
3432 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
3434 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
3435 // Configuration initialization
3436 config = config || {};
3438 // Parent constructor
3439 OO.ui.ToolGroup.super.call( this, config );
3441 // Mixin constructors
3442 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
3444 // Properties
3445 this.toolbar = toolbar;
3446 this.tools = {};
3447 this.pressed = null;
3448 this.autoDisabled = false;
3449 this.include = config.include || [];
3450 this.exclude = config.exclude || [];
3451 this.promote = config.promote || [];
3452 this.demote = config.demote || [];
3453 this.onCapturedMouseUpHandler = OO.ui.bind( this.onCapturedMouseUp, this );
3455 // Events
3456 this.$element.on( {
3457 'mousedown': OO.ui.bind( this.onMouseDown, this ),
3458 'mouseup': OO.ui.bind( this.onMouseUp, this ),
3459 'mouseover': OO.ui.bind( this.onMouseOver, this ),
3460 'mouseout': OO.ui.bind( this.onMouseOut, this )
3461 } );
3462 this.toolbar.getToolFactory().connect( this, { 'register': 'onToolFactoryRegister' } );
3463 this.aggregate( { 'disable': 'itemDisable' } );
3464 this.connect( this, { 'itemDisable': 'updateDisabled' } );
3466 // Initialization
3467 this.$group.addClass( 'oo-ui-toolGroup-tools' );
3468 this.$element
3469 .addClass( 'oo-ui-toolGroup' )
3470 .append( this.$group );
3471 this.populate();
3474 /* Setup */
3476 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
3477 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
3479 /* Events */
3482 * @event update
3485 /* Static Properties */
3488 * Show labels in tooltips.
3490 * @static
3491 * @inheritable
3492 * @property {boolean}
3494 OO.ui.ToolGroup.static.titleTooltips = false;
3497 * Show acceleration labels in tooltips.
3499 * @static
3500 * @inheritable
3501 * @property {boolean}
3503 OO.ui.ToolGroup.static.accelTooltips = false;
3506 * Automatically disable the toolgroup when all tools are disabled
3508 * @static
3509 * @inheritable
3510 * @property {boolean}
3512 OO.ui.ToolGroup.static.autoDisable = true;
3514 /* Methods */
3517 * @inheritdoc
3519 OO.ui.ToolGroup.prototype.isDisabled = function () {
3520 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
3524 * @inheritdoc
3526 OO.ui.ToolGroup.prototype.updateDisabled = function () {
3527 var i, item, allDisabled = true;
3529 if ( this.constructor.static.autoDisable ) {
3530 for ( i = this.items.length - 1; i >= 0; i-- ) {
3531 item = this.items[i];
3532 if ( !item.isDisabled() ) {
3533 allDisabled = false;
3534 break;
3537 this.autoDisabled = allDisabled;
3539 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
3543 * Handle mouse down events.
3545 * @param {jQuery.Event} e Mouse down event
3547 OO.ui.ToolGroup.prototype.onMouseDown = function ( e ) {
3548 if ( !this.isDisabled() && e.which === 1 ) {
3549 this.pressed = this.getTargetTool( e );
3550 if ( this.pressed ) {
3551 this.pressed.setActive( true );
3552 this.getElementDocument().addEventListener(
3553 'mouseup', this.onCapturedMouseUpHandler, true
3555 return false;
3561 * Handle captured mouse up events.
3563 * @param {Event} e Mouse up event
3565 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
3566 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
3567 // onMouseUp may be called a second time, depending on where the mouse is when the button is
3568 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
3569 this.onMouseUp( e );
3573 * Handle mouse up events.
3575 * @param {jQuery.Event} e Mouse up event
3577 OO.ui.ToolGroup.prototype.onMouseUp = function ( e ) {
3578 var tool = this.getTargetTool( e );
3580 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
3581 this.pressed.onSelect();
3584 this.pressed = null;
3585 return false;
3589 * Handle mouse over events.
3591 * @param {jQuery.Event} e Mouse over event
3593 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
3594 var tool = this.getTargetTool( e );
3596 if ( this.pressed && this.pressed === tool ) {
3597 this.pressed.setActive( true );
3602 * Handle mouse out events.
3604 * @param {jQuery.Event} e Mouse out event
3606 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
3607 var tool = this.getTargetTool( e );
3609 if ( this.pressed && this.pressed === tool ) {
3610 this.pressed.setActive( false );
3615 * Get the closest tool to a jQuery.Event.
3617 * Only tool links are considered, which prevents other elements in the tool such as popups from
3618 * triggering tool group interactions.
3620 * @private
3621 * @param {jQuery.Event} e
3622 * @return {OO.ui.Tool|null} Tool, `null` if none was found
3624 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
3625 var tool,
3626 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
3628 if ( $item.length ) {
3629 tool = $item.parent().data( 'oo-ui-tool' );
3632 return tool && !tool.isDisabled() ? tool : null;
3636 * Handle tool registry register events.
3638 * If a tool is registered after the group is created, we must repopulate the list to account for:
3640 * - a tool being added that may be included
3641 * - a tool already included being overridden
3643 * @param {string} name Symbolic name of tool
3645 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
3646 this.populate();
3650 * Get the toolbar this group is in.
3652 * @return {OO.ui.Toolbar} Toolbar of group
3654 OO.ui.ToolGroup.prototype.getToolbar = function () {
3655 return this.toolbar;
3659 * Add and remove tools based on configuration.
3661 OO.ui.ToolGroup.prototype.populate = function () {
3662 var i, len, name, tool,
3663 toolFactory = this.toolbar.getToolFactory(),
3664 names = {},
3665 add = [],
3666 remove = [],
3667 list = this.toolbar.getToolFactory().getTools(
3668 this.include, this.exclude, this.promote, this.demote
3671 // Build a list of needed tools
3672 for ( i = 0, len = list.length; i < len; i++ ) {
3673 name = list[i];
3674 if (
3675 // Tool exists
3676 toolFactory.lookup( name ) &&
3677 // Tool is available or is already in this group
3678 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
3680 tool = this.tools[name];
3681 if ( !tool ) {
3682 // Auto-initialize tools on first use
3683 this.tools[name] = tool = toolFactory.create( name, this );
3684 tool.updateTitle();
3686 this.toolbar.reserveTool( tool );
3687 add.push( tool );
3688 names[name] = true;
3691 // Remove tools that are no longer needed
3692 for ( name in this.tools ) {
3693 if ( !names[name] ) {
3694 this.tools[name].destroy();
3695 this.toolbar.releaseTool( this.tools[name] );
3696 remove.push( this.tools[name] );
3697 delete this.tools[name];
3700 if ( remove.length ) {
3701 this.removeItems( remove );
3703 // Update emptiness state
3704 if ( add.length ) {
3705 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
3706 } else {
3707 this.$element.addClass( 'oo-ui-toolGroup-empty' );
3709 // Re-add tools (moving existing ones to new locations)
3710 this.addItems( add );
3711 // Disabled state may depend on items
3712 this.updateDisabled();
3716 * Destroy tool group.
3718 OO.ui.ToolGroup.prototype.destroy = function () {
3719 var name;
3721 this.clearItems();
3722 this.toolbar.getToolFactory().disconnect( this );
3723 for ( name in this.tools ) {
3724 this.toolbar.releaseTool( this.tools[name] );
3725 this.tools[name].disconnect( this ).destroy();
3726 delete this.tools[name];
3728 this.$element.remove();
3731 * Factory for tool groups.
3733 * @class
3734 * @extends OO.Factory
3735 * @constructor
3737 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3738 // Parent constructor
3739 OO.Factory.call( this );
3741 var i, l,
3742 defaultClasses = this.constructor.static.getDefaultClasses();
3744 // Register default toolgroups
3745 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3746 this.register( defaultClasses[i] );
3750 /* Setup */
3752 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3754 /* Static Methods */
3757 * Get a default set of classes to be registered on construction
3759 * @return {Function[]} Default classes
3761 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3762 return [
3763 OO.ui.BarToolGroup,
3764 OO.ui.ListToolGroup,
3765 OO.ui.MenuToolGroup
3769 * Layout made of a fieldset and optional legend.
3771 * Just add OO.ui.FieldLayout items.
3773 * @class
3774 * @extends OO.ui.Layout
3775 * @mixins OO.ui.LabeledElement
3776 * @mixins OO.ui.IconedElement
3777 * @mixins OO.ui.GroupElement
3779 * @constructor
3780 * @param {Object} [config] Configuration options
3781 * @cfg {string} [icon] Symbolic icon name
3782 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
3784 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
3785 // Config initialization
3786 config = config || {};
3788 // Parent constructor
3789 OO.ui.FieldsetLayout.super.call( this, config );
3791 // Mixin constructors
3792 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
3793 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
3794 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
3796 // Initialization
3797 this.$element
3798 .addClass( 'oo-ui-fieldsetLayout' )
3799 .prepend( this.$icon, this.$label, this.$group );
3800 if ( $.isArray( config.items ) ) {
3801 this.addItems( config.items );
3805 /* Setup */
3807 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
3808 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconedElement );
3809 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabeledElement );
3810 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
3812 /* Static Properties */
3814 OO.ui.FieldsetLayout.static.tagName = 'div';
3816 * Layout made of a field and optional label.
3818 * @class
3819 * @extends OO.ui.Layout
3820 * @mixins OO.ui.LabeledElement
3822 * Available label alignment modes include:
3823 * - 'left': Label is before the field and aligned away from it, best for when the user will be
3824 * scanning for a specific label in a form with many fields
3825 * - 'right': Label is before the field and aligned toward it, best for forms the user is very
3826 * familiar with and will tab through field checking quickly to verify which field they are in
3827 * - 'top': Label is before the field and above it, best for when the use will need to fill out all
3828 * fields from top to bottom in a form with few fields
3829 * - 'inline': Label is after the field and aligned toward it, best for small boolean fields like
3830 * checkboxes or radio buttons
3832 * @constructor
3833 * @param {OO.ui.Widget} field Field widget
3834 * @param {Object} [config] Configuration options
3835 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
3837 OO.ui.FieldLayout = function OoUiFieldLayout( field, config ) {
3838 // Config initialization
3839 config = $.extend( { 'align': 'left' }, config );
3841 // Parent constructor
3842 OO.ui.FieldLayout.super.call( this, config );
3844 // Mixin constructors
3845 OO.ui.LabeledElement.call( this, this.$( '<label>' ), config );
3847 // Properties
3848 this.$field = this.$( '<div>' );
3849 this.field = field;
3850 this.align = null;
3852 // Events
3853 if ( this.field instanceof OO.ui.InputWidget ) {
3854 this.$label.on( 'click', OO.ui.bind( this.onLabelClick, this ) );
3856 this.field.connect( this, { 'disable': 'onFieldDisable' } );
3858 // Initialization
3859 this.$element.addClass( 'oo-ui-fieldLayout' );
3860 this.$field
3861 .addClass( 'oo-ui-fieldLayout-field' )
3862 .toggleClass( 'oo-ui-fieldLayout-disable', this.field.isDisabled() )
3863 .append( this.field.$element );
3864 this.setAlignment( config.align );
3867 /* Setup */
3869 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
3870 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabeledElement );
3872 /* Methods */
3875 * Handle field disable events.
3877 * @param {boolean} value Field is disabled
3879 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
3880 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
3884 * Handle label mouse click events.
3886 * @param {jQuery.Event} e Mouse click event
3888 OO.ui.FieldLayout.prototype.onLabelClick = function () {
3889 this.field.simulateLabelClick();
3890 return false;
3894 * Get the field.
3896 * @return {OO.ui.Widget} Field widget
3898 OO.ui.FieldLayout.prototype.getField = function () {
3899 return this.field;
3903 * Set the field alignment mode.
3905 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
3906 * @chainable
3908 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
3909 if ( value !== this.align ) {
3910 // Default to 'left'
3911 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
3912 value = 'left';
3914 // Reorder elements
3915 if ( value === 'inline' ) {
3916 this.$element.append( this.$field, this.$label );
3917 } else {
3918 this.$element.append( this.$label, this.$field );
3920 // Set classes
3921 if ( this.align ) {
3922 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
3924 this.align = value;
3925 this.$element.addClass( 'oo-ui-fieldLayout-align-' + this.align );
3928 return this;
3931 * Layout made of proportionally sized columns and rows.
3933 * @class
3934 * @extends OO.ui.Layout
3936 * @constructor
3937 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
3938 * @param {Object} [config] Configuration options
3939 * @cfg {number[]} [widths] Widths of columns as ratios
3940 * @cfg {number[]} [heights] Heights of columns as ratios
3942 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
3943 var i, len, widths;
3945 // Config initialization
3946 config = config || {};
3948 // Parent constructor
3949 OO.ui.GridLayout.super.call( this, config );
3951 // Properties
3952 this.panels = [];
3953 this.widths = [];
3954 this.heights = [];
3956 // Initialization
3957 this.$element.addClass( 'oo-ui-gridLayout' );
3958 for ( i = 0, len = panels.length; i < len; i++ ) {
3959 this.panels.push( panels[i] );
3960 this.$element.append( panels[i].$element );
3962 if ( config.widths || config.heights ) {
3963 this.layout( config.widths || [1], config.heights || [1] );
3964 } else {
3965 // Arrange in columns by default
3966 widths = [];
3967 for ( i = 0, len = this.panels.length; i < len; i++ ) {
3968 widths[i] = 1;
3970 this.layout( widths, [1] );
3974 /* Setup */
3976 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
3978 /* Events */
3981 * @event layout
3985 * @event update
3988 /* Static Properties */
3990 OO.ui.GridLayout.static.tagName = 'div';
3992 /* Methods */
3995 * Set grid dimensions.
3997 * @param {number[]} widths Widths of columns as ratios
3998 * @param {number[]} heights Heights of rows as ratios
3999 * @fires layout
4000 * @throws {Error} If grid is not large enough to fit all panels
4002 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
4003 var x, y,
4004 xd = 0,
4005 yd = 0,
4006 cols = widths.length,
4007 rows = heights.length;
4009 // Verify grid is big enough to fit panels
4010 if ( cols * rows < this.panels.length ) {
4011 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
4014 // Sum up denominators
4015 for ( x = 0; x < cols; x++ ) {
4016 xd += widths[x];
4018 for ( y = 0; y < rows; y++ ) {
4019 yd += heights[y];
4021 // Store factors
4022 this.widths = [];
4023 this.heights = [];
4024 for ( x = 0; x < cols; x++ ) {
4025 this.widths[x] = widths[x] / xd;
4027 for ( y = 0; y < rows; y++ ) {
4028 this.heights[y] = heights[y] / yd;
4030 // Synchronize view
4031 this.update();
4032 this.emit( 'layout' );
4036 * Update panel positions and sizes.
4038 * @fires update
4040 OO.ui.GridLayout.prototype.update = function () {
4041 var x, y, panel,
4042 i = 0,
4043 left = 0,
4044 top = 0,
4045 dimensions,
4046 width = 0,
4047 height = 0,
4048 cols = this.widths.length,
4049 rows = this.heights.length;
4051 for ( y = 0; y < rows; y++ ) {
4052 for ( x = 0; x < cols; x++ ) {
4053 panel = this.panels[i];
4054 width = this.widths[x];
4055 height = this.heights[y];
4056 dimensions = {
4057 'width': Math.round( width * 100 ) + '%',
4058 'height': Math.round( height * 100 ) + '%',
4059 'top': Math.round( top * 100 ) + '%'
4061 // If RTL, reverse:
4062 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
4063 dimensions.right = Math.round( left * 100 ) + '%';
4064 } else {
4065 dimensions.left = Math.round( left * 100 ) + '%';
4067 panel.$element.css( dimensions );
4068 i++;
4069 left += width;
4071 top += height;
4072 left = 0;
4075 this.emit( 'update' );
4079 * Get a panel at a given position.
4081 * The x and y position is affected by the current grid layout.
4083 * @param {number} x Horizontal position
4084 * @param {number} y Vertical position
4085 * @return {OO.ui.PanelLayout} The panel at the given postion
4087 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
4088 return this.panels[( x * this.widths.length ) + y];
4091 * Layout containing a series of pages.
4093 * @class
4094 * @extends OO.ui.Layout
4096 * @constructor
4097 * @param {Object} [config] Configuration options
4098 * @cfg {boolean} [continuous=false] Show all pages, one after another
4099 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
4100 * @cfg {boolean} [outlined=false] Show an outline
4101 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
4102 * @cfg {Object[]} [adders] List of adders for controls, each with name, icon and title properties
4104 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
4105 // Initialize configuration
4106 config = config || {};
4108 // Parent constructor
4109 OO.ui.BookletLayout.super.call( this, config );
4111 // Properties
4112 this.currentPageName = null;
4113 this.pages = {};
4114 this.ignoreFocus = false;
4115 this.stackLayout = new OO.ui.StackLayout( { '$': this.$, 'continuous': !!config.continuous } );
4116 this.autoFocus = config.autoFocus === undefined ? true : !!config.autoFocus;
4117 this.outlineVisible = false;
4118 this.outlined = !!config.outlined;
4119 if ( this.outlined ) {
4120 this.editable = !!config.editable;
4121 this.adders = config.adders || null;
4122 this.outlineControlsWidget = null;
4123 this.outlineWidget = new OO.ui.OutlineWidget( { '$': this.$ } );
4124 this.outlinePanel = new OO.ui.PanelLayout( { '$': this.$, 'scrollable': true } );
4125 this.gridLayout = new OO.ui.GridLayout(
4126 [this.outlinePanel, this.stackLayout], { '$': this.$, 'widths': [1, 2] }
4128 this.outlineVisible = true;
4129 if ( this.editable ) {
4130 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
4131 this.outlineWidget,
4132 { '$': this.$, 'adders': this.adders }
4137 // Events
4138 this.stackLayout.connect( this, { 'set': 'onStackLayoutSet' } );
4139 if ( this.outlined ) {
4140 this.outlineWidget.connect( this, { 'select': 'onOutlineWidgetSelect' } );
4142 if ( this.autoFocus ) {
4143 // Event 'focus' does not bubble, but 'focusin' does
4144 this.stackLayout.onDOMEvent( 'focusin', OO.ui.bind( this.onStackLayoutFocus, this ) );
4147 // Initialization
4148 this.$element.addClass( 'oo-ui-bookletLayout' );
4149 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
4150 if ( this.outlined ) {
4151 this.outlinePanel.$element
4152 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
4153 .append( this.outlineWidget.$element );
4154 if ( this.editable ) {
4155 this.outlinePanel.$element
4156 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
4157 .append( this.outlineControlsWidget.$element );
4159 this.$element.append( this.gridLayout.$element );
4160 } else {
4161 this.$element.append( this.stackLayout.$element );
4165 /* Setup */
4167 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
4169 /* Events */
4172 * @event set
4173 * @param {OO.ui.PageLayout} page Current page
4177 * @event add
4178 * @param {OO.ui.PageLayout[]} page Added pages
4179 * @param {number} index Index pages were added at
4183 * @event remove
4184 * @param {OO.ui.PageLayout[]} pages Removed pages
4187 /* Methods */
4190 * Handle stack layout focus.
4192 * @param {jQuery.Event} e Focusin event
4194 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
4195 var name, $target;
4197 // Find the page that an element was focused within
4198 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
4199 for ( name in this.pages ) {
4200 // Check for page match, exclude current page to find only page changes
4201 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
4202 this.setPage( name );
4203 break;
4209 * Handle stack layout set events.
4211 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
4213 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
4214 if ( page ) {
4215 page.scrollElementIntoView( { 'complete': OO.ui.bind( function () {
4216 if ( this.autoFocus ) {
4217 // Set focus to the first input if nothing on the page is focused yet
4218 if ( !page.$element.find( ':focus' ).length ) {
4219 page.$element.find( ':input:first' ).focus();
4222 }, this ) } );
4227 * Handle outline widget select events.
4229 * @param {OO.ui.OptionWidget|null} item Selected item
4231 OO.ui.BookletLayout.prototype.onOutlineWidgetSelect = function ( item ) {
4232 if ( item ) {
4233 this.setPage( item.getData() );
4238 * Check if booklet has an outline.
4240 * @return {boolean}
4242 OO.ui.BookletLayout.prototype.isOutlined = function () {
4243 return this.outlined;
4247 * Check if booklet has editing controls.
4249 * @return {boolean}
4251 OO.ui.BookletLayout.prototype.isEditable = function () {
4252 return this.editable;
4256 * Check if booklet has a visible outline.
4258 * @return {boolean}
4260 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
4261 return this.outlined && this.outlineVisible;
4265 * Hide or show the outline.
4267 * @param {boolean} [show] Show outline, omit to invert current state
4268 * @chainable
4270 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
4271 if ( this.outlined ) {
4272 show = show === undefined ? !this.outlineVisible : !!show;
4273 this.outlineVisible = show;
4274 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
4277 return this;
4281 * Get the outline widget.
4283 * @param {OO.ui.PageLayout} page Page to be selected
4284 * @return {OO.ui.PageLayout|null} Closest page to another
4286 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
4287 var next, prev, level,
4288 pages = this.stackLayout.getItems(),
4289 index = $.inArray( page, pages );
4291 if ( index !== -1 ) {
4292 next = pages[index + 1];
4293 prev = pages[index - 1];
4294 // Prefer adjacent pages at the same level
4295 if ( this.outlined ) {
4296 level = this.outlineWidget.getItemFromData( page.getName() ).getLevel();
4297 if (
4298 prev &&
4299 level === this.outlineWidget.getItemFromData( prev.getName() ).getLevel()
4301 return prev;
4303 if (
4304 next &&
4305 level === this.outlineWidget.getItemFromData( next.getName() ).getLevel()
4307 return next;
4311 return prev || next || null;
4315 * Get the outline widget.
4317 * @return {OO.ui.OutlineWidget|null} Outline widget, or null if boolet has no outline
4319 OO.ui.BookletLayout.prototype.getOutline = function () {
4320 return this.outlineWidget;
4324 * Get the outline controls widget. If the outline is not editable, null is returned.
4326 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
4328 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
4329 return this.outlineControlsWidget;
4333 * Get a page by name.
4335 * @param {string} name Symbolic name of page
4336 * @return {OO.ui.PageLayout|undefined} Page, if found
4338 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
4339 return this.pages[name];
4343 * Get the current page name.
4345 * @return {string|null} Current page name
4347 OO.ui.BookletLayout.prototype.getPageName = function () {
4348 return this.currentPageName;
4352 * Add a page to the layout.
4354 * When pages are added with the same names as existing pages, the existing pages will be
4355 * automatically removed before the new pages are added.
4357 * @param {OO.ui.PageLayout[]} pages Pages to add
4358 * @param {number} index Index to insert pages after
4359 * @fires add
4360 * @chainable
4362 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
4363 var i, len, name, page, item, currentIndex,
4364 stackLayoutPages = this.stackLayout.getItems(),
4365 remove = [],
4366 items = [];
4368 // Remove pages with same names
4369 for ( i = 0, len = pages.length; i < len; i++ ) {
4370 page = pages[i];
4371 name = page.getName();
4373 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
4374 // Correct the insertion index
4375 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
4376 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
4377 index--;
4379 remove.push( this.pages[name] );
4382 if ( remove.length ) {
4383 this.removePages( remove );
4386 // Add new pages
4387 for ( i = 0, len = pages.length; i < len; i++ ) {
4388 page = pages[i];
4389 name = page.getName();
4390 this.pages[page.getName()] = page;
4391 if ( this.outlined ) {
4392 item = new OO.ui.OutlineItemWidget( name, page, { '$': this.$ } );
4393 page.setOutlineItem( item );
4394 items.push( item );
4398 if ( this.outlined && items.length ) {
4399 this.outlineWidget.addItems( items, index );
4400 this.updateOutlineWidget();
4402 this.stackLayout.addItems( pages, index );
4403 this.emit( 'add', pages, index );
4405 return this;
4409 * Remove a page from the layout.
4411 * @fires remove
4412 * @chainable
4414 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
4415 var i, len, name, page,
4416 items = [];
4418 for ( i = 0, len = pages.length; i < len; i++ ) {
4419 page = pages[i];
4420 name = page.getName();
4421 delete this.pages[name];
4422 if ( this.outlined ) {
4423 items.push( this.outlineWidget.getItemFromData( name ) );
4424 page.setOutlineItem( null );
4427 if ( this.outlined && items.length ) {
4428 this.outlineWidget.removeItems( items );
4429 this.updateOutlineWidget();
4431 this.stackLayout.removeItems( pages );
4432 this.emit( 'remove', pages );
4434 return this;
4438 * Clear all pages from the layout.
4440 * @fires remove
4441 * @chainable
4443 OO.ui.BookletLayout.prototype.clearPages = function () {
4444 var i, len,
4445 pages = this.stackLayout.getItems();
4447 this.pages = {};
4448 this.currentPageName = null;
4449 if ( this.outlined ) {
4450 this.outlineWidget.clearItems();
4451 for ( i = 0, len = pages.length; i < len; i++ ) {
4452 pages[i].setOutlineItem( null );
4455 this.stackLayout.clearItems();
4457 this.emit( 'remove', pages );
4459 return this;
4463 * Set the current page by name.
4465 * @fires set
4466 * @param {string} name Symbolic name of page
4468 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
4469 var selectedItem,
4470 page = this.pages[name];
4472 if ( name !== this.currentPageName ) {
4473 if ( this.outlined ) {
4474 selectedItem = this.outlineWidget.getSelectedItem();
4475 if ( selectedItem && selectedItem.getData() !== name ) {
4476 this.outlineWidget.selectItem( this.outlineWidget.getItemFromData( name ) );
4479 if ( page ) {
4480 if ( this.currentPageName && this.pages[this.currentPageName] ) {
4481 this.pages[this.currentPageName].setActive( false );
4482 // Blur anything focused if the next page doesn't have anything focusable - this
4483 // is not needed if the next page has something focusable because once it is focused
4484 // this blur happens automatically
4485 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
4486 this.pages[this.currentPageName].$element.find( ':focus' ).blur();
4489 this.currentPageName = name;
4490 this.stackLayout.setItem( page );
4491 page.setActive( true );
4492 this.emit( 'set', page );
4498 * Call this after adding or removing items from the OutlineWidget.
4500 * @chainable
4502 OO.ui.BookletLayout.prototype.updateOutlineWidget = function () {
4503 // Auto-select first item when nothing is selected anymore
4504 if ( !this.outlineWidget.getSelectedItem() ) {
4505 this.outlineWidget.selectItem( this.outlineWidget.getFirstSelectableItem() );
4508 return this;
4511 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
4513 * @class
4514 * @extends OO.ui.Layout
4516 * @constructor
4517 * @param {Object} [config] Configuration options
4518 * @cfg {boolean} [scrollable] Allow vertical scrolling
4519 * @cfg {boolean} [padded] Pad the content from the edges
4521 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
4522 // Config initialization
4523 config = config || {};
4525 // Parent constructor
4526 OO.ui.PanelLayout.super.call( this, config );
4528 // Initialization
4529 this.$element.addClass( 'oo-ui-panelLayout' );
4530 if ( config.scrollable ) {
4531 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
4534 if ( config.padded ) {
4535 this.$element.addClass( 'oo-ui-panelLayout-padded' );
4538 // Add directionality class:
4539 this.$element.addClass( 'oo-ui-' + OO.ui.Element.getDir( this.$.context ) );
4542 /* Setup */
4544 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
4546 * Page within an booklet layout.
4548 * @class
4549 * @extends OO.ui.PanelLayout
4551 * @constructor
4552 * @param {string} name Unique symbolic name of page
4553 * @param {Object} [config] Configuration options
4554 * @param {string} [outlineItem] Outline item widget
4556 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
4557 // Configuration initialization
4558 config = $.extend( { 'scrollable': true }, config );
4560 // Parent constructor
4561 OO.ui.PageLayout.super.call( this, config );
4563 // Properties
4564 this.name = name;
4565 this.outlineItem = config.outlineItem || null;
4566 this.active = false;
4568 // Initialization
4569 this.$element.addClass( 'oo-ui-pageLayout' );
4572 /* Setup */
4574 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
4576 /* Events */
4579 * @event active
4580 * @param {boolean} active Page is active
4583 /* Methods */
4586 * Get page name.
4588 * @return {string} Symbolic name of page
4590 OO.ui.PageLayout.prototype.getName = function () {
4591 return this.name;
4595 * Check if page is active.
4597 * @return {boolean} Page is active
4599 OO.ui.PageLayout.prototype.isActive = function () {
4600 return this.active;
4604 * Get outline item.
4606 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
4608 OO.ui.PageLayout.prototype.getOutlineItem = function () {
4609 return this.outlineItem;
4613 * Get outline item.
4615 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
4616 * @chainable
4618 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
4619 this.outlineItem = outlineItem;
4620 return this;
4624 * Set page active state.
4626 * @param {boolean} Page is active
4627 * @fires active
4629 OO.ui.PageLayout.prototype.setActive = function ( active ) {
4630 active = !!active;
4632 if ( active !== this.active ) {
4633 this.active = active;
4634 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
4635 this.emit( 'active', this.active );
4639 * Layout containing a series of mutually exclusive pages.
4641 * @class
4642 * @extends OO.ui.PanelLayout
4643 * @mixins OO.ui.GroupElement
4645 * @constructor
4646 * @param {Object} [config] Configuration options
4647 * @cfg {boolean} [continuous=false] Show all pages, one after another
4648 * @cfg {string} [icon=''] Symbolic icon name
4649 * @cfg {OO.ui.Layout[]} [items] Layouts to add
4651 OO.ui.StackLayout = function OoUiStackLayout( config ) {
4652 // Config initialization
4653 config = $.extend( { 'scrollable': true }, config );
4655 // Parent constructor
4656 OO.ui.StackLayout.super.call( this, config );
4658 // Mixin constructors
4659 OO.ui.GroupElement.call( this, this.$element, config );
4661 // Properties
4662 this.currentItem = null;
4663 this.continuous = !!config.continuous;
4665 // Initialization
4666 this.$element.addClass( 'oo-ui-stackLayout' );
4667 if ( this.continuous ) {
4668 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
4670 if ( $.isArray( config.items ) ) {
4671 this.addItems( config.items );
4675 /* Setup */
4677 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
4678 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
4680 /* Events */
4683 * @event set
4684 * @param {OO.ui.Layout|null} [item] Current item
4687 /* Methods */
4690 * Get the current item.
4692 * @return {OO.ui.Layout|null} [description]
4694 OO.ui.StackLayout.prototype.getCurrentItem = function () {
4695 return this.currentItem;
4699 * Add items.
4701 * Adding an existing item (by value) will move it.
4703 * @param {OO.ui.Layout[]} items Items to add
4704 * @param {number} [index] Index to insert items after
4705 * @chainable
4707 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
4708 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
4710 if ( !this.currentItem && items.length ) {
4711 this.setItem( items[0] );
4714 return this;
4718 * Remove items.
4720 * Items will be detached, not removed, so they can be used later.
4722 * @param {OO.ui.Layout[]} items Items to remove
4723 * @chainable
4725 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
4726 OO.ui.GroupElement.prototype.removeItems.call( this, items );
4727 if ( $.inArray( this.currentItem, items ) !== -1 ) {
4728 this.currentItem = null;
4729 if ( !this.currentItem && this.items.length ) {
4730 this.setItem( this.items[0] );
4734 return this;
4738 * Clear all items.
4740 * Items will be detached, not removed, so they can be used later.
4742 * @chainable
4744 OO.ui.StackLayout.prototype.clearItems = function () {
4745 this.currentItem = null;
4746 OO.ui.GroupElement.prototype.clearItems.call( this );
4748 return this;
4752 * Show item.
4754 * Any currently shown item will be hidden.
4756 * @param {OO.ui.Layout} item Item to show
4757 * @chainable
4759 OO.ui.StackLayout.prototype.setItem = function ( item ) {
4760 if ( item !== this.currentItem ) {
4761 if ( !this.continuous ) {
4762 this.$items.css( 'display', '' );
4764 if ( $.inArray( item, this.items ) !== -1 ) {
4765 if ( !this.continuous ) {
4766 item.$element.css( 'display', 'block' );
4768 } else {
4769 item = null;
4771 this.currentItem = item;
4772 this.emit( 'set', item );
4775 return this;
4778 * Horizontal bar layout of tools as icon buttons.
4780 * @abstract
4781 * @class
4782 * @extends OO.ui.ToolGroup
4784 * @constructor
4785 * @param {OO.ui.Toolbar} toolbar
4786 * @param {Object} [config] Configuration options
4788 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
4789 // Parent constructor
4790 OO.ui.BarToolGroup.super.call( this, toolbar, config );
4792 // Initialization
4793 this.$element.addClass( 'oo-ui-barToolGroup' );
4796 /* Setup */
4798 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
4800 /* Static Properties */
4802 OO.ui.BarToolGroup.static.titleTooltips = true;
4804 OO.ui.BarToolGroup.static.accelTooltips = true;
4806 OO.ui.BarToolGroup.static.name = 'bar';
4808 * Popup list of tools with an icon and optional label.
4810 * @abstract
4811 * @class
4812 * @extends OO.ui.ToolGroup
4813 * @mixins OO.ui.IconedElement
4814 * @mixins OO.ui.IndicatedElement
4815 * @mixins OO.ui.LabeledElement
4816 * @mixins OO.ui.TitledElement
4817 * @mixins OO.ui.ClippableElement
4819 * @constructor
4820 * @param {OO.ui.Toolbar} toolbar
4821 * @param {Object} [config] Configuration options
4823 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
4824 // Configuration initialization
4825 config = config || {};
4827 // Parent constructor
4828 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
4830 // Mixin constructors
4831 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
4832 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
4833 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
4834 OO.ui.TitledElement.call( this, this.$element, config );
4835 OO.ui.ClippableElement.call( this, this.$group, config );
4837 // Properties
4838 this.active = false;
4839 this.dragging = false;
4840 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
4841 this.$handle = this.$( '<span>' );
4843 // Events
4844 this.$handle.on( {
4845 'mousedown': OO.ui.bind( this.onHandleMouseDown, this ),
4846 'mouseup': OO.ui.bind( this.onHandleMouseUp, this )
4847 } );
4849 // Initialization
4850 this.$handle
4851 .addClass( 'oo-ui-popupToolGroup-handle' )
4852 .append( this.$icon, this.$label, this.$indicator );
4853 this.$element
4854 .addClass( 'oo-ui-popupToolGroup' )
4855 .prepend( this.$handle );
4858 /* Setup */
4860 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
4861 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconedElement );
4862 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatedElement );
4863 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabeledElement );
4864 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
4865 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
4867 /* Static Properties */
4869 /* Methods */
4872 * @inheritdoc
4874 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
4875 // Parent method
4876 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
4878 if ( this.isDisabled() && this.isElementAttached() ) {
4879 this.setActive( false );
4884 * Handle focus being lost.
4886 * The event is actually generated from a mouseup, so it is not a normal blur event object.
4888 * @param {jQuery.Event} e Mouse up event
4890 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
4891 // Only deactivate when clicking outside the dropdown element
4892 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
4893 this.setActive( false );
4898 * @inheritdoc
4900 OO.ui.PopupToolGroup.prototype.onMouseUp = function ( e ) {
4901 if ( !this.isDisabled() && e.which === 1 ) {
4902 this.setActive( false );
4904 return OO.ui.ToolGroup.prototype.onMouseUp.call( this, e );
4908 * Handle mouse up events.
4910 * @param {jQuery.Event} e Mouse up event
4912 OO.ui.PopupToolGroup.prototype.onHandleMouseUp = function () {
4913 return false;
4917 * Handle mouse down events.
4919 * @param {jQuery.Event} e Mouse down event
4921 OO.ui.PopupToolGroup.prototype.onHandleMouseDown = function ( e ) {
4922 if ( !this.isDisabled() && e.which === 1 ) {
4923 this.setActive( !this.active );
4925 return false;
4929 * Switch into active mode.
4931 * When active, mouseup events anywhere in the document will trigger deactivation.
4933 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
4934 value = !!value;
4935 if ( this.active !== value ) {
4936 this.active = value;
4937 if ( value ) {
4938 this.setClipping( true );
4939 this.$element.addClass( 'oo-ui-popupToolGroup-active' );
4940 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
4941 } else {
4942 this.setClipping( false );
4943 this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
4944 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
4949 * Drop down list layout of tools as labeled icon buttons.
4951 * @abstract
4952 * @class
4953 * @extends OO.ui.PopupToolGroup
4955 * @constructor
4956 * @param {OO.ui.Toolbar} toolbar
4957 * @param {Object} [config] Configuration options
4959 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
4960 // Parent constructor
4961 OO.ui.ListToolGroup.super.call( this, toolbar, config );
4963 // Initialization
4964 this.$element.addClass( 'oo-ui-listToolGroup' );
4967 /* Setup */
4969 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
4971 /* Static Properties */
4973 OO.ui.ListToolGroup.static.accelTooltips = true;
4975 OO.ui.ListToolGroup.static.name = 'list';
4977 * Drop down menu layout of tools as selectable menu items.
4979 * @abstract
4980 * @class
4981 * @extends OO.ui.PopupToolGroup
4983 * @constructor
4984 * @param {OO.ui.Toolbar} toolbar
4985 * @param {Object} [config] Configuration options
4987 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
4988 // Configuration initialization
4989 config = config || {};
4991 // Parent constructor
4992 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
4994 // Events
4995 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
4997 // Initialization
4998 this.$element.addClass( 'oo-ui-menuToolGroup' );
5001 /* Setup */
5003 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
5005 /* Static Properties */
5007 OO.ui.MenuToolGroup.static.accelTooltips = true;
5009 OO.ui.MenuToolGroup.static.name = 'menu';
5011 /* Methods */
5014 * Handle the toolbar state being updated.
5016 * When the state changes, the title of each active item in the menu will be joined together and
5017 * used as a label for the group. The label will be empty if none of the items are active.
5019 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
5020 var name,
5021 labelTexts = [];
5023 for ( name in this.tools ) {
5024 if ( this.tools[name].isActive() ) {
5025 labelTexts.push( this.tools[name].getTitle() );
5029 this.setLabel( labelTexts.join( ', ' ) || ' ' );
5032 * Tool that shows a popup when selected.
5034 * @abstract
5035 * @class
5036 * @extends OO.ui.Tool
5037 * @mixins OO.ui.PopuppableElement
5039 * @constructor
5040 * @param {OO.ui.Toolbar} toolbar
5041 * @param {Object} [config] Configuration options
5043 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
5044 // Parent constructor
5045 OO.ui.PopupTool.super.call( this, toolbar, config );
5047 // Mixin constructors
5048 OO.ui.PopuppableElement.call( this, config );
5050 // Initialization
5051 this.$element
5052 .addClass( 'oo-ui-popupTool' )
5053 .append( this.popup.$element );
5056 /* Setup */
5058 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
5059 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopuppableElement );
5061 /* Methods */
5064 * Handle the tool being selected.
5066 * @inheritdoc
5068 OO.ui.PopupTool.prototype.onSelect = function () {
5069 if ( !this.isDisabled() ) {
5070 if ( this.popup.isVisible() ) {
5071 this.hidePopup();
5072 } else {
5073 this.showPopup();
5076 this.setActive( false );
5077 return false;
5081 * Handle the toolbar state being updated.
5083 * @inheritdoc
5085 OO.ui.PopupTool.prototype.onUpdateState = function () {
5086 this.setActive( false );
5089 * Group widget.
5091 * Mixin for OO.ui.Widget subclasses.
5093 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
5095 * @abstract
5096 * @class
5097 * @extends OO.ui.GroupElement
5099 * @constructor
5100 * @param {jQuery} $group Container node, assigned to #$group
5101 * @param {Object} [config] Configuration options
5103 OO.ui.GroupWidget = function OoUiGroupWidget( $element, config ) {
5104 // Parent constructor
5105 OO.ui.GroupWidget.super.call( this, $element, config );
5108 /* Setup */
5110 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
5112 /* Methods */
5115 * Set the disabled state of the widget.
5117 * This will also update the disabled state of child widgets.
5119 * @param {boolean} disabled Disable widget
5120 * @chainable
5122 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
5123 var i, len;
5125 // Parent method
5126 // Note this is calling OO.ui.Widget; we're assuming the class this is mixed into
5127 // is a subclass of OO.ui.Widget.
5128 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5130 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
5131 if ( this.items ) {
5132 for ( i = 0, len = this.items.length; i < len; i++ ) {
5133 this.items[i].updateDisabled();
5137 return this;
5140 * Item widget.
5142 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
5144 * @abstract
5145 * @class
5147 * @constructor
5149 OO.ui.ItemWidget = function OoUiItemWidget() {
5153 /* Methods */
5156 * Check if widget is disabled.
5158 * Checks parent if present, making disabled state inheritable.
5160 * @return {boolean} Widget is disabled
5162 OO.ui.ItemWidget.prototype.isDisabled = function () {
5163 return this.disabled ||
5164 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5168 * Set group element is in.
5170 * @param {OO.ui.GroupElement|null} group Group element, null if none
5171 * @chainable
5173 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
5174 // Parent method
5175 OO.ui.Element.prototype.setElementGroup.call( this, group );
5177 // Initialize item disabled states
5178 this.updateDisabled();
5180 return this;
5183 * Icon widget.
5185 * @class
5186 * @extends OO.ui.Widget
5187 * @mixins OO.ui.IconedElement
5188 * @mixins OO.ui.TitledElement
5190 * @constructor
5191 * @param {Object} [config] Configuration options
5193 OO.ui.IconWidget = function OoUiIconWidget( config ) {
5194 // Config intialization
5195 config = config || {};
5197 // Parent constructor
5198 OO.ui.IconWidget.super.call( this, config );
5200 // Mixin constructors
5201 OO.ui.IconedElement.call( this, this.$element, config );
5202 OO.ui.TitledElement.call( this, this.$element, config );
5204 // Initialization
5205 this.$element.addClass( 'oo-ui-iconWidget' );
5208 /* Setup */
5210 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
5211 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconedElement );
5212 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
5214 /* Static Properties */
5216 OO.ui.IconWidget.static.tagName = 'span';
5218 * Indicator widget.
5220 * @class
5221 * @extends OO.ui.Widget
5222 * @mixins OO.ui.IndicatedElement
5223 * @mixins OO.ui.TitledElement
5225 * @constructor
5226 * @param {Object} [config] Configuration options
5228 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
5229 // Config intialization
5230 config = config || {};
5232 // Parent constructor
5233 OO.ui.IndicatorWidget.super.call( this, config );
5235 // Mixin constructors
5236 OO.ui.IndicatedElement.call( this, this.$element, config );
5237 OO.ui.TitledElement.call( this, this.$element, config );
5239 // Initialization
5240 this.$element.addClass( 'oo-ui-indicatorWidget' );
5243 /* Setup */
5245 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
5246 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatedElement );
5247 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
5249 /* Static Properties */
5251 OO.ui.IndicatorWidget.static.tagName = 'span';
5253 * Container for multiple related buttons.
5255 * Use together with OO.ui.ButtonWidget.
5257 * @class
5258 * @extends OO.ui.Widget
5259 * @mixins OO.ui.GroupElement
5261 * @constructor
5262 * @param {Object} [config] Configuration options
5263 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
5265 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
5266 // Parent constructor
5267 OO.ui.ButtonGroupWidget.super.call( this, config );
5269 // Mixin constructors
5270 OO.ui.GroupElement.call( this, this.$element, config );
5272 // Initialization
5273 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
5274 if ( $.isArray( config.items ) ) {
5275 this.addItems( config.items );
5279 /* Setup */
5281 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
5282 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
5284 * Button widget.
5286 * @abstract
5287 * @class
5288 * @extends OO.ui.Widget
5289 * @mixins OO.ui.ButtonedElement
5290 * @mixins OO.ui.IconedElement
5291 * @mixins OO.ui.IndicatedElement
5292 * @mixins OO.ui.LabeledElement
5293 * @mixins OO.ui.TitledElement
5294 * @mixins OO.ui.FlaggableElement
5296 * @constructor
5297 * @param {Object} [config] Configuration options
5298 * @cfg {string} [title=''] Title text
5299 * @cfg {string} [href] Hyperlink to visit when clicked
5300 * @cfg {string} [target] Target to open hyperlink in
5302 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
5303 // Configuration initialization
5304 config = $.extend( { 'target': '_blank' }, config );
5306 // Parent constructor
5307 OO.ui.ButtonWidget.super.call( this, config );
5309 // Mixin constructors
5310 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
5311 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
5312 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
5313 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
5314 OO.ui.TitledElement.call( this, this.$button, config );
5315 OO.ui.FlaggableElement.call( this, config );
5317 // Properties
5318 this.isHyperlink = typeof config.href === 'string';
5320 // Events
5321 this.$button.on( {
5322 'click': OO.ui.bind( this.onClick, this ),
5323 'keypress': OO.ui.bind( this.onKeyPress, this )
5324 } );
5326 // Initialization
5327 this.$button
5328 .append( this.$icon, this.$label, this.$indicator )
5329 .attr( { 'href': config.href, 'target': config.target } );
5330 this.$element
5331 .addClass( 'oo-ui-buttonWidget' )
5332 .append( this.$button );
5335 /* Setup */
5337 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
5338 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonedElement );
5339 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconedElement );
5340 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatedElement );
5341 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabeledElement );
5342 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
5343 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggableElement );
5345 /* Events */
5348 * @event click
5351 /* Methods */
5354 * Handles mouse click events.
5356 * @param {jQuery.Event} e Mouse click event
5357 * @fires click
5359 OO.ui.ButtonWidget.prototype.onClick = function () {
5360 if ( !this.isDisabled() ) {
5361 this.emit( 'click' );
5362 if ( this.isHyperlink ) {
5363 return true;
5366 return false;
5370 * Handles keypress events.
5372 * @param {jQuery.Event} e Keypress event
5373 * @fires click
5375 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
5376 if ( !this.isDisabled() && e.which === OO.ui.Keys.SPACE ) {
5377 if ( this.isHyperlink ) {
5378 this.onClick();
5379 return true;
5382 return false;
5385 * Input widget.
5387 * @abstract
5388 * @class
5389 * @extends OO.ui.Widget
5391 * @constructor
5392 * @param {Object} [config] Configuration options
5393 * @cfg {string} [name=''] HTML input name
5394 * @cfg {string} [value=''] Input value
5395 * @cfg {boolean} [readOnly=false] Prevent changes
5396 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
5398 OO.ui.InputWidget = function OoUiInputWidget( config ) {
5399 // Config intialization
5400 config = $.extend( { 'readOnly': false }, config );
5402 // Parent constructor
5403 OO.ui.InputWidget.super.call( this, config );
5405 // Properties
5406 this.$input = this.getInputElement( config );
5407 this.value = '';
5408 this.readOnly = false;
5409 this.inputFilter = config.inputFilter;
5411 // Events
5412 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
5414 // Initialization
5415 this.$input
5416 .attr( 'name', config.name )
5417 .prop( 'disabled', this.isDisabled() );
5418 this.setReadOnly( config.readOnly );
5419 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
5420 this.setValue( config.value );
5423 /* Setup */
5425 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
5427 /* Events */
5430 * @event change
5431 * @param value
5434 /* Methods */
5437 * Get input element.
5439 * @param {Object} [config] Configuration options
5440 * @return {jQuery} Input element
5442 OO.ui.InputWidget.prototype.getInputElement = function () {
5443 return this.$( '<input>' );
5447 * Handle potentially value-changing events.
5449 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
5451 OO.ui.InputWidget.prototype.onEdit = function () {
5452 if ( !this.isDisabled() ) {
5453 // Allow the stack to clear so the value will be updated
5454 setTimeout( OO.ui.bind( function () {
5455 this.setValue( this.$input.val() );
5456 }, this ) );
5461 * Get the value of the input.
5463 * @return {string} Input value
5465 OO.ui.InputWidget.prototype.getValue = function () {
5466 return this.value;
5470 * Sets the direction of the current input, either RTL or LTR
5472 * @param {boolean} isRTL
5474 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
5475 if ( isRTL ) {
5476 this.$input.removeClass( 'oo-ui-ltr' );
5477 this.$input.addClass( 'oo-ui-rtl' );
5478 } else {
5479 this.$input.removeClass( 'oo-ui-rtl' );
5480 this.$input.addClass( 'oo-ui-ltr' );
5485 * Set the value of the input.
5487 * @param {string} value New value
5488 * @fires change
5489 * @chainable
5491 OO.ui.InputWidget.prototype.setValue = function ( value ) {
5492 value = this.sanitizeValue( value );
5493 if ( this.value !== value ) {
5494 this.value = value;
5495 this.emit( 'change', this.value );
5497 // Update the DOM if it has changed. Note that with sanitizeValue, it
5498 // is possible for the DOM value to change without this.value changing.
5499 if ( this.$input.val() !== this.value ) {
5500 this.$input.val( this.value );
5502 return this;
5506 * Sanitize incoming value.
5508 * Ensures value is a string, and converts undefined and null to empty strings.
5510 * @param {string} value Original value
5511 * @return {string} Sanitized value
5513 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
5514 if ( value === undefined || value === null ) {
5515 return '';
5516 } else if ( this.inputFilter ) {
5517 return this.inputFilter( String( value ) );
5518 } else {
5519 return String( value );
5524 * Simulate the behavior of clicking on a label bound to this input.
5526 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
5527 if ( !this.isDisabled() ) {
5528 if ( this.$input.is( ':checkbox,:radio' ) ) {
5529 this.$input.click();
5530 } else if ( this.$input.is( ':input' ) ) {
5531 this.$input.focus();
5537 * Check if the widget is read-only.
5539 * @return {boolean}
5541 OO.ui.InputWidget.prototype.isReadOnly = function () {
5542 return this.readOnly;
5546 * Set the read-only state of the widget.
5548 * This should probably change the widgets's appearance and prevent it from being used.
5550 * @param {boolean} state Make input read-only
5551 * @chainable
5553 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
5554 this.readOnly = !!state;
5555 this.$input.prop( 'readOnly', this.readOnly );
5556 return this;
5560 * @inheritdoc
5562 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
5563 OO.ui.Widget.prototype.setDisabled.call( this, state );
5564 if ( this.$input ) {
5565 this.$input.prop( 'disabled', this.isDisabled() );
5567 return this;
5571 * Focus the input.
5573 * @chainable
5575 OO.ui.InputWidget.prototype.focus = function () {
5576 this.$input.focus();
5577 return this;
5580 * Checkbox widget.
5582 * @class
5583 * @extends OO.ui.InputWidget
5585 * @constructor
5586 * @param {Object} [config] Configuration options
5588 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
5589 // Parent constructor
5590 OO.ui.CheckboxInputWidget.super.call( this, config );
5592 // Initialization
5593 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
5596 /* Setup */
5598 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
5600 /* Events */
5602 /* Methods */
5605 * Get input element.
5607 * @return {jQuery} Input element
5609 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
5610 return this.$( '<input type="checkbox" />' );
5614 * Get checked state of the checkbox
5616 * @return {boolean} If the checkbox is checked
5618 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
5619 return this.value;
5623 * Set value
5625 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
5626 value = !!value;
5627 if ( this.value !== value ) {
5628 this.value = value;
5629 this.$input.prop( 'checked', this.value );
5630 this.emit( 'change', this.value );
5635 * @inheritdoc
5637 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
5638 if ( !this.isDisabled() ) {
5639 // Allow the stack to clear so the value will be updated
5640 setTimeout( OO.ui.bind( function () {
5641 this.setValue( this.$input.prop( 'checked' ) );
5642 }, this ) );
5646 * Label widget.
5648 * @class
5649 * @extends OO.ui.Widget
5650 * @mixins OO.ui.LabeledElement
5652 * @constructor
5653 * @param {Object} [config] Configuration options
5655 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
5656 // Config intialization
5657 config = config || {};
5659 // Parent constructor
5660 OO.ui.LabelWidget.super.call( this, config );
5662 // Mixin constructors
5663 OO.ui.LabeledElement.call( this, this.$element, config );
5665 // Properties
5666 this.input = config.input;
5668 // Events
5669 if ( this.input instanceof OO.ui.InputWidget ) {
5670 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
5673 // Initialization
5674 this.$element.addClass( 'oo-ui-labelWidget' );
5677 /* Setup */
5679 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
5680 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabeledElement );
5682 /* Static Properties */
5684 OO.ui.LabelWidget.static.tagName = 'label';
5686 /* Methods */
5689 * Handles label mouse click events.
5691 * @param {jQuery.Event} e Mouse click event
5693 OO.ui.LabelWidget.prototype.onClick = function () {
5694 this.input.simulateLabelClick();
5695 return false;
5698 * Lookup input widget.
5700 * Mixin that adds a menu showing suggested values to a text input. Subclasses must handle `select`
5701 * and `choose` events on #lookupMenu to make use of selections.
5703 * @class
5704 * @abstract
5706 * @constructor
5707 * @param {OO.ui.TextInputWidget} input Input widget
5708 * @param {Object} [config] Configuration options
5709 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
5711 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
5712 // Config intialization
5713 config = config || {};
5715 // Properties
5716 this.lookupInput = input;
5717 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
5718 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
5719 '$': OO.ui.Element.getJQuery( this.$overlay ),
5720 'input': this.lookupInput,
5721 '$container': config.$container
5722 } );
5723 this.lookupCache = {};
5724 this.lookupQuery = null;
5725 this.lookupRequest = null;
5726 this.populating = false;
5728 // Events
5729 this.$overlay.append( this.lookupMenu.$element );
5731 this.lookupInput.$input.on( {
5732 'focus': OO.ui.bind( this.onLookupInputFocus, this ),
5733 'blur': OO.ui.bind( this.onLookupInputBlur, this ),
5734 'mousedown': OO.ui.bind( this.onLookupInputMouseDown, this )
5735 } );
5736 this.lookupInput.connect( this, { 'change': 'onLookupInputChange' } );
5738 // Initialization
5739 this.$element.addClass( 'oo-ui-lookupWidget' );
5740 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
5743 /* Methods */
5746 * Handle input focus event.
5748 * @param {jQuery.Event} e Input focus event
5750 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
5751 this.openLookupMenu();
5755 * Handle input blur event.
5757 * @param {jQuery.Event} e Input blur event
5759 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
5760 this.lookupMenu.hide();
5764 * Handle input mouse down event.
5766 * @param {jQuery.Event} e Input mouse down event
5768 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
5769 this.openLookupMenu();
5773 * Handle input change event.
5775 * @param {string} value New input value
5777 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
5778 this.openLookupMenu();
5782 * Get lookup menu.
5784 * @return {OO.ui.TextInputMenuWidget}
5786 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
5787 return this.lookupMenu;
5791 * Open the menu.
5793 * @chainable
5795 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
5796 var value = this.lookupInput.getValue();
5798 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
5799 this.populateLookupMenu();
5800 if ( !this.lookupMenu.isVisible() ) {
5801 this.lookupMenu.show();
5803 } else {
5804 this.lookupMenu.clearItems();
5805 this.lookupMenu.hide();
5808 return this;
5812 * Populate lookup menu with current information.
5814 * @chainable
5816 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
5817 if ( !this.populating ) {
5818 this.populating = true;
5819 this.getLookupMenuItems()
5820 .done( OO.ui.bind( function ( items ) {
5821 this.lookupMenu.clearItems();
5822 if ( items.length ) {
5823 this.lookupMenu.show();
5824 this.lookupMenu.addItems( items );
5825 this.initializeLookupMenuSelection();
5826 this.openLookupMenu();
5827 } else {
5828 this.lookupMenu.hide();
5830 this.populating = false;
5831 }, this ) )
5832 .fail( OO.ui.bind( function () {
5833 this.lookupMenu.clearItems();
5834 this.populating = false;
5835 }, this ) );
5838 return this;
5842 * Set selection in the lookup menu with current information.
5844 * @chainable
5846 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
5847 if ( !this.lookupMenu.getSelectedItem() ) {
5848 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5850 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5854 * Get lookup menu items for the current query.
5856 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
5857 * of the done event
5859 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
5860 var value = this.lookupInput.getValue(),
5861 deferred = $.Deferred();
5863 if ( value && value !== this.lookupQuery ) {
5864 // Abort current request if query has changed
5865 if ( this.lookupRequest ) {
5866 this.lookupRequest.abort();
5867 this.lookupQuery = null;
5868 this.lookupRequest = null;
5870 if ( value in this.lookupCache ) {
5871 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
5872 } else {
5873 this.lookupQuery = value;
5874 this.lookupRequest = this.getLookupRequest()
5875 .always( OO.ui.bind( function () {
5876 this.lookupQuery = null;
5877 this.lookupRequest = null;
5878 }, this ) )
5879 .done( OO.ui.bind( function ( data ) {
5880 this.lookupCache[value] = this.getLookupCacheItemFromData( data );
5881 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
5882 }, this ) )
5883 .fail( function () {
5884 deferred.reject();
5885 } );
5886 this.pushPending();
5887 this.lookupRequest.always( OO.ui.bind( function () {
5888 this.popPending();
5889 }, this ) );
5892 return deferred.promise();
5896 * Get a new request object of the current lookup query value.
5898 * @abstract
5899 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
5901 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
5902 // Stub, implemented in subclass
5903 return null;
5907 * Handle successful lookup request.
5909 * Overriding methods should call #populateLookupMenu when results are available and cache results
5910 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
5912 * @abstract
5913 * @param {Mixed} data Response from server
5915 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
5916 // Stub, implemented in subclass
5920 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
5922 * @abstract
5923 * @param {Mixed} data Cached result data, usually an array
5924 * @return {OO.ui.MenuItemWidget[]} Menu items
5926 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
5927 // Stub, implemented in subclass
5928 return [];
5931 * Option widget.
5933 * Use with OO.ui.SelectWidget.
5935 * @abstract
5936 * @class
5937 * @extends OO.ui.Widget
5938 * @mixins OO.ui.IconedElement
5939 * @mixins OO.ui.LabeledElement
5940 * @mixins OO.ui.IndicatedElement
5941 * @mixins OO.ui.FlaggableElement
5943 * @constructor
5944 * @param {Mixed} data Option data
5945 * @param {Object} [config] Configuration options
5946 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
5948 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
5949 // Config intialization
5950 config = config || {};
5952 // Parent constructor
5953 OO.ui.OptionWidget.super.call( this, config );
5955 // Mixin constructors
5956 OO.ui.ItemWidget.call( this );
5957 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
5958 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
5959 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
5960 OO.ui.FlaggableElement.call( this, config );
5962 // Properties
5963 this.data = data;
5964 this.selected = false;
5965 this.highlighted = false;
5966 this.pressed = false;
5968 // Initialization
5969 this.$element
5970 .data( 'oo-ui-optionWidget', this )
5971 .attr( 'rel', config.rel )
5972 .addClass( 'oo-ui-optionWidget' )
5973 .append( this.$label );
5974 this.$element
5975 .prepend( this.$icon )
5976 .append( this.$indicator );
5979 /* Setup */
5981 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
5982 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
5983 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconedElement );
5984 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabeledElement );
5985 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatedElement );
5986 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggableElement );
5988 /* Static Properties */
5990 OO.ui.OptionWidget.static.tagName = 'li';
5992 OO.ui.OptionWidget.static.selectable = true;
5994 OO.ui.OptionWidget.static.highlightable = true;
5996 OO.ui.OptionWidget.static.pressable = true;
5998 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6000 /* Methods */
6003 * Check if option can be selected.
6005 * @return {boolean} Item is selectable
6007 OO.ui.OptionWidget.prototype.isSelectable = function () {
6008 return this.constructor.static.selectable && !this.isDisabled();
6012 * Check if option can be highlighted.
6014 * @return {boolean} Item is highlightable
6016 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6017 return this.constructor.static.highlightable && !this.isDisabled();
6021 * Check if option can be pressed.
6023 * @return {boolean} Item is pressable
6025 OO.ui.OptionWidget.prototype.isPressable = function () {
6026 return this.constructor.static.pressable && !this.isDisabled();
6030 * Check if option is selected.
6032 * @return {boolean} Item is selected
6034 OO.ui.OptionWidget.prototype.isSelected = function () {
6035 return this.selected;
6039 * Check if option is highlighted.
6041 * @return {boolean} Item is highlighted
6043 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6044 return this.highlighted;
6048 * Check if option is pressed.
6050 * @return {boolean} Item is pressed
6052 OO.ui.OptionWidget.prototype.isPressed = function () {
6053 return this.pressed;
6057 * Set selected state.
6059 * @param {boolean} [state=false] Select option
6060 * @chainable
6062 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6063 if ( !this.isDisabled() && this.constructor.static.selectable ) {
6064 this.selected = !!state;
6065 if ( this.selected ) {
6066 this.$element.addClass( 'oo-ui-optionWidget-selected' );
6067 if ( this.constructor.static.scrollIntoViewOnSelect ) {
6068 this.scrollElementIntoView();
6070 } else {
6071 this.$element.removeClass( 'oo-ui-optionWidget-selected' );
6074 return this;
6078 * Set highlighted state.
6080 * @param {boolean} [state=false] Highlight option
6081 * @chainable
6083 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6084 if ( !this.isDisabled() && this.constructor.static.highlightable ) {
6085 this.highlighted = !!state;
6086 if ( this.highlighted ) {
6087 this.$element.addClass( 'oo-ui-optionWidget-highlighted' );
6088 } else {
6089 this.$element.removeClass( 'oo-ui-optionWidget-highlighted' );
6092 return this;
6096 * Set pressed state.
6098 * @param {boolean} [state=false] Press option
6099 * @chainable
6101 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6102 if ( !this.isDisabled() && this.constructor.static.pressable ) {
6103 this.pressed = !!state;
6104 if ( this.pressed ) {
6105 this.$element.addClass( 'oo-ui-optionWidget-pressed' );
6106 } else {
6107 this.$element.removeClass( 'oo-ui-optionWidget-pressed' );
6110 return this;
6114 * Make the option's highlight flash.
6116 * While flashing, the visual style of the pressed state is removed if present.
6118 * @return {jQuery.Promise} Promise resolved when flashing is done
6120 OO.ui.OptionWidget.prototype.flash = function () {
6121 var $this = this.$element,
6122 deferred = $.Deferred();
6124 if ( !this.isDisabled() && this.constructor.static.pressable ) {
6125 $this.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
6126 setTimeout( OO.ui.bind( function () {
6127 // Restore original classes
6128 $this
6129 .toggleClass( 'oo-ui-optionWidget-highlighted', this.highlighted )
6130 .toggleClass( 'oo-ui-optionWidget-pressed', this.pressed );
6131 setTimeout( function () {
6132 deferred.resolve();
6133 }, 100 );
6134 }, this ), 100 );
6137 return deferred.promise();
6141 * Get option data.
6143 * @return {Mixed} Option data
6145 OO.ui.OptionWidget.prototype.getData = function () {
6146 return this.data;
6149 * Selection of options.
6151 * Use together with OO.ui.OptionWidget.
6153 * @abstract
6154 * @class
6155 * @extends OO.ui.Widget
6156 * @mixins OO.ui.GroupElement
6158 * @constructor
6159 * @param {Object} [config] Configuration options
6160 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
6162 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6163 // Config intialization
6164 config = config || {};
6166 // Parent constructor
6167 OO.ui.SelectWidget.super.call( this, config );
6169 // Mixin constructors
6170 OO.ui.GroupWidget.call( this, this.$element, config );
6172 // Properties
6173 this.pressed = false;
6174 this.selecting = null;
6175 this.hashes = {};
6177 // Events
6178 this.$element.on( {
6179 'mousedown': OO.ui.bind( this.onMouseDown, this ),
6180 'mouseup': OO.ui.bind( this.onMouseUp, this ),
6181 'mousemove': OO.ui.bind( this.onMouseMove, this ),
6182 'mouseover': OO.ui.bind( this.onMouseOver, this ),
6183 'mouseleave': OO.ui.bind( this.onMouseLeave, this )
6184 } );
6186 // Initialization
6187 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
6188 if ( $.isArray( config.items ) ) {
6189 this.addItems( config.items );
6193 /* Setup */
6195 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6197 // Need to mixin base class as well
6198 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
6199 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
6201 /* Events */
6204 * @event highlight
6205 * @param {OO.ui.OptionWidget|null} item Highlighted item
6209 * @event press
6210 * @param {OO.ui.OptionWidget|null} item Pressed item
6214 * @event select
6215 * @param {OO.ui.OptionWidget|null} item Selected item
6219 * @event choose
6220 * @param {OO.ui.OptionWidget|null} item Chosen item
6224 * @event add
6225 * @param {OO.ui.OptionWidget[]} items Added items
6226 * @param {number} index Index items were added at
6230 * @event remove
6231 * @param {OO.ui.OptionWidget[]} items Removed items
6234 /* Static Properties */
6236 OO.ui.SelectWidget.static.tagName = 'ul';
6238 /* Methods */
6241 * Handle mouse down events.
6243 * @private
6244 * @param {jQuery.Event} e Mouse down event
6246 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6247 var item;
6249 if ( !this.isDisabled() && e.which === 1 ) {
6250 this.togglePressed( true );
6251 item = this.getTargetItem( e );
6252 if ( item && item.isSelectable() ) {
6253 this.pressItem( item );
6254 this.selecting = item;
6255 this.$( this.$.context ).one( 'mouseup', OO.ui.bind( this.onMouseUp, this ) );
6258 return false;
6262 * Handle mouse up events.
6264 * @private
6265 * @param {jQuery.Event} e Mouse up event
6267 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6268 var item;
6270 this.togglePressed( false );
6271 if ( !this.selecting ) {
6272 item = this.getTargetItem( e );
6273 if ( item && item.isSelectable() ) {
6274 this.selecting = item;
6277 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
6278 this.pressItem( null );
6279 this.chooseItem( this.selecting );
6280 this.selecting = null;
6283 return false;
6287 * Handle mouse move events.
6289 * @private
6290 * @param {jQuery.Event} e Mouse move event
6292 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6293 var item;
6295 if ( !this.isDisabled() && this.pressed ) {
6296 item = this.getTargetItem( e );
6297 if ( item && item !== this.selecting && item.isSelectable() ) {
6298 this.pressItem( item );
6299 this.selecting = item;
6302 return false;
6306 * Handle mouse over events.
6308 * @private
6309 * @param {jQuery.Event} e Mouse over event
6311 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6312 var item;
6314 if ( !this.isDisabled() ) {
6315 item = this.getTargetItem( e );
6316 this.highlightItem( item && item.isHighlightable() ? item : null );
6318 return false;
6322 * Handle mouse leave events.
6324 * @private
6325 * @param {jQuery.Event} e Mouse over event
6327 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6328 if ( !this.isDisabled() ) {
6329 this.highlightItem( null );
6331 return false;
6335 * Get the closest item to a jQuery.Event.
6337 * @private
6338 * @param {jQuery.Event} e
6339 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6341 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
6342 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
6343 if ( $item.length ) {
6344 return $item.data( 'oo-ui-optionWidget' );
6346 return null;
6350 * Get selected item.
6352 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6354 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
6355 var i, len;
6357 for ( i = 0, len = this.items.length; i < len; i++ ) {
6358 if ( this.items[i].isSelected() ) {
6359 return this.items[i];
6362 return null;
6366 * Get highlighted item.
6368 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6370 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
6371 var i, len;
6373 for ( i = 0, len = this.items.length; i < len; i++ ) {
6374 if ( this.items[i].isHighlighted() ) {
6375 return this.items[i];
6378 return null;
6382 * Get an existing item with equivilant data.
6384 * @param {Object} data Item data to search for
6385 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
6387 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
6388 var hash = OO.getHash( data );
6390 if ( hash in this.hashes ) {
6391 return this.hashes[hash];
6394 return null;
6398 * Toggle pressed state.
6400 * @param {boolean} pressed An option is being pressed
6402 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6403 if ( pressed === undefined ) {
6404 pressed = !this.pressed;
6406 if ( pressed !== this.pressed ) {
6407 this.$element.toggleClass( 'oo-ui-selectWidget-pressed', pressed );
6408 this.$element.toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6409 this.pressed = pressed;
6414 * Highlight an item.
6416 * Highlighting is mutually exclusive.
6418 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
6419 * @fires highlight
6420 * @chainable
6422 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6423 var i, len, highlighted,
6424 changed = false;
6426 for ( i = 0, len = this.items.length; i < len; i++ ) {
6427 highlighted = this.items[i] === item;
6428 if ( this.items[i].isHighlighted() !== highlighted ) {
6429 this.items[i].setHighlighted( highlighted );
6430 changed = true;
6433 if ( changed ) {
6434 this.emit( 'highlight', item );
6437 return this;
6441 * Select an item.
6443 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6444 * @fires select
6445 * @chainable
6447 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6448 var i, len, selected,
6449 changed = false;
6451 for ( i = 0, len = this.items.length; i < len; i++ ) {
6452 selected = this.items[i] === item;
6453 if ( this.items[i].isSelected() !== selected ) {
6454 this.items[i].setSelected( selected );
6455 changed = true;
6458 if ( changed ) {
6459 this.emit( 'select', item );
6462 return this;
6466 * Press an item.
6468 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6469 * @fires press
6470 * @chainable
6472 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6473 var i, len, pressed,
6474 changed = false;
6476 for ( i = 0, len = this.items.length; i < len; i++ ) {
6477 pressed = this.items[i] === item;
6478 if ( this.items[i].isPressed() !== pressed ) {
6479 this.items[i].setPressed( pressed );
6480 changed = true;
6483 if ( changed ) {
6484 this.emit( 'press', item );
6487 return this;
6491 * Choose an item.
6493 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
6494 * an item is selected using the keyboard or mouse.
6496 * @param {OO.ui.OptionWidget} item Item to choose
6497 * @fires choose
6498 * @chainable
6500 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6501 this.selectItem( item );
6502 this.emit( 'choose', item );
6504 return this;
6508 * Get an item relative to another one.
6510 * @param {OO.ui.OptionWidget} item Item to start at
6511 * @param {number} direction Direction to move in
6512 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
6514 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
6515 var inc = direction > 0 ? 1 : -1,
6516 len = this.items.length,
6517 index = item instanceof OO.ui.OptionWidget ?
6518 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
6519 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
6520 i = inc > 0 ?
6521 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
6522 Math.max( index, -1 ) :
6523 // Default to n-1 instead of -1, if nothing is selected let's start at the end
6524 Math.min( index, len );
6526 while ( true ) {
6527 i = ( i + inc + len ) % len;
6528 item = this.items[i];
6529 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6530 return item;
6532 // Stop iterating when we've looped all the way around
6533 if ( i === stopAt ) {
6534 break;
6537 return null;
6541 * Get the next selectable item.
6543 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
6545 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
6546 var i, len, item;
6548 for ( i = 0, len = this.items.length; i < len; i++ ) {
6549 item = this.items[i];
6550 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6551 return item;
6555 return null;
6559 * Add items.
6561 * When items are added with the same values as existing items, the existing items will be
6562 * automatically removed before the new items are added.
6564 * @param {OO.ui.OptionWidget[]} items Items to add
6565 * @param {number} [index] Index to insert items after
6566 * @fires add
6567 * @chainable
6569 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6570 var i, len, item, hash,
6571 remove = [];
6573 for ( i = 0, len = items.length; i < len; i++ ) {
6574 item = items[i];
6575 hash = OO.getHash( item.getData() );
6576 if ( hash in this.hashes ) {
6577 // Remove item with same value
6578 remove.push( this.hashes[hash] );
6580 this.hashes[hash] = item;
6582 if ( remove.length ) {
6583 this.removeItems( remove );
6586 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
6588 // Always provide an index, even if it was omitted
6589 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
6591 return this;
6595 * Remove items.
6597 * Items will be detached, not removed, so they can be used later.
6599 * @param {OO.ui.OptionWidget[]} items Items to remove
6600 * @fires remove
6601 * @chainable
6603 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
6604 var i, len, item, hash;
6606 for ( i = 0, len = items.length; i < len; i++ ) {
6607 item = items[i];
6608 hash = OO.getHash( item.getData() );
6609 if ( hash in this.hashes ) {
6610 // Remove existing item
6611 delete this.hashes[hash];
6613 if ( item.isSelected() ) {
6614 this.selectItem( null );
6617 OO.ui.GroupElement.prototype.removeItems.call( this, items );
6619 this.emit( 'remove', items );
6621 return this;
6625 * Clear all items.
6627 * Items will be detached, not removed, so they can be used later.
6629 * @fires remove
6630 * @chainable
6632 OO.ui.SelectWidget.prototype.clearItems = function () {
6633 var items = this.items.slice();
6635 // Clear all items
6636 this.hashes = {};
6637 OO.ui.GroupElement.prototype.clearItems.call( this );
6638 this.selectItem( null );
6640 this.emit( 'remove', items );
6642 return this;
6645 * Menu item widget.
6647 * Use with OO.ui.MenuWidget.
6649 * @class
6650 * @extends OO.ui.OptionWidget
6652 * @constructor
6653 * @param {Mixed} data Item data
6654 * @param {Object} [config] Configuration options
6656 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
6657 // Configuration initialization
6658 config = $.extend( { 'icon': 'check' }, config );
6660 // Parent constructor
6661 OO.ui.MenuItemWidget.super.call( this, data, config );
6663 // Initialization
6664 this.$element.addClass( 'oo-ui-menuItemWidget' );
6667 /* Setup */
6669 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.OptionWidget );
6671 * Menu widget.
6673 * Use together with OO.ui.MenuItemWidget.
6675 * @class
6676 * @extends OO.ui.SelectWidget
6677 * @mixins OO.ui.ClippableElement
6679 * @constructor
6680 * @param {Object} [config] Configuration options
6681 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
6683 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
6684 // Config intialization
6685 config = config || {};
6687 // Parent constructor
6688 OO.ui.MenuWidget.super.call( this, config );
6690 // Mixin constructors
6691 OO.ui.ClippableElement.call( this, this.$group, config );
6693 // Properties
6694 this.newItems = null;
6695 this.$input = config.input ? config.input.$input : null;
6696 this.$previousFocus = null;
6697 this.isolated = !config.input;
6698 this.visible = false;
6699 this.flashing = false;
6700 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
6702 // Initialization
6703 this.$element.hide().addClass( 'oo-ui-menuWidget' );
6706 /* Setup */
6708 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
6709 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
6711 /* Methods */
6714 * Handles key down events.
6716 * @param {jQuery.Event} e Key down event
6718 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
6719 var nextItem,
6720 handled = false,
6721 highlightItem = this.getHighlightedItem();
6723 if ( !this.isDisabled() && this.visible ) {
6724 if ( !highlightItem ) {
6725 highlightItem = this.getSelectedItem();
6727 switch ( e.keyCode ) {
6728 case OO.ui.Keys.ENTER:
6729 this.chooseItem( highlightItem );
6730 handled = true;
6731 break;
6732 case OO.ui.Keys.UP:
6733 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
6734 handled = true;
6735 break;
6736 case OO.ui.Keys.DOWN:
6737 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
6738 handled = true;
6739 break;
6740 case OO.ui.Keys.ESCAPE:
6741 if ( highlightItem ) {
6742 highlightItem.setHighlighted( false );
6744 this.hide();
6745 handled = true;
6746 break;
6749 if ( nextItem ) {
6750 this.highlightItem( nextItem );
6751 nextItem.scrollElementIntoView();
6754 if ( handled ) {
6755 e.preventDefault();
6756 e.stopPropagation();
6757 return false;
6763 * Check if the menu is visible.
6765 * @return {boolean} Menu is visible
6767 OO.ui.MenuWidget.prototype.isVisible = function () {
6768 return this.visible;
6772 * Bind key down listener.
6774 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
6775 if ( this.$input ) {
6776 this.$input.on( 'keydown', this.onKeyDownHandler );
6777 } else {
6778 // Capture menu navigation keys
6779 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
6784 * Unbind key down listener.
6786 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
6787 if ( this.$input ) {
6788 this.$input.off( 'keydown' );
6789 } else {
6790 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
6795 * Choose an item.
6797 * This will close the menu when done, unlike selectItem which only changes selection.
6799 * @param {OO.ui.OptionWidget} item Item to choose
6800 * @chainable
6802 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
6803 // Parent method
6804 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
6806 if ( item && !this.flashing ) {
6807 this.flashing = true;
6808 item.flash().done( OO.ui.bind( function () {
6809 this.hide();
6810 this.flashing = false;
6811 }, this ) );
6812 } else {
6813 this.hide();
6816 return this;
6820 * Add items.
6822 * Adding an existing item (by value) will move it.
6824 * @param {OO.ui.MenuItemWidget[]} items Items to add
6825 * @param {number} [index] Index to insert items after
6826 * @chainable
6828 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
6829 var i, len, item;
6831 // Parent method
6832 OO.ui.SelectWidget.prototype.addItems.call( this, items, index );
6834 // Auto-initialize
6835 if ( !this.newItems ) {
6836 this.newItems = [];
6839 for ( i = 0, len = items.length; i < len; i++ ) {
6840 item = items[i];
6841 if ( this.visible ) {
6842 // Defer fitting label until
6843 item.fitLabel();
6844 } else {
6845 this.newItems.push( item );
6849 return this;
6853 * Show the menu.
6855 * @chainable
6857 OO.ui.MenuWidget.prototype.show = function () {
6858 var i, len;
6860 if ( this.items.length ) {
6861 this.$element.show();
6862 this.visible = true;
6863 this.bindKeyDownListener();
6865 // Change focus to enable keyboard navigation
6866 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
6867 this.$previousFocus = this.$( ':focus' );
6868 this.$input.focus();
6870 if ( this.newItems && this.newItems.length ) {
6871 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
6872 this.newItems[i].fitLabel();
6874 this.newItems = null;
6877 this.setClipping( true );
6880 return this;
6884 * Hide the menu.
6886 * @chainable
6888 OO.ui.MenuWidget.prototype.hide = function () {
6889 this.$element.hide();
6890 this.visible = false;
6891 this.unbindKeyDownListener();
6893 if ( this.isolated && this.$previousFocus ) {
6894 this.$previousFocus.focus();
6895 this.$previousFocus = null;
6898 this.setClipping( false );
6900 return this;
6903 * Inline menu of options.
6905 * Use with OO.ui.MenuOptionWidget.
6907 * @class
6908 * @extends OO.ui.Widget
6909 * @mixins OO.ui.IconedElement
6910 * @mixins OO.ui.IndicatedElement
6911 * @mixins OO.ui.LabeledElement
6912 * @mixins OO.ui.TitledElement
6914 * @constructor
6915 * @param {Object} [config] Configuration options
6916 * @cfg {Object} [menu] Configuration options to pass to menu widget
6918 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
6919 // Configuration initialization
6920 config = $.extend( { 'indicator': 'down' }, config );
6922 // Parent constructor
6923 OO.ui.InlineMenuWidget.super.call( this, config );
6925 // Mixin constructors
6926 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
6927 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
6928 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
6929 OO.ui.TitledElement.call( this, this.$label, config );
6931 // Properties
6932 this.menu = new OO.ui.MenuWidget( $.extend( { '$': this.$ }, config.menu ) );
6933 this.$handle = this.$( '<span>' );
6935 // Events
6936 this.$element.on( { 'click': OO.ui.bind( this.onClick, this ) } );
6937 this.menu.connect( this, { 'select': 'onMenuSelect' } );
6939 // Initialization
6940 this.$handle
6941 .addClass( 'oo-ui-inlineMenuWidget-handle' )
6942 .append( this.$icon, this.$label, this.$indicator );
6943 this.$element
6944 .addClass( 'oo-ui-inlineMenuWidget' )
6945 .append( this.$handle, this.menu.$element );
6948 /* Setup */
6950 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
6951 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconedElement );
6952 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatedElement );
6953 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabeledElement );
6954 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
6956 /* Methods */
6959 * Get the menu.
6961 * @return {OO.ui.MenuWidget} Menu of widget
6963 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
6964 return this.menu;
6968 * Handles menu select events.
6970 * @param {OO.ui.MenuItemWidget} item Selected menu item
6972 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
6973 var selectedLabel;
6975 if ( !item ) {
6976 return;
6979 selectedLabel = item.getLabel();
6981 // If the label is a DOM element, clone it, because setLabel will append() it
6982 if ( selectedLabel instanceof jQuery ) {
6983 selectedLabel = selectedLabel.clone();
6986 this.setLabel( selectedLabel );
6990 * Handles mouse click events.
6992 * @param {jQuery.Event} e Mouse click event
6994 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
6995 // Skip clicks within the menu
6996 if ( $.contains( this.menu.$element[0], e.target ) ) {
6997 return;
7000 if ( !this.isDisabled() ) {
7001 if ( this.menu.isVisible() ) {
7002 this.menu.hide();
7003 } else {
7004 this.menu.show();
7007 return false;
7010 * Menu section item widget.
7012 * Use with OO.ui.MenuWidget.
7014 * @class
7015 * @extends OO.ui.OptionWidget
7017 * @constructor
7018 * @param {Mixed} data Item data
7019 * @param {Object} [config] Configuration options
7021 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
7022 // Parent constructor
7023 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
7025 // Initialization
7026 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
7029 /* Setup */
7031 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.OptionWidget );
7033 /* Static Properties */
7035 OO.ui.MenuSectionItemWidget.static.selectable = false;
7037 OO.ui.MenuSectionItemWidget.static.highlightable = false;
7039 * Create an OO.ui.OutlineWidget object.
7041 * Use with OO.ui.OutlineItemWidget.
7043 * @class
7044 * @extends OO.ui.SelectWidget
7046 * @constructor
7047 * @param {Object} [config] Configuration options
7049 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
7050 // Config intialization
7051 config = config || {};
7053 // Parent constructor
7054 OO.ui.OutlineWidget.super.call( this, config );
7056 // Initialization
7057 this.$element.addClass( 'oo-ui-outlineWidget' );
7060 /* Setup */
7062 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
7064 * Creates an OO.ui.OutlineControlsWidget object.
7066 * Use together with OO.ui.OutlineWidget.js
7068 * @class
7070 * @constructor
7071 * @param {OO.ui.OutlineWidget} outline Outline to control
7072 * @param {Object} [config] Configuration options
7074 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7075 // Configuration initialization
7076 config = $.extend( { 'icon': 'add-item' }, config );
7078 // Parent constructor
7079 OO.ui.OutlineControlsWidget.super.call( this, config );
7081 // Mixin constructors
7082 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
7083 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
7085 // Properties
7086 this.outline = outline;
7087 this.$movers = this.$( '<div>' );
7088 this.upButton = new OO.ui.ButtonWidget( {
7089 '$': this.$,
7090 'frameless': true,
7091 'icon': 'collapse',
7092 'title': OO.ui.msg( 'ooui-outline-control-move-up' )
7093 } );
7094 this.downButton = new OO.ui.ButtonWidget( {
7095 '$': this.$,
7096 'frameless': true,
7097 'icon': 'expand',
7098 'title': OO.ui.msg( 'ooui-outline-control-move-down' )
7099 } );
7100 this.removeButton = new OO.ui.ButtonWidget( {
7101 '$': this.$,
7102 'frameless': true,
7103 'icon': 'remove',
7104 'title': OO.ui.msg( 'ooui-outline-control-remove' )
7105 } );
7107 // Events
7108 outline.connect( this, {
7109 'select': 'onOutlineChange',
7110 'add': 'onOutlineChange',
7111 'remove': 'onOutlineChange'
7112 } );
7113 this.upButton.connect( this, { 'click': ['emit', 'move', -1] } );
7114 this.downButton.connect( this, { 'click': ['emit', 'move', 1] } );
7115 this.removeButton.connect( this, { 'click': ['emit', 'remove'] } );
7117 // Initialization
7118 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7119 this.$group.addClass( 'oo-ui-outlineControlsWidget-adders' );
7120 this.$movers
7121 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7122 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7123 this.$element.append( this.$icon, this.$group, this.$movers );
7126 /* Setup */
7128 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7129 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7130 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconedElement );
7132 /* Events */
7135 * @event move
7136 * @param {number} places Number of places to move
7140 * @event remove
7143 /* Methods */
7146 * Handle outline change events.
7148 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7149 var i, len, firstMovable, lastMovable,
7150 items = this.outline.getItems(),
7151 selectedItem = this.outline.getSelectedItem(),
7152 movable = selectedItem && selectedItem.isMovable(),
7153 removable = selectedItem && selectedItem.isRemovable();
7155 if ( movable ) {
7156 i = -1;
7157 len = items.length;
7158 while ( ++i < len ) {
7159 if ( items[i].isMovable() ) {
7160 firstMovable = items[i];
7161 break;
7164 i = len;
7165 while ( i-- ) {
7166 if ( items[i].isMovable() ) {
7167 lastMovable = items[i];
7168 break;
7172 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7173 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7174 this.removeButton.setDisabled( !removable );
7177 * Creates an OO.ui.OutlineItemWidget object.
7179 * Use with OO.ui.OutlineWidget.
7181 * @class
7182 * @extends OO.ui.OptionWidget
7184 * @constructor
7185 * @param {Mixed} data Item data
7186 * @param {Object} [config] Configuration options
7187 * @cfg {number} [level] Indentation level
7188 * @cfg {boolean} [movable] Allow modification from outline controls
7190 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
7191 // Config intialization
7192 config = config || {};
7194 // Parent constructor
7195 OO.ui.OutlineItemWidget.super.call( this, data, config );
7197 // Properties
7198 this.level = 0;
7199 this.movable = !!config.movable;
7200 this.removable = !!config.removable;
7202 // Initialization
7203 this.$element.addClass( 'oo-ui-outlineItemWidget' );
7204 this.setLevel( config.level );
7207 /* Setup */
7209 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.OptionWidget );
7211 /* Static Properties */
7213 OO.ui.OutlineItemWidget.static.highlightable = false;
7215 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
7217 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
7219 OO.ui.OutlineItemWidget.static.levels = 3;
7221 /* Methods */
7224 * Check if item is movable.
7226 * Movablilty is used by outline controls.
7228 * @return {boolean} Item is movable
7230 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
7231 return this.movable;
7235 * Check if item is removable.
7237 * Removablilty is used by outline controls.
7239 * @return {boolean} Item is removable
7241 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
7242 return this.removable;
7246 * Get indentation level.
7248 * @return {number} Indentation level
7250 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
7251 return this.level;
7255 * Set movability.
7257 * Movablilty is used by outline controls.
7259 * @param {boolean} movable Item is movable
7260 * @chainable
7262 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
7263 this.movable = !!movable;
7264 return this;
7268 * Set removability.
7270 * Removablilty is used by outline controls.
7272 * @param {boolean} movable Item is removable
7273 * @chainable
7275 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
7276 this.removable = !!removable;
7277 return this;
7281 * Set indentation level.
7283 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
7284 * @chainable
7286 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
7287 var levels = this.constructor.static.levels,
7288 levelClass = this.constructor.static.levelClass,
7289 i = levels;
7291 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
7292 while ( i-- ) {
7293 if ( this.level === i ) {
7294 this.$element.addClass( levelClass + i );
7295 } else {
7296 this.$element.removeClass( levelClass + i );
7300 return this;
7303 * Option widget that looks like a button.
7305 * Use together with OO.ui.ButtonSelectWidget.
7307 * @class
7308 * @extends OO.ui.OptionWidget
7309 * @mixins OO.ui.ButtonedElement
7310 * @mixins OO.ui.FlaggableElement
7312 * @constructor
7313 * @param {Mixed} data Option data
7314 * @param {Object} [config] Configuration options
7316 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
7317 // Parent constructor
7318 OO.ui.ButtonOptionWidget.super.call( this, data, config );
7320 // Mixin constructors
7321 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
7322 OO.ui.FlaggableElement.call( this, config );
7324 // Initialization
7325 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
7326 this.$button.append( this.$element.contents() );
7327 this.$element.append( this.$button );
7330 /* Setup */
7332 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
7333 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonedElement );
7334 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.FlaggableElement );
7336 /* Methods */
7339 * @inheritdoc
7341 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
7342 OO.ui.OptionWidget.prototype.setSelected.call( this, state );
7344 this.setActive( state );
7346 return this;
7349 * Select widget containing button options.
7351 * Use together with OO.ui.ButtonOptionWidget.
7353 * @class
7354 * @extends OO.ui.SelectWidget
7356 * @constructor
7357 * @param {Object} [config] Configuration options
7359 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
7360 // Parent constructor
7361 OO.ui.ButtonSelectWidget.super.call( this, config );
7363 // Initialization
7364 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
7367 /* Setup */
7369 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
7371 * Container for content that is overlaid and positioned absolutely.
7373 * @class
7374 * @extends OO.ui.Widget
7375 * @mixins OO.ui.LabeledElement
7377 * @constructor
7378 * @param {Object} [config] Configuration options
7379 * @cfg {boolean} [tail=true] Show tail pointing to origin of popup
7380 * @cfg {string} [align='center'] Alignment of popup to origin
7381 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
7382 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
7383 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
7384 * @cfg {boolean} [head] Show label and close button at the top
7386 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
7387 // Config intialization
7388 config = config || {};
7390 // Parent constructor
7391 OO.ui.PopupWidget.super.call( this, config );
7393 // Mixin constructors
7394 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
7395 OO.ui.ClippableElement.call( this, this.$( '<div>' ), config );
7397 // Properties
7398 this.visible = false;
7399 this.$popup = this.$( '<div>' );
7400 this.$head = this.$( '<div>' );
7401 this.$body = this.$clippable;
7402 this.$tail = this.$( '<div>' );
7403 this.$container = config.$container || this.$( 'body' );
7404 this.autoClose = !!config.autoClose;
7405 this.$autoCloseIgnore = config.$autoCloseIgnore;
7406 this.transitionTimeout = null;
7407 this.tail = false;
7408 this.align = config.align || 'center';
7409 this.closeButton = new OO.ui.ButtonWidget( { '$': this.$, 'frameless': true, 'icon': 'close' } );
7410 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
7412 // Events
7413 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
7415 // Initialization
7416 this.useTail( config.tail !== undefined ? !!config.tail : true );
7417 this.$body.addClass( 'oo-ui-popupWidget-body' );
7418 this.$tail.addClass( 'oo-ui-popupWidget-tail' );
7419 this.$head
7420 .addClass( 'oo-ui-popupWidget-head' )
7421 .append( this.$label, this.closeButton.$element );
7422 if ( !config.head ) {
7423 this.$head.hide();
7425 this.$popup
7426 .addClass( 'oo-ui-popupWidget-popup' )
7427 .append( this.$head, this.$body );
7428 this.$element.hide()
7429 .addClass( 'oo-ui-popupWidget' )
7430 .append( this.$popup, this.$tail );
7433 /* Setup */
7435 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
7436 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabeledElement );
7437 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
7439 /* Events */
7442 * @event hide
7446 * @event show
7449 /* Methods */
7452 * Handles mouse down events.
7454 * @param {jQuery.Event} e Mouse down event
7456 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
7457 if (
7458 this.visible &&
7459 !$.contains( this.$element[0], e.target ) &&
7460 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
7462 this.hide();
7467 * Bind mouse down listener.
7469 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
7470 // Capture clicks outside popup
7471 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
7475 * Handles close button click events.
7477 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
7478 if ( this.visible ) {
7479 this.hide();
7484 * Unbind mouse down listener.
7486 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
7487 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
7491 * Check if the popup is visible.
7493 * @return {boolean} Popup is visible
7495 OO.ui.PopupWidget.prototype.isVisible = function () {
7496 return this.visible;
7500 * Set whether to show a tail.
7502 * @return {boolean} Make tail visible
7504 OO.ui.PopupWidget.prototype.useTail = function ( value ) {
7505 value = !!value;
7506 if ( this.tail !== value ) {
7507 this.tail = value;
7508 if ( value ) {
7509 this.$element.addClass( 'oo-ui-popupWidget-tailed' );
7510 } else {
7511 this.$element.removeClass( 'oo-ui-popupWidget-tailed' );
7517 * Check if showing a tail.
7519 * @return {boolean} tail is visible
7521 OO.ui.PopupWidget.prototype.hasTail = function () {
7522 return this.tail;
7526 * Show the context.
7528 * @fires show
7529 * @chainable
7531 OO.ui.PopupWidget.prototype.show = function () {
7532 if ( !this.visible ) {
7533 this.setClipping( true );
7534 this.$element.show();
7535 this.visible = true;
7536 this.emit( 'show' );
7537 if ( this.autoClose ) {
7538 this.bindMouseDownListener();
7541 return this;
7545 * Hide the context.
7547 * @fires hide
7548 * @chainable
7550 OO.ui.PopupWidget.prototype.hide = function () {
7551 if ( this.visible ) {
7552 this.setClipping( false );
7553 this.$element.hide();
7554 this.visible = false;
7555 this.emit( 'hide' );
7556 if ( this.autoClose ) {
7557 this.unbindMouseDownListener();
7560 return this;
7564 * Updates the position and size.
7566 * @param {number} width Width
7567 * @param {number} height Height
7568 * @param {boolean} [transition=false] Use a smooth transition
7569 * @chainable
7571 OO.ui.PopupWidget.prototype.display = function ( width, height, transition ) {
7572 var padding = 10,
7573 originOffset = Math.round( this.$element.offset().left ),
7574 containerLeft = Math.round( this.$container.offset().left ),
7575 containerWidth = this.$container.innerWidth(),
7576 containerRight = containerLeft + containerWidth,
7577 popupOffset = width * ( { 'left': 0, 'center': -0.5, 'right': -1 } )[this.align],
7578 popupLeft = popupOffset - padding,
7579 popupRight = popupOffset + padding + width + padding,
7580 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
7581 overlapRight = containerRight - ( originOffset + popupRight );
7583 // Prevent transition from being interrupted
7584 clearTimeout( this.transitionTimeout );
7585 if ( transition ) {
7586 // Enable transition
7587 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
7590 if ( overlapRight < 0 ) {
7591 popupOffset += overlapRight;
7592 } else if ( overlapLeft < 0 ) {
7593 popupOffset -= overlapLeft;
7596 // Position body relative to anchor and resize
7597 this.$popup.css( {
7598 'left': popupOffset,
7599 'width': width,
7600 'height': height === undefined ? 'auto' : height
7601 } );
7603 if ( transition ) {
7604 // Prevent transitioning after transition is complete
7605 this.transitionTimeout = setTimeout( OO.ui.bind( function () {
7606 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7607 }, this ), 200 );
7608 } else {
7609 // Prevent transitioning immediately
7610 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7613 return this;
7616 * Button that shows and hides a popup.
7618 * @class
7619 * @extends OO.ui.ButtonWidget
7620 * @mixins OO.ui.PopuppableElement
7622 * @constructor
7623 * @param {Object} [config] Configuration options
7625 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
7626 // Parent constructor
7627 OO.ui.PopupButtonWidget.super.call( this, config );
7629 // Mixin constructors
7630 OO.ui.PopuppableElement.call( this, config );
7632 // Initialization
7633 this.$element
7634 .addClass( 'oo-ui-popupButtonWidget' )
7635 .append( this.popup.$element );
7638 /* Setup */
7640 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
7641 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopuppableElement );
7643 /* Methods */
7646 * Handles mouse click events.
7648 * @param {jQuery.Event} e Mouse click event
7650 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
7651 // Skip clicks within the popup
7652 if ( $.contains( this.popup.$element[0], e.target ) ) {
7653 return;
7656 if ( !this.isDisabled() ) {
7657 if ( this.popup.isVisible() ) {
7658 this.hidePopup();
7659 } else {
7660 this.showPopup();
7662 OO.ui.ButtonWidget.prototype.onClick.call( this );
7664 return false;
7667 * Search widget.
7669 * Combines query and results selection widgets.
7671 * @class
7672 * @extends OO.ui.Widget
7674 * @constructor
7675 * @param {Object} [config] Configuration options
7676 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
7677 * @cfg {string} [value] Initial query value
7679 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
7680 // Configuration intialization
7681 config = config || {};
7683 // Parent constructor
7684 OO.ui.SearchWidget.super.call( this, config );
7686 // Properties
7687 this.query = new OO.ui.TextInputWidget( {
7688 '$': this.$,
7689 'icon': 'search',
7690 'placeholder': config.placeholder,
7691 'value': config.value
7692 } );
7693 this.results = new OO.ui.SelectWidget( { '$': this.$ } );
7694 this.$query = this.$( '<div>' );
7695 this.$results = this.$( '<div>' );
7697 // Events
7698 this.query.connect( this, {
7699 'change': 'onQueryChange',
7700 'enter': 'onQueryEnter'
7701 } );
7702 this.results.connect( this, {
7703 'highlight': 'onResultsHighlight',
7704 'select': 'onResultsSelect'
7705 } );
7706 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
7708 // Initialization
7709 this.$query
7710 .addClass( 'oo-ui-searchWidget-query' )
7711 .append( this.query.$element );
7712 this.$results
7713 .addClass( 'oo-ui-searchWidget-results' )
7714 .append( this.results.$element );
7715 this.$element
7716 .addClass( 'oo-ui-searchWidget' )
7717 .append( this.$results, this.$query );
7720 /* Setup */
7722 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
7724 /* Events */
7727 * @event highlight
7728 * @param {Object|null} item Item data or null if no item is highlighted
7732 * @event select
7733 * @param {Object|null} item Item data or null if no item is selected
7736 /* Methods */
7739 * Handle query key down events.
7741 * @param {jQuery.Event} e Key down event
7743 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
7744 var highlightedItem, nextItem,
7745 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
7747 if ( dir ) {
7748 highlightedItem = this.results.getHighlightedItem();
7749 if ( !highlightedItem ) {
7750 highlightedItem = this.results.getSelectedItem();
7752 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
7753 this.results.highlightItem( nextItem );
7754 nextItem.scrollElementIntoView();
7759 * Handle select widget select events.
7761 * Clears existing results. Subclasses should repopulate items according to new query.
7763 * @param {string} value New value
7765 OO.ui.SearchWidget.prototype.onQueryChange = function () {
7766 // Reset
7767 this.results.clearItems();
7771 * Handle select widget enter key events.
7773 * Selects highlighted item.
7775 * @param {string} value New value
7777 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
7778 // Reset
7779 this.results.selectItem( this.results.getHighlightedItem() );
7783 * Handle select widget highlight events.
7785 * @param {OO.ui.OptionWidget} item Highlighted item
7786 * @fires highlight
7788 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
7789 this.emit( 'highlight', item ? item.getData() : null );
7793 * Handle select widget select events.
7795 * @param {OO.ui.OptionWidget} item Selected item
7796 * @fires select
7798 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
7799 this.emit( 'select', item ? item.getData() : null );
7803 * Get the query input.
7805 * @return {OO.ui.TextInputWidget} Query input
7807 OO.ui.SearchWidget.prototype.getQuery = function () {
7808 return this.query;
7812 * Get the results list.
7814 * @return {OO.ui.SelectWidget} Select list
7816 OO.ui.SearchWidget.prototype.getResults = function () {
7817 return this.results;
7820 * Text input widget.
7822 * @class
7823 * @extends OO.ui.InputWidget
7825 * @constructor
7826 * @param {Object} [config] Configuration options
7827 * @cfg {string} [placeholder] Placeholder text
7828 * @cfg {string} [icon] Symbolic name of icon
7829 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7830 * @cfg {boolean} [autosize=false] Automatically resize to fit content
7831 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
7833 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
7834 config = $.extend( { 'maxRows': 10 }, config );
7836 // Parent constructor
7837 OO.ui.TextInputWidget.super.call( this, config );
7839 // Properties
7840 this.pending = 0;
7841 this.multiline = !!config.multiline;
7842 this.autosize = !!config.autosize;
7843 this.maxRows = config.maxRows;
7845 // Events
7846 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
7847 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
7849 // Initialization
7850 this.$element.addClass( 'oo-ui-textInputWidget' );
7851 if ( config.icon ) {
7852 this.$element.addClass( 'oo-ui-textInputWidget-decorated' );
7853 this.$element.append(
7854 this.$( '<span>' )
7855 .addClass( 'oo-ui-textInputWidget-icon oo-ui-icon-' + config.icon )
7856 .mousedown( OO.ui.bind( function () {
7857 this.$input.focus();
7858 return false;
7859 }, this ) )
7862 if ( config.placeholder ) {
7863 this.$input.attr( 'placeholder', config.placeholder );
7867 /* Setup */
7869 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
7871 /* Events */
7874 * User presses enter inside the text box.
7876 * Not called if input is multiline.
7878 * @event enter
7881 /* Methods */
7884 * Handle key press events.
7886 * @param {jQuery.Event} e Key press event
7887 * @fires enter If enter key is pressed and input is not multiline
7889 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
7890 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
7891 this.emit( 'enter' );
7896 * Handle element attach events.
7898 * @param {jQuery.Event} e Element attach event
7900 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
7901 this.adjustSize();
7905 * @inheritdoc
7907 OO.ui.TextInputWidget.prototype.onEdit = function () {
7908 this.adjustSize();
7910 // Parent method
7911 return OO.ui.InputWidget.prototype.onEdit.call( this );
7915 * Automatically adjust the size of the text input.
7917 * This only affects multi-line inputs that are auto-sized.
7919 * @chainable
7921 OO.ui.TextInputWidget.prototype.adjustSize = function () {
7922 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
7924 if ( this.multiline && this.autosize ) {
7925 $clone = this.$input.clone()
7926 .val( this.$input.val() )
7927 .css( { 'height': 0 } )
7928 .insertAfter( this.$input );
7929 // Set inline height property to 0 to measure scroll height
7930 scrollHeight = $clone[0].scrollHeight;
7931 // Remove inline height property to measure natural heights
7932 $clone.css( 'height', '' );
7933 innerHeight = $clone.innerHeight();
7934 outerHeight = $clone.outerHeight();
7935 // Measure max rows height
7936 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
7937 maxInnerHeight = $clone.innerHeight();
7938 $clone.removeAttr( 'rows' ).css( 'height', '' );
7939 $clone.remove();
7940 idealHeight = Math.min( maxInnerHeight, scrollHeight );
7941 // Only apply inline height when expansion beyond natural height is needed
7942 this.$input.css(
7943 'height',
7944 // Use the difference between the inner and outer height as a buffer
7945 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
7948 return this;
7952 * Get input element.
7954 * @param {Object} [config] Configuration options
7955 * @return {jQuery} Input element
7957 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
7958 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
7961 /* Methods */
7964 * Check if input supports multiple lines.
7966 * @return {boolean}
7968 OO.ui.TextInputWidget.prototype.isMultiline = function () {
7969 return !!this.multiline;
7973 * Check if input automatically adjusts its size.
7975 * @return {boolean}
7977 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
7978 return !!this.autosize;
7982 * Check if input is pending.
7984 * @return {boolean}
7986 OO.ui.TextInputWidget.prototype.isPending = function () {
7987 return !!this.pending;
7991 * Increase the pending stack.
7993 * @chainable
7995 OO.ui.TextInputWidget.prototype.pushPending = function () {
7996 if ( this.pending === 0 ) {
7997 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
7998 this.$input.addClass( 'oo-ui-texture-pending' );
8000 this.pending++;
8002 return this;
8006 * Reduce the pending stack.
8008 * Clamped at zero.
8010 * @chainable
8012 OO.ui.TextInputWidget.prototype.popPending = function () {
8013 if ( this.pending === 1 ) {
8014 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
8015 this.$input.removeClass( 'oo-ui-texture-pending' );
8017 this.pending = Math.max( 0, this.pending - 1 );
8019 return this;
8023 * Select the contents of the input.
8025 * @chainable
8027 OO.ui.TextInputWidget.prototype.select = function () {
8028 this.$input.select();
8029 return this;
8032 * Menu for a text input widget.
8034 * @class
8035 * @extends OO.ui.MenuWidget
8037 * @constructor
8038 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
8039 * @param {Object} [config] Configuration options
8040 * @cfg {jQuery} [$container=input.$element] Element to render menu under
8042 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
8043 // Parent constructor
8044 OO.ui.TextInputMenuWidget.super.call( this, config );
8046 // Properties
8047 this.input = input;
8048 this.$container = config.$container || this.input.$element;
8049 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
8051 // Initialization
8052 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
8055 /* Setup */
8057 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
8059 /* Methods */
8062 * Handle window resize event.
8064 * @param {jQuery.Event} e Window resize event
8066 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
8067 this.position();
8071 * Show the menu.
8073 * @chainable
8075 OO.ui.TextInputMenuWidget.prototype.show = function () {
8076 // Parent method
8077 OO.ui.MenuWidget.prototype.show.call( this );
8079 this.position();
8080 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8081 return this;
8085 * Hide the menu.
8087 * @chainable
8089 OO.ui.TextInputMenuWidget.prototype.hide = function () {
8090 // Parent method
8091 OO.ui.MenuWidget.prototype.hide.call( this );
8093 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8094 return this;
8098 * Position the menu.
8100 * @chainable
8102 OO.ui.TextInputMenuWidget.prototype.position = function () {
8103 var frameOffset,
8104 $container = this.$container,
8105 dimensions = $container.offset();
8107 // Position under input
8108 dimensions.top += $container.height();
8110 // Compensate for frame position if in a differnt frame
8111 if ( this.input.$.frame && this.input.$.context !== this.$element[0].ownerDocument ) {
8112 frameOffset = OO.ui.Element.getRelativePosition(
8113 this.input.$.frame.$element, this.$element.offsetParent()
8115 dimensions.left += frameOffset.left;
8116 dimensions.top += frameOffset.top;
8117 } else {
8118 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
8119 if ( this.$element.css( 'direction' ) === 'rtl' ) {
8120 dimensions.right = this.$element.parent().position().left -
8121 dimensions.width - dimensions.left;
8122 // Erase the value for 'left':
8123 delete dimensions.left;
8127 this.$element.css( dimensions );
8128 this.setIdealSize( $container.width() );
8129 return this;
8132 * Width with on and off states.
8134 * Mixin for widgets with a boolean state.
8136 * @abstract
8137 * @class
8139 * @constructor
8140 * @param {Object} [config] Configuration options
8141 * @cfg {boolean} [value=false] Initial value
8143 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
8144 // Configuration initialization
8145 config = config || {};
8147 // Properties
8148 this.value = null;
8150 // Initialization
8151 this.$element.addClass( 'oo-ui-toggleWidget' );
8152 this.setValue( !!config.value );
8155 /* Events */
8158 * @event change
8159 * @param {boolean} value Changed value
8162 /* Methods */
8165 * Get the value of the toggle.
8167 * @return {boolean}
8169 OO.ui.ToggleWidget.prototype.getValue = function () {
8170 return this.value;
8174 * Set the value of the toggle.
8176 * @param {boolean} value New value
8177 * @fires change
8178 * @chainable
8180 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
8181 value = !!value;
8182 if ( this.value !== value ) {
8183 this.value = value;
8184 this.emit( 'change', value );
8185 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
8186 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
8188 return this;
8191 * Button that toggles on and off.
8193 * @class
8194 * @extends OO.ui.ButtonWidget
8195 * @mixins OO.ui.ToggleWidget
8197 * @constructor
8198 * @param {Object} [config] Configuration options
8199 * @cfg {boolean} [value=false] Initial value
8201 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
8202 // Configuration initialization
8203 config = config || {};
8205 // Parent constructor
8206 OO.ui.ToggleButtonWidget.super.call( this, config );
8208 // Mixin constructors
8209 OO.ui.ToggleWidget.call( this, config );
8211 // Initialization
8212 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
8215 /* Setup */
8217 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
8218 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
8220 /* Methods */
8223 * @inheritdoc
8225 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
8226 if ( !this.isDisabled() ) {
8227 this.setValue( !this.value );
8230 // Parent method
8231 return OO.ui.ButtonWidget.prototype.onClick.call( this );
8235 * @inheritdoc
8237 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
8238 value = !!value;
8239 if ( value !== this.value ) {
8240 this.setActive( value );
8243 // Parent method
8244 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
8246 return this;
8249 * Switch that slides on and off.
8251 * @abstract
8252 * @class
8253 * @extends OO.ui.Widget
8254 * @mixins OO.ui.ToggleWidget
8256 * @constructor
8257 * @param {Object} [config] Configuration options
8258 * @cfg {boolean} [value=false] Initial value
8260 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
8261 // Parent constructor
8262 OO.ui.ToggleSwitchWidget.super.call( this, config );
8264 // Mixin constructors
8265 OO.ui.ToggleWidget.call( this, config );
8267 // Properties
8268 this.dragging = false;
8269 this.dragStart = null;
8270 this.sliding = false;
8271 this.$glow = this.$( '<span>' );
8272 this.$grip = this.$( '<span>' );
8274 // Events
8275 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
8277 // Initialization
8278 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
8279 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
8280 this.$element
8281 .addClass( 'oo-ui-toggleSwitchWidget' )
8282 .append( this.$glow, this.$grip );
8285 /* Setup */
8287 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
8288 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
8290 /* Methods */
8293 * Handle mouse down events.
8295 * @param {jQuery.Event} e Mouse down event
8297 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
8298 if ( !this.isDisabled() && e.which === 1 ) {
8299 this.setValue( !this.value );
8302 }( OO ) );