Merge "Remove ImageGalleryBase::useSkin() (deprecated since 1.18)"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.1.0-pre (9aad824bd6)
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: Wed Jun 25 2014 10:59:56 GMT-0700 (PDT)
10 */
11 ( function ( OO ) {
12
13 'use strict';
14 /**
15 * Namespace for all classes, static methods and static properties.
16 *
17 * @class
18 * @singleton
19 */
20 OO.ui = {};
21
22 OO.ui.bind = $.proxy;
23
24 /**
25 * @property {Object}
26 */
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
44 };
45
46 /**
47 * Get the user's language and any fallback languages.
48 *
49 * These language codes are used to localize user interface elements in the user's language.
50 *
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.
53 *
54 * @return {string[]} Language codes, in descending order of priority
55 */
56 OO.ui.getUserLanguages = function () {
57 return [ 'en' ];
58 };
59
60 /**
61 * Get a value in an object keyed by language code.
62 *
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
67 */
68 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
69 var i, len, langs;
70
71 // Requested language
72 if ( obj[lang] ) {
73 return obj[lang];
74 }
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];
81 }
82 }
83 // Fallback language
84 if ( obj[fallback] ) {
85 return obj[fallback];
86 }
87 // First existing language
88 for ( lang in obj ) {
89 return obj[lang];
90 }
91
92 return undefined;
93 };
94
95 ( function () {
96
97 /**
98 * Message store for the default implementation of OO.ui.msg
99 *
100 * Environments that provide a localization system should not use this, but should override
101 * OO.ui.msg altogether.
102 *
103 * @private
104 */
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',
116
117 // Label for the generic dialog used to confirm things
118 'ooui-dialog-confirm-title': 'Confirm',
119 // The default prompt of a confirmation dialog
120 'ooui-dialog-confirm-default-prompt': 'Are you sure?',
121 // The default OK button text on a confirmation dialog
122 'ooui-dialog-confirm-default-ok': 'OK',
123 // The default cancel button text on a confirmation dialog
124 'ooui-dialog-confirm-default-cancel': 'Cancel'
125 };
126
127 /**
128 * Get a localized message.
129 *
130 * In environments that provide a localization system, this function should be overridden to
131 * return the message translated in the user's language. The default implementation always returns
132 * English messages.
133 *
134 * After the message key, message parameters may optionally be passed. In the default implementation,
135 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
136 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
137 * they support unnamed, ordered message parameters.
138 *
139 * @abstract
140 * @param {string} key Message key
141 * @param {Mixed...} [params] Message parameters
142 * @return {string} Translated message with parameters substituted
143 */
144 OO.ui.msg = function ( key ) {
145 var message = messages[key], params = Array.prototype.slice.call( arguments, 1 );
146 if ( typeof message === 'string' ) {
147 // Perform $1 substitution
148 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
149 var i = parseInt( n, 10 );
150 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
151 } );
152 } else {
153 // Return placeholder if message not found
154 message = '[' + key + ']';
155 }
156 return message;
157 };
158
159 /** */
160 OO.ui.deferMsg = function ( key ) {
161 return function () {
162 return OO.ui.msg( key );
163 };
164 };
165
166 /** */
167 OO.ui.resolveMsg = function ( msg ) {
168 if ( $.isFunction( msg ) ) {
169 return msg();
170 }
171 return msg;
172 };
173
174 } )();
175 /**
176 * DOM element abstraction.
177 *
178 * @abstract
179 * @class
180 *
181 * @constructor
182 * @param {Object} [config] Configuration options
183 * @cfg {Function} [$] jQuery for the frame the widget is in
184 * @cfg {string[]} [classes] CSS class names
185 * @cfg {string} [text] Text to insert
186 * @cfg {jQuery} [$content] Content elements to append (after text)
187 */
188 OO.ui.Element = function OoUiElement( config ) {
189 // Configuration initialization
190 config = config || {};
191
192 // Properties
193 this.$ = config.$ || OO.ui.Element.getJQuery( document );
194 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
195 this.elementGroup = null;
196
197 // Initialization
198 if ( $.isArray( config.classes ) ) {
199 this.$element.addClass( config.classes.join( ' ' ) );
200 }
201 if ( config.text ) {
202 this.$element.text( config.text );
203 }
204 if ( config.$content ) {
205 this.$element.append( config.$content );
206 }
207 };
208
209 /* Setup */
210
211 OO.initClass( OO.ui.Element );
212
213 /* Static Properties */
214
215 /**
216 * HTML tag name.
217 *
218 * This may be ignored if getTagName is overridden.
219 *
220 * @static
221 * @inheritable
222 * @property {string}
223 */
224 OO.ui.Element.static.tagName = 'div';
225
226 /* Static Methods */
227
228 /**
229 * Get a jQuery function within a specific document.
230 *
231 * @static
232 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
233 * @param {OO.ui.Frame} [frame] Frame of the document context
234 * @return {Function} Bound jQuery function
235 */
236 OO.ui.Element.getJQuery = function ( context, frame ) {
237 function wrapper( selector ) {
238 return $( selector, wrapper.context );
239 }
240
241 wrapper.context = this.getDocument( context );
242
243 if ( frame ) {
244 wrapper.frame = frame;
245 }
246
247 return wrapper;
248 };
249
250 /**
251 * Get the document of an element.
252 *
253 * @static
254 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
255 * @return {HTMLDocument|null} Document object
256 */
257 OO.ui.Element.getDocument = function ( obj ) {
258 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
259 return ( obj[0] && obj[0].ownerDocument ) ||
260 // Empty jQuery selections might have a context
261 obj.context ||
262 // HTMLElement
263 obj.ownerDocument ||
264 // Window
265 obj.document ||
266 // HTMLDocument
267 ( obj.nodeType === 9 && obj ) ||
268 null;
269 };
270
271 /**
272 * Get the window of an element or document.
273 *
274 * @static
275 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
276 * @return {Window} Window object
277 */
278 OO.ui.Element.getWindow = function ( obj ) {
279 var doc = this.getDocument( obj );
280 return doc.parentWindow || doc.defaultView;
281 };
282
283 /**
284 * Get the direction of an element or document.
285 *
286 * @static
287 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
288 * @return {string} Text direction, either `ltr` or `rtl`
289 */
290 OO.ui.Element.getDir = function ( obj ) {
291 var isDoc, isWin;
292
293 if ( obj instanceof jQuery ) {
294 obj = obj[0];
295 }
296 isDoc = obj.nodeType === 9;
297 isWin = obj.document !== undefined;
298 if ( isDoc || isWin ) {
299 if ( isWin ) {
300 obj = obj.document;
301 }
302 obj = obj.body;
303 }
304 return $( obj ).css( 'direction' );
305 };
306
307 /**
308 * Get the offset between two frames.
309 *
310 * TODO: Make this function not use recursion.
311 *
312 * @static
313 * @param {Window} from Window of the child frame
314 * @param {Window} [to=window] Window of the parent frame
315 * @param {Object} [offset] Offset to start with, used internally
316 * @return {Object} Offset object, containing left and top properties
317 */
318 OO.ui.Element.getFrameOffset = function ( from, to, offset ) {
319 var i, len, frames, frame, rect;
320
321 if ( !to ) {
322 to = window;
323 }
324 if ( !offset ) {
325 offset = { 'top': 0, 'left': 0 };
326 }
327 if ( from.parent === from ) {
328 return offset;
329 }
330
331 // Get iframe element
332 frames = from.parent.document.getElementsByTagName( 'iframe' );
333 for ( i = 0, len = frames.length; i < len; i++ ) {
334 if ( frames[i].contentWindow === from ) {
335 frame = frames[i];
336 break;
337 }
338 }
339
340 // Recursively accumulate offset values
341 if ( frame ) {
342 rect = frame.getBoundingClientRect();
343 offset.left += rect.left;
344 offset.top += rect.top;
345 if ( from !== to ) {
346 this.getFrameOffset( from.parent, offset );
347 }
348 }
349 return offset;
350 };
351
352 /**
353 * Get the offset between two elements.
354 *
355 * @static
356 * @param {jQuery} $from
357 * @param {jQuery} $to
358 * @return {Object} Translated position coordinates, containing top and left properties
359 */
360 OO.ui.Element.getRelativePosition = function ( $from, $to ) {
361 var from = $from.offset(),
362 to = $to.offset();
363 return { 'top': Math.round( from.top - to.top ), 'left': Math.round( from.left - to.left ) };
364 };
365
366 /**
367 * Get element border sizes.
368 *
369 * @static
370 * @param {HTMLElement} el Element to measure
371 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
372 */
373 OO.ui.Element.getBorders = function ( el ) {
374 var doc = el.ownerDocument,
375 win = doc.parentWindow || doc.defaultView,
376 style = win && win.getComputedStyle ?
377 win.getComputedStyle( el, null ) :
378 el.currentStyle,
379 $el = $( el ),
380 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
381 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
382 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
383 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
384
385 return {
386 'top': Math.round( top ),
387 'left': Math.round( left ),
388 'bottom': Math.round( bottom ),
389 'right': Math.round( right )
390 };
391 };
392
393 /**
394 * Get dimensions of an element or window.
395 *
396 * @static
397 * @param {HTMLElement|Window} el Element to measure
398 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
399 */
400 OO.ui.Element.getDimensions = function ( el ) {
401 var $el, $win,
402 doc = el.ownerDocument || el.document,
403 win = doc.parentWindow || doc.defaultView;
404
405 if ( win === el || el === doc.documentElement ) {
406 $win = $( win );
407 return {
408 'borders': { 'top': 0, 'left': 0, 'bottom': 0, 'right': 0 },
409 'scroll': {
410 'top': $win.scrollTop(),
411 'left': $win.scrollLeft()
412 },
413 'scrollbar': { 'right': 0, 'bottom': 0 },
414 'rect': {
415 'top': 0,
416 'left': 0,
417 'bottom': $win.innerHeight(),
418 'right': $win.innerWidth()
419 }
420 };
421 } else {
422 $el = $( el );
423 return {
424 'borders': this.getBorders( el ),
425 'scroll': {
426 'top': $el.scrollTop(),
427 'left': $el.scrollLeft()
428 },
429 'scrollbar': {
430 'right': $el.innerWidth() - el.clientWidth,
431 'bottom': $el.innerHeight() - el.clientHeight
432 },
433 'rect': el.getBoundingClientRect()
434 };
435 }
436 };
437
438 /**
439 * Get closest scrollable container.
440 *
441 * Traverses up until either a scrollable element or the root is reached, in which case the window
442 * will be returned.
443 *
444 * @static
445 * @param {HTMLElement} el Element to find scrollable container for
446 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
447 * @return {HTMLElement|Window} Closest scrollable container
448 */
449 OO.ui.Element.getClosestScrollableContainer = function ( el, dimension ) {
450 var i, val,
451 props = [ 'overflow' ],
452 $parent = $( el ).parent();
453
454 if ( dimension === 'x' || dimension === 'y' ) {
455 props.push( 'overflow-' + dimension );
456 }
457
458 while ( $parent.length ) {
459 if ( $parent[0] === el.ownerDocument.body ) {
460 return $parent[0];
461 }
462 i = props.length;
463 while ( i-- ) {
464 val = $parent.css( props[i] );
465 if ( val === 'auto' || val === 'scroll' ) {
466 return $parent[0];
467 }
468 }
469 $parent = $parent.parent();
470 }
471 return this.getDocument( el ).body;
472 };
473
474 /**
475 * Scroll element into view.
476 *
477 * @static
478 * @param {HTMLElement} el Element to scroll into view
479 * @param {Object} [config={}] Configuration config
480 * @param {string} [config.duration] jQuery animation duration value
481 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
482 * to scroll in both directions
483 * @param {Function} [config.complete] Function to call when scrolling completes
484 */
485 OO.ui.Element.scrollIntoView = function ( el, config ) {
486 // Configuration initialization
487 config = config || {};
488
489 var rel, anim = {},
490 callback = typeof config.complete === 'function' && config.complete,
491 sc = this.getClosestScrollableContainer( el, config.direction ),
492 $sc = $( sc ),
493 eld = this.getDimensions( el ),
494 scd = this.getDimensions( sc ),
495 $win = $( this.getWindow( el ) );
496
497 // Compute the distances between the edges of el and the edges of the scroll viewport
498 if ( $sc.is( 'body' ) ) {
499 // If the scrollable container is the <body> this is easy
500 rel = {
501 'top': eld.rect.top,
502 'bottom': $win.innerHeight() - eld.rect.bottom,
503 'left': eld.rect.left,
504 'right': $win.innerWidth() - eld.rect.right
505 };
506 } else {
507 // Otherwise, we have to subtract el's coordinates from sc's coordinates
508 rel = {
509 'top': eld.rect.top - ( scd.rect.top + scd.borders.top ),
510 'bottom': scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
511 'left': eld.rect.left - ( scd.rect.left + scd.borders.left ),
512 'right': scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
513 };
514 }
515
516 if ( !config.direction || config.direction === 'y' ) {
517 if ( rel.top < 0 ) {
518 anim.scrollTop = scd.scroll.top + rel.top;
519 } else if ( rel.top > 0 && rel.bottom < 0 ) {
520 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
521 }
522 }
523 if ( !config.direction || config.direction === 'x' ) {
524 if ( rel.left < 0 ) {
525 anim.scrollLeft = scd.scroll.left + rel.left;
526 } else if ( rel.left > 0 && rel.right < 0 ) {
527 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
528 }
529 }
530 if ( !$.isEmptyObject( anim ) ) {
531 $sc.stop( true ).animate( anim, config.duration || 'fast' );
532 if ( callback ) {
533 $sc.queue( function ( next ) {
534 callback();
535 next();
536 } );
537 }
538 } else {
539 if ( callback ) {
540 callback();
541 }
542 }
543 };
544
545 /* Methods */
546
547 /**
548 * Get the HTML tag name.
549 *
550 * Override this method to base the result on instance information.
551 *
552 * @return {string} HTML tag name
553 */
554 OO.ui.Element.prototype.getTagName = function () {
555 return this.constructor.static.tagName;
556 };
557
558 /**
559 * Check if the element is attached to the DOM
560 * @return {boolean} The element is attached to the DOM
561 */
562 OO.ui.Element.prototype.isElementAttached = function () {
563 return $.contains( this.getElementDocument(), this.$element[0] );
564 };
565
566 /**
567 * Get the DOM document.
568 *
569 * @return {HTMLDocument} Document object
570 */
571 OO.ui.Element.prototype.getElementDocument = function () {
572 return OO.ui.Element.getDocument( this.$element );
573 };
574
575 /**
576 * Get the DOM window.
577 *
578 * @return {Window} Window object
579 */
580 OO.ui.Element.prototype.getElementWindow = function () {
581 return OO.ui.Element.getWindow( this.$element );
582 };
583
584 /**
585 * Get closest scrollable container.
586 */
587 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
588 return OO.ui.Element.getClosestScrollableContainer( this.$element[0] );
589 };
590
591 /**
592 * Get group element is in.
593 *
594 * @return {OO.ui.GroupElement|null} Group element, null if none
595 */
596 OO.ui.Element.prototype.getElementGroup = function () {
597 return this.elementGroup;
598 };
599
600 /**
601 * Set group element is in.
602 *
603 * @param {OO.ui.GroupElement|null} group Group element, null if none
604 * @chainable
605 */
606 OO.ui.Element.prototype.setElementGroup = function ( group ) {
607 this.elementGroup = group;
608 return this;
609 };
610
611 /**
612 * Scroll element into view.
613 *
614 * @param {Object} [config={}]
615 */
616 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
617 return OO.ui.Element.scrollIntoView( this.$element[0], config );
618 };
619
620 /**
621 * Bind a handler for an event on this.$element
622 *
623 * @deprecated Use jQuery#on instead.
624 * @param {string} event
625 * @param {Function} callback
626 */
627 OO.ui.Element.prototype.onDOMEvent = function ( event, callback ) {
628 OO.ui.Element.onDOMEvent( this.$element, event, callback );
629 };
630
631 /**
632 * Unbind a handler bound with #offDOMEvent
633 *
634 * @deprecated Use jQuery#off instead.
635 * @param {string} event
636 * @param {Function} callback
637 */
638 OO.ui.Element.prototype.offDOMEvent = function ( event, callback ) {
639 OO.ui.Element.offDOMEvent( this.$element, event, callback );
640 };
641
642 ( function () {
643 /**
644 * Bind a handler for an event on a DOM element.
645 *
646 * Used to be for working around a jQuery bug (jqbug.com/14180),
647 * but obsolete as of jQuery 1.11.0.
648 *
649 * @static
650 * @deprecated Use jQuery#on instead.
651 * @param {HTMLElement|jQuery} el DOM element
652 * @param {string} event Event to bind
653 * @param {Function} callback Callback to call when the event fires
654 */
655 OO.ui.Element.onDOMEvent = function ( el, event, callback ) {
656 $( el ).on( event, callback );
657 };
658
659 /**
660 * Unbind a handler bound with #static-method-onDOMEvent.
661 *
662 * @deprecated Use jQuery#off instead.
663 * @static
664 * @param {HTMLElement|jQuery} el DOM element
665 * @param {string} event Event to unbind
666 * @param {Function} [callback] Callback to unbind
667 */
668 OO.ui.Element.offDOMEvent = function ( el, event, callback ) {
669 $( el ).off( event, callback );
670 };
671 }() );
672 /**
673 * Embedded iframe with the same styles as its parent.
674 *
675 * @class
676 * @extends OO.ui.Element
677 * @mixins OO.EventEmitter
678 *
679 * @constructor
680 * @param {Object} [config] Configuration options
681 */
682 OO.ui.Frame = function OoUiFrame( config ) {
683 // Parent constructor
684 OO.ui.Frame.super.call( this, config );
685
686 // Mixin constructors
687 OO.EventEmitter.call( this );
688
689 // Properties
690 this.loading = null;
691 this.config = config;
692
693 // Initialize
694 this.$element
695 .addClass( 'oo-ui-frame' )
696 .attr( { 'frameborder': 0, 'scrolling': 'no' } );
697
698 };
699
700 /* Setup */
701
702 OO.inheritClass( OO.ui.Frame, OO.ui.Element );
703 OO.mixinClass( OO.ui.Frame, OO.EventEmitter );
704
705 /* Static Properties */
706
707 /**
708 * @static
709 * @inheritdoc
710 */
711 OO.ui.Frame.static.tagName = 'iframe';
712
713 /* Events */
714
715 /**
716 * @event load
717 */
718
719 /* Static Methods */
720
721 /**
722 * Transplant the CSS styles from as parent document to a frame's document.
723 *
724 * This loops over the style sheets in the parent document, and copies their nodes to the
725 * frame's document. It then polls the document to see when all styles have loaded, and once they
726 * have, resolves the promise.
727 *
728 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
729 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
730 * Firefox, where the styles won't load until the iframe becomes visible.
731 *
732 * For details of how we arrived at the strategy used in this function, see #load.
733 *
734 * @static
735 * @inheritable
736 * @param {HTMLDocument} parentDoc Document to transplant styles from
737 * @param {HTMLDocument} frameDoc Document to transplant styles to
738 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
739 * @return {jQuery.Promise} Promise resolved when styles have loaded
740 */
741 OO.ui.Frame.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
742 var i, numSheets, styleNode, newNode, timeoutID, pollNodeId, $pendingPollNodes,
743 $pollNodes = $( [] ),
744 // Fake font-family value
745 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
746 deferred = $.Deferred();
747
748 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
749 styleNode = parentDoc.styleSheets[i].ownerNode;
750 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
751 // External stylesheet
752 // Create a node with a unique ID that we're going to monitor to see when the CSS
753 // has loaded
754 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + i;
755 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
756 .attr( 'id', pollNodeId )
757 .appendTo( frameDoc.body )
758 );
759
760 // Add <style>@import url(...); #pollNodeId { font-family: ... }</style>
761 // The font-family rule will only take effect once the @import finishes
762 newNode = frameDoc.createElement( 'style' );
763 newNode.textContent = '@import url(' + styleNode.href + ');\n' +
764 '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
765 } else {
766 // Not an external stylesheet, or no polling required; just copy the node over
767 newNode = frameDoc.importNode( styleNode, true );
768 }
769 frameDoc.head.appendChild( newNode );
770 }
771
772 // Poll every 100ms until all external stylesheets have loaded
773 $pendingPollNodes = $pollNodes;
774 timeoutID = setTimeout( function pollExternalStylesheets() {
775 while (
776 $pendingPollNodes.length > 0 &&
777 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
778 ) {
779 $pendingPollNodes = $pendingPollNodes.slice( 1 );
780 }
781
782 if ( $pendingPollNodes.length === 0 ) {
783 // We're done!
784 if ( timeoutID !== null ) {
785 timeoutID = null;
786 $pollNodes.remove();
787 deferred.resolve();
788 }
789 } else {
790 timeoutID = setTimeout( pollExternalStylesheets, 100 );
791 }
792 }, 100 );
793 // ...but give up after a while
794 if ( timeout !== 0 ) {
795 setTimeout( function () {
796 if ( timeoutID ) {
797 clearTimeout( timeoutID );
798 timeoutID = null;
799 $pollNodes.remove();
800 deferred.reject();
801 }
802 }, timeout || 5000 );
803 }
804
805 return deferred.promise();
806 };
807
808 /* Methods */
809
810 /**
811 * Load the frame contents.
812 *
813 * Once the iframe's stylesheets are loaded, the `load` event will be emitted and the returned
814 * promise will be resolved. Calling while loading will return a promise but not trigger a new
815 * loading cycle. Calling after loading is complete will return a promise that's already been
816 * resolved.
817 *
818 * Sounds simple right? Read on...
819 *
820 * When you create a dynamic iframe using open/write/close, the window.load event for the
821 * iframe is triggered when you call close, and there's no further load event to indicate that
822 * everything is actually loaded.
823 *
824 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
825 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
826 * are added to document.styleSheets immediately, and the only way you can determine whether they've
827 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
828 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
829 *
830 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>` tags.
831 * Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets until
832 * the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the `@import`
833 * has finished. And because the contents of the `<style>` tag are from the same origin, accessing
834 * .cssRules is allowed.
835 *
836 * However, now that we control the styles we're injecting, we might as well do away with
837 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
838 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
839 * and wait for its font-family to change to someValue. Because `@import` is blocking, the font-family
840 * rule is not applied until after the `@import` finishes.
841 *
842 * All this stylesheet injection and polling magic is in #transplantStyles.
843 *
844 * @return {jQuery.Promise} Promise resolved when loading is complete
845 * @fires load
846 */
847 OO.ui.Frame.prototype.load = function () {
848 var win, doc;
849
850 // Return existing promise if already loading or loaded
851 if ( this.loading ) {
852 return this.loading.promise();
853 }
854
855 // Load the frame
856 this.loading = $.Deferred();
857
858 win = this.$element.prop( 'contentWindow' );
859 doc = win.document;
860
861 // Figure out directionality:
862 this.dir = OO.ui.Element.getDir( this.$element ) || 'ltr';
863
864 // Initialize contents
865 doc.open();
866 doc.write(
867 '<!doctype html>' +
868 '<html>' +
869 '<body class="oo-ui-frame-body oo-ui-' + this.dir + '" style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
870 '<div class="oo-ui-frame-content"></div>' +
871 '</body>' +
872 '</html>'
873 );
874 doc.close();
875
876 // Properties
877 this.$ = OO.ui.Element.getJQuery( doc, this );
878 this.$content = this.$( '.oo-ui-frame-content' ).attr( 'tabIndex', 0 );
879 this.$document = this.$( doc );
880
881 // Initialization
882 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[0] )
883 .always( OO.ui.bind( function () {
884 this.emit( 'load' );
885 this.loading.resolve();
886 }, this ) );
887
888 return this.loading.promise();
889 };
890
891 /**
892 * Set the size of the frame.
893 *
894 * @param {number} width Frame width in pixels
895 * @param {number} height Frame height in pixels
896 * @chainable
897 */
898 OO.ui.Frame.prototype.setSize = function ( width, height ) {
899 this.$element.css( { 'width': width, 'height': height } );
900 return this;
901 };
902 /**
903 * Container for elements in a child frame.
904 *
905 * There are two ways to specify a title: set the static `title` property or provide a `title`
906 * property in the configuration options. The latter will override the former.
907 *
908 * @abstract
909 * @class
910 * @extends OO.ui.Element
911 * @mixins OO.EventEmitter
912 *
913 * @constructor
914 * @param {Object} [config] Configuration options
915 * @cfg {string|Function} [title] Title string or function that returns a string
916 * @cfg {string} [icon] Symbolic name of icon
917 * @fires initialize
918 */
919 OO.ui.Window = function OoUiWindow( config ) {
920 var element = this;
921 // Parent constructor
922 OO.ui.Window.super.call( this, config );
923
924 // Mixin constructors
925 OO.EventEmitter.call( this );
926
927 // Properties
928 this.visible = false;
929 this.opening = null;
930 this.closing = null;
931 this.opened = null;
932 this.title = OO.ui.resolveMsg( config.title || this.constructor.static.title );
933 this.icon = config.icon || this.constructor.static.icon;
934 this.frame = new OO.ui.Frame( { '$': this.$ } );
935 this.$frame = this.$( '<div>' );
936 this.$ = function () {
937 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
938 };
939
940 // Initialization
941 this.$element
942 .addClass( 'oo-ui-window' )
943 // Hide the window using visibility: hidden; while the iframe is still loading
944 // Can't use display: none; because that prevents the iframe from loading in Firefox
945 .css( 'visibility', 'hidden' )
946 .append( this.$frame );
947 this.$frame
948 .addClass( 'oo-ui-window-frame' )
949 .append( this.frame.$element );
950
951 // Events
952 this.frame.on( 'load', function () {
953 element.initialize();
954 // Undo the visibility: hidden; hack and apply display: none;
955 // We can do this safely now that the iframe has initialized
956 // (don't do this from within #initialize because it has to happen
957 // after the all subclasses have been handled as well).
958 element.$element.hide().css( 'visibility', '' );
959 } );
960 };
961
962 /* Setup */
963
964 OO.inheritClass( OO.ui.Window, OO.ui.Element );
965 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
966
967 /* Events */
968
969 /**
970 * Window is setup.
971 *
972 * Fired after the setup process has been executed.
973 *
974 * @event setup
975 * @param {Object} data Window opening data
976 */
977
978 /**
979 * Window is ready.
980 *
981 * Fired after the ready process has been executed.
982 *
983 * @event ready
984 * @param {Object} data Window opening data
985 */
986
987 /**
988 * Window is torn down
989 *
990 * Fired after the teardown process has been executed.
991 *
992 * @event teardown
993 * @param {Object} data Window closing data
994 */
995
996 /* Static Properties */
997
998 /**
999 * Symbolic name of icon.
1000 *
1001 * @static
1002 * @inheritable
1003 * @property {string}
1004 */
1005 OO.ui.Window.static.icon = 'window';
1006
1007 /**
1008 * Window title.
1009 *
1010 * Subclasses must implement this property before instantiating the window.
1011 * Alternatively, override #getTitle with an alternative implementation.
1012 *
1013 * @static
1014 * @abstract
1015 * @inheritable
1016 * @property {string|Function} Title string or function that returns a string
1017 */
1018 OO.ui.Window.static.title = null;
1019
1020 /* Methods */
1021
1022 /**
1023 * Check if window is visible.
1024 *
1025 * @return {boolean} Window is visible
1026 */
1027 OO.ui.Window.prototype.isVisible = function () {
1028 return this.visible;
1029 };
1030
1031 /**
1032 * Check if window is opening.
1033 *
1034 * @return {boolean} Window is opening
1035 */
1036 OO.ui.Window.prototype.isOpening = function () {
1037 return !!this.opening && this.opening.state() === 'pending';
1038 };
1039
1040 /**
1041 * Check if window is closing.
1042 *
1043 * @return {boolean} Window is closing
1044 */
1045 OO.ui.Window.prototype.isClosing = function () {
1046 return !!this.closing && this.closing.state() === 'pending';
1047 };
1048
1049 /**
1050 * Check if window is opened.
1051 *
1052 * @return {boolean} Window is opened
1053 */
1054 OO.ui.Window.prototype.isOpened = function () {
1055 return !!this.opened && this.opened.state() === 'pending';
1056 };
1057
1058 /**
1059 * Get the window frame.
1060 *
1061 * @return {OO.ui.Frame} Frame of window
1062 */
1063 OO.ui.Window.prototype.getFrame = function () {
1064 return this.frame;
1065 };
1066
1067 /**
1068 * Get the title of the window.
1069 *
1070 * @return {string} Title text
1071 */
1072 OO.ui.Window.prototype.getTitle = function () {
1073 return this.title;
1074 };
1075
1076 /**
1077 * Get the window icon.
1078 *
1079 * @return {string} Symbolic name of icon
1080 */
1081 OO.ui.Window.prototype.getIcon = function () {
1082 return this.icon;
1083 };
1084
1085 /**
1086 * Set the size of window frame.
1087 *
1088 * @param {number} [width=auto] Custom width
1089 * @param {number} [height=auto] Custom height
1090 * @chainable
1091 */
1092 OO.ui.Window.prototype.setSize = function ( width, height ) {
1093 if ( !this.frame.$content ) {
1094 return;
1095 }
1096
1097 this.frame.$element.css( {
1098 'width': width === undefined ? 'auto' : width,
1099 'height': height === undefined ? 'auto' : height
1100 } );
1101
1102 return this;
1103 };
1104
1105 /**
1106 * Set the title of the window.
1107 *
1108 * @param {string|Function} title Title text or a function that returns text
1109 * @chainable
1110 */
1111 OO.ui.Window.prototype.setTitle = function ( title ) {
1112 this.title = OO.ui.resolveMsg( title );
1113 if ( this.$title ) {
1114 this.$title.text( title );
1115 }
1116 return this;
1117 };
1118
1119 /**
1120 * Set the icon of the window.
1121 *
1122 * @param {string} icon Symbolic name of icon
1123 * @chainable
1124 */
1125 OO.ui.Window.prototype.setIcon = function ( icon ) {
1126 if ( this.$icon ) {
1127 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
1128 }
1129 this.icon = icon;
1130 if ( this.$icon ) {
1131 this.$icon.addClass( 'oo-ui-icon-' + this.icon );
1132 }
1133
1134 return this;
1135 };
1136
1137 /**
1138 * Set the position of window to fit with contents.
1139 *
1140 * @param {string} left Left offset
1141 * @param {string} top Top offset
1142 * @chainable
1143 */
1144 OO.ui.Window.prototype.setPosition = function ( left, top ) {
1145 this.$element.css( { 'left': left, 'top': top } );
1146 return this;
1147 };
1148
1149 /**
1150 * Set the height of window to fit with contents.
1151 *
1152 * @param {number} [min=0] Min height
1153 * @param {number} [max] Max height (defaults to content's outer height)
1154 * @chainable
1155 */
1156 OO.ui.Window.prototype.fitHeightToContents = function ( min, max ) {
1157 var height = this.frame.$content.outerHeight();
1158
1159 this.frame.$element.css(
1160 'height', Math.max( min || 0, max === undefined ? height : Math.min( max, height ) )
1161 );
1162
1163 return this;
1164 };
1165
1166 /**
1167 * Set the width of window to fit with contents.
1168 *
1169 * @param {number} [min=0] Min height
1170 * @param {number} [max] Max height (defaults to content's outer width)
1171 * @chainable
1172 */
1173 OO.ui.Window.prototype.fitWidthToContents = function ( min, max ) {
1174 var width = this.frame.$content.outerWidth();
1175
1176 this.frame.$element.css(
1177 'width', Math.max( min || 0, max === undefined ? width : Math.min( max, width ) )
1178 );
1179
1180 return this;
1181 };
1182
1183 /**
1184 * Initialize window contents.
1185 *
1186 * The first time the window is opened, #initialize is called when it's safe to begin populating
1187 * its contents. See #setup for a way to make changes each time the window opens.
1188 *
1189 * Once this method is called, this.$$ can be used to create elements within the frame.
1190 *
1191 * @chainable
1192 */
1193 OO.ui.Window.prototype.initialize = function () {
1194 // Properties
1195 this.$ = this.frame.$;
1196 this.$title = this.$( '<div class="oo-ui-window-title"></div>' )
1197 .text( this.title );
1198 this.$icon = this.$( '<div class="oo-ui-window-icon"></div>' )
1199 .addClass( 'oo-ui-icon-' + this.icon );
1200 this.$head = this.$( '<div class="oo-ui-window-head"></div>' );
1201 this.$body = this.$( '<div class="oo-ui-window-body"></div>' );
1202 this.$foot = this.$( '<div class="oo-ui-window-foot"></div>' );
1203 this.$overlay = this.$( '<div class="oo-ui-window-overlay"></div>' );
1204
1205 // Initialization
1206 this.frame.$content.append(
1207 this.$head.append( this.$icon, this.$title ),
1208 this.$body,
1209 this.$foot,
1210 this.$overlay
1211 );
1212
1213 return this;
1214 };
1215
1216 /**
1217 * Get a process for setting up a window for use.
1218 *
1219 * Each time the window is opened this process will set it up for use in a particular context, based
1220 * on the `data` argument.
1221 *
1222 * When you override this method, you can add additional setup steps to the process the parent
1223 * method provides using the 'first' and 'next' methods.
1224 *
1225 * @abstract
1226 * @param {Object} [data] Window opening data
1227 * @return {OO.ui.Process} Setup process
1228 */
1229 OO.ui.Window.prototype.getSetupProcess = function () {
1230 return new OO.ui.Process();
1231 };
1232
1233 /**
1234 * Get a process for readying a window for use.
1235 *
1236 * Each time the window is open and setup, this process will ready it up for use in a particular
1237 * context, based on the `data` argument.
1238 *
1239 * When you override this method, you can add additional setup steps to the process the parent
1240 * method provides using the 'first' and 'next' methods.
1241 *
1242 * @abstract
1243 * @param {Object} [data] Window opening data
1244 * @return {OO.ui.Process} Setup process
1245 */
1246 OO.ui.Window.prototype.getReadyProcess = function () {
1247 return new OO.ui.Process();
1248 };
1249
1250 /**
1251 * Get a process for tearing down a window after use.
1252 *
1253 * Each time the window is closed this process will tear it down and do something with the user's
1254 * interactions within the window, based on the `data` argument.
1255 *
1256 * When you override this method, you can add additional teardown steps to the process the parent
1257 * method provides using the 'first' and 'next' methods.
1258 *
1259 * @abstract
1260 * @param {Object} [data] Window closing data
1261 * @return {OO.ui.Process} Teardown process
1262 */
1263 OO.ui.Window.prototype.getTeardownProcess = function () {
1264 return new OO.ui.Process();
1265 };
1266
1267 /**
1268 * Open window.
1269 *
1270 * Do not override this method. Use #getSetupProcess to do something each time the window closes.
1271 *
1272 * @param {Object} [data] Window opening data
1273 * @fires initialize
1274 * @fires opening
1275 * @fires open
1276 * @fires ready
1277 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
1278 * first argument will be a promise which will be resolved when the window begins closing
1279 */
1280 OO.ui.Window.prototype.open = function ( data ) {
1281 // Return existing promise if already opening or open
1282 if ( this.opening ) {
1283 return this.opening.promise();
1284 }
1285
1286 // Open the window
1287 this.opening = $.Deferred();
1288
1289 this.$ariaHidden = $( 'body' ).children().not( this.$element.parentsUntil( 'body' ).last() )
1290 .attr( 'aria-hidden', '' );
1291
1292 this.frame.load().done( OO.ui.bind( function () {
1293 this.$element.show();
1294 this.visible = true;
1295 this.getSetupProcess( data ).execute().done( OO.ui.bind( function () {
1296 this.$element.addClass( 'oo-ui-window-setup' );
1297 this.emit( 'setup', data );
1298 setTimeout( OO.ui.bind( function () {
1299 this.frame.$content.focus();
1300 this.getReadyProcess( data ).execute().done( OO.ui.bind( function () {
1301 this.$element.addClass( 'oo-ui-window-ready' );
1302 this.emit( 'ready', data );
1303 this.opened = $.Deferred();
1304 // Now that we are totally done opening, it's safe to allow closing
1305 this.closing = null;
1306 this.opening.resolve( this.opened.promise() );
1307 }, this ) );
1308 }, this ) );
1309 }, this ) );
1310 }, this ) );
1311
1312 return this.opening.promise();
1313 };
1314
1315 /**
1316 * Close window.
1317 *
1318 * Do not override this method. Use #getTeardownProcess to do something each time the window closes.
1319 *
1320 * @param {Object} [data] Window closing data
1321 * @fires closing
1322 * @fires close
1323 * @return {jQuery.Promise} Promise resolved when window is closed
1324 */
1325 OO.ui.Window.prototype.close = function ( data ) {
1326 var close;
1327
1328 // Return existing promise if already closing or closed
1329 if ( this.closing ) {
1330 return this.closing.promise();
1331 }
1332
1333 // Close after opening is done if opening is in progress
1334 if ( this.opening && this.opening.state() === 'pending' ) {
1335 close = OO.ui.bind( function () {
1336 return this.close( data );
1337 }, this );
1338 return this.opening.then( close, close );
1339 }
1340
1341 // Close the window
1342 // This.closing needs to exist before we emit the closing event so that handlers can call
1343 // window.close() and trigger the safety check above
1344 this.closing = $.Deferred();
1345 this.frame.$content.find( ':focus' ).blur();
1346 this.$element.removeClass( 'oo-ui-window-ready' );
1347 this.getTeardownProcess( data ).execute().done( OO.ui.bind( function () {
1348 this.$element.removeClass( 'oo-ui-window-setup' );
1349 this.emit( 'teardown', data );
1350 // To do something different with #opened, resolve/reject #opened in the teardown process
1351 if ( this.opened && this.opened.state() === 'pending' ) {
1352 this.opened.resolve();
1353 }
1354 this.$element.hide();
1355 if ( this.$ariaHidden ) {
1356 this.$ariaHidden.removeAttr( 'aria-hidden' );
1357 this.$ariaHidden = undefined;
1358 }
1359 this.visible = false;
1360 this.closing.resolve();
1361 // Now that we are totally done closing, it's safe to allow opening
1362 this.opening = null;
1363 }, this ) );
1364
1365 return this.closing.promise();
1366 };
1367 /**
1368 * Set of mutually exclusive windows.
1369 *
1370 * @class
1371 * @extends OO.ui.Element
1372 * @mixins OO.EventEmitter
1373 *
1374 * @constructor
1375 * @param {OO.Factory} factory Window factory
1376 * @param {Object} [config] Configuration options
1377 */
1378 OO.ui.WindowSet = function OoUiWindowSet( factory, config ) {
1379 // Parent constructor
1380 OO.ui.WindowSet.super.call( this, config );
1381
1382 // Mixin constructors
1383 OO.EventEmitter.call( this );
1384
1385 // Properties
1386 this.factory = factory;
1387
1388 /**
1389 * List of all windows associated with this window set.
1390 *
1391 * @property {OO.ui.Window[]}
1392 */
1393 this.windowList = [];
1394
1395 /**
1396 * Mapping of OO.ui.Window objects created by name from the #factory.
1397 *
1398 * @property {Object}
1399 */
1400 this.windows = {};
1401 this.currentWindow = null;
1402
1403 // Initialization
1404 this.$element.addClass( 'oo-ui-windowSet' );
1405 };
1406
1407 /* Setup */
1408
1409 OO.inheritClass( OO.ui.WindowSet, OO.ui.Element );
1410 OO.mixinClass( OO.ui.WindowSet, OO.EventEmitter );
1411
1412 /* Events */
1413
1414 /**
1415 * @event setup
1416 * @param {OO.ui.Window} win Window that's been setup
1417 * @param {Object} config Window opening information
1418 */
1419
1420 /**
1421 * @event ready
1422 * @param {OO.ui.Window} win Window that's ready
1423 * @param {Object} config Window opening information
1424 */
1425
1426 /**
1427 * @event teardown
1428 * @param {OO.ui.Window} win Window that's been torn down
1429 * @param {Object} config Window closing information
1430 */
1431
1432 /* Methods */
1433
1434 /**
1435 * Handle a window setup event.
1436 *
1437 * @param {OO.ui.Window} win Window that's been setup
1438 * @param {Object} [config] Window opening information
1439 * @fires setup
1440 */
1441 OO.ui.WindowSet.prototype.onWindowSetup = function ( win, config ) {
1442 if ( this.currentWindow && this.currentWindow !== win ) {
1443 this.currentWindow.close();
1444 }
1445 this.currentWindow = win;
1446 this.emit( 'setup', win, config );
1447 };
1448
1449 /**
1450 * Handle a window ready event.
1451 *
1452 * @param {OO.ui.Window} win Window that's ready
1453 * @param {Object} [config] Window opening information
1454 * @fires ready
1455 */
1456 OO.ui.WindowSet.prototype.onWindowReady = function ( win, config ) {
1457 this.emit( 'ready', win, config );
1458 };
1459
1460 /**
1461 * Handle a window teardown event.
1462 *
1463 * @param {OO.ui.Window} win Window that's been torn down
1464 * @param {Object} [config] Window closing information
1465 * @fires teardown
1466 */
1467 OO.ui.WindowSet.prototype.onWindowTeardown = function ( win, config ) {
1468 this.currentWindow = null;
1469 this.emit( 'teardown', win, config );
1470 };
1471
1472 /**
1473 * Get the current window.
1474 *
1475 * @return {OO.ui.Window|null} Current window or null if none open
1476 */
1477 OO.ui.WindowSet.prototype.getCurrentWindow = function () {
1478 return this.currentWindow;
1479 };
1480
1481 /**
1482 * Return a given window.
1483 *
1484 * @param {string} name Symbolic name of window
1485 * @return {OO.ui.Window} Window with specified name
1486 */
1487 OO.ui.WindowSet.prototype.getWindow = function ( name ) {
1488 var win;
1489
1490 if ( !this.factory.lookup( name ) ) {
1491 throw new Error( 'Unknown window: ' + name );
1492 }
1493 if ( !( name in this.windows ) ) {
1494 win = this.windows[name] = this.createWindow( name );
1495 this.addWindow( win );
1496 }
1497 return this.windows[name];
1498 };
1499
1500 /**
1501 * Create a window for use in this window set.
1502 *
1503 * @param {string} name Symbolic name of window
1504 * @return {OO.ui.Window} Window with specified name
1505 */
1506 OO.ui.WindowSet.prototype.createWindow = function ( name ) {
1507 return this.factory.create( name, { '$': this.$ } );
1508 };
1509
1510 /**
1511 * Add a given window to this window set.
1512 *
1513 * Connects event handlers and attaches it to the DOM. Calling
1514 * OO.ui.Window#open will not work until the window is added to the set.
1515 *
1516 * @param {OO.ui.Window} win Window to add
1517 */
1518 OO.ui.WindowSet.prototype.addWindow = function ( win ) {
1519 if ( this.windowList.indexOf( win ) !== -1 ) {
1520 // Already set up
1521 return;
1522 }
1523 this.windowList.push( win );
1524
1525 win.connect( this, {
1526 'setup': [ 'onWindowSetup', win ],
1527 'ready': [ 'onWindowReady', win ],
1528 'teardown': [ 'onWindowTeardown', win ]
1529 } );
1530 this.$element.append( win.$element );
1531 };
1532 /**
1533 * Modal dialog window.
1534 *
1535 * @abstract
1536 * @class
1537 * @extends OO.ui.Window
1538 *
1539 * @constructor
1540 * @param {Object} [config] Configuration options
1541 * @cfg {boolean} [footless] Hide foot
1542 * @cfg {string} [size='large'] Symbolic name of dialog size, `small`, `medium` or `large`
1543 */
1544 OO.ui.Dialog = function OoUiDialog( config ) {
1545 // Configuration initialization
1546 config = $.extend( { 'size': 'large' }, config );
1547
1548 // Parent constructor
1549 OO.ui.Dialog.super.call( this, config );
1550
1551 // Properties
1552 this.visible = false;
1553 this.footless = !!config.footless;
1554 this.size = null;
1555 this.pending = 0;
1556 this.onWindowMouseWheelHandler = OO.ui.bind( this.onWindowMouseWheel, this );
1557 this.onDocumentKeyDownHandler = OO.ui.bind( this.onDocumentKeyDown, this );
1558
1559 // Events
1560 this.$element.on( 'mousedown', false );
1561
1562 // Initialization
1563 this.$element.addClass( 'oo-ui-dialog' ).attr( 'role', 'dialog' );
1564 this.setSize( config.size );
1565 };
1566
1567 /* Setup */
1568
1569 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
1570
1571 /* Static Properties */
1572
1573 /**
1574 * Symbolic name of dialog.
1575 *
1576 * @abstract
1577 * @static
1578 * @inheritable
1579 * @property {string}
1580 */
1581 OO.ui.Dialog.static.name = '';
1582
1583 /**
1584 * Map of symbolic size names and CSS classes.
1585 *
1586 * @static
1587 * @inheritable
1588 * @property {Object}
1589 */
1590 OO.ui.Dialog.static.sizeCssClasses = {
1591 'small': 'oo-ui-dialog-small',
1592 'medium': 'oo-ui-dialog-medium',
1593 'large': 'oo-ui-dialog-large'
1594 };
1595
1596 /* Methods */
1597
1598 /**
1599 * Handle close button click events.
1600 */
1601 OO.ui.Dialog.prototype.onCloseButtonClick = function () {
1602 this.close( { 'action': 'cancel' } );
1603 };
1604
1605 /**
1606 * Handle window mouse wheel events.
1607 *
1608 * @param {jQuery.Event} e Mouse wheel event
1609 */
1610 OO.ui.Dialog.prototype.onWindowMouseWheel = function () {
1611 return false;
1612 };
1613
1614 /**
1615 * Handle document key down events.
1616 *
1617 * @param {jQuery.Event} e Key down event
1618 */
1619 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
1620 switch ( e.which ) {
1621 case OO.ui.Keys.PAGEUP:
1622 case OO.ui.Keys.PAGEDOWN:
1623 case OO.ui.Keys.END:
1624 case OO.ui.Keys.HOME:
1625 case OO.ui.Keys.LEFT:
1626 case OO.ui.Keys.UP:
1627 case OO.ui.Keys.RIGHT:
1628 case OO.ui.Keys.DOWN:
1629 // Prevent any key events that might cause scrolling
1630 return false;
1631 }
1632 };
1633
1634 /**
1635 * Handle frame document key down events.
1636 *
1637 * @param {jQuery.Event} e Key down event
1638 */
1639 OO.ui.Dialog.prototype.onFrameDocumentKeyDown = function ( e ) {
1640 if ( e.which === OO.ui.Keys.ESCAPE ) {
1641 this.close( { 'action': 'cancel' } );
1642 return false;
1643 }
1644 };
1645
1646 /**
1647 * Set dialog size.
1648 *
1649 * @param {string} [size='large'] Symbolic name of dialog size, `small`, `medium` or `large`
1650 */
1651 OO.ui.Dialog.prototype.setSize = function ( size ) {
1652 var name, state, cssClass,
1653 sizeCssClasses = OO.ui.Dialog.static.sizeCssClasses;
1654
1655 if ( !sizeCssClasses[size] ) {
1656 size = 'large';
1657 }
1658 this.size = size;
1659 for ( name in sizeCssClasses ) {
1660 state = name === size;
1661 cssClass = sizeCssClasses[name];
1662 this.$element.toggleClass( cssClass, state );
1663 }
1664 };
1665
1666 /**
1667 * @inheritdoc
1668 */
1669 OO.ui.Dialog.prototype.initialize = function () {
1670 // Parent method
1671 OO.ui.Dialog.super.prototype.initialize.call( this );
1672
1673 // Properties
1674 this.closeButton = new OO.ui.ButtonWidget( {
1675 '$': this.$,
1676 'frameless': true,
1677 'icon': 'close',
1678 'title': OO.ui.msg( 'ooui-dialog-action-close' )
1679 } );
1680
1681 // Events
1682 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
1683 this.frame.$document.on( 'keydown', OO.ui.bind( this.onFrameDocumentKeyDown, this ) );
1684
1685 // Initialization
1686 this.frame.$content.addClass( 'oo-ui-dialog-content' );
1687 if ( this.footless ) {
1688 this.frame.$content.addClass( 'oo-ui-dialog-content-footless' );
1689 }
1690 this.closeButton.$element.addClass( 'oo-ui-window-closeButton' );
1691 this.$head.append( this.closeButton.$element );
1692 };
1693
1694 /**
1695 * @inheritdoc
1696 */
1697 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
1698 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
1699 .next( function () {
1700 // Prevent scrolling in top-level window
1701 this.$( window ).on( 'mousewheel', this.onWindowMouseWheelHandler );
1702 this.$( document ).on( 'keydown', this.onDocumentKeyDownHandler );
1703 }, this );
1704 };
1705
1706 /**
1707 * @inheritdoc
1708 */
1709 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
1710 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
1711 .first( function () {
1712 // Wait for closing transition
1713 return OO.ui.Process.static.delay( 250 );
1714 }, this )
1715 .next( function () {
1716 // Allow scrolling in top-level window
1717 this.$( window ).off( 'mousewheel', this.onWindowMouseWheelHandler );
1718 this.$( document ).off( 'keydown', this.onDocumentKeyDownHandler );
1719 }, this );
1720 };
1721
1722 /**
1723 * Check if input is pending.
1724 *
1725 * @return {boolean}
1726 */
1727 OO.ui.Dialog.prototype.isPending = function () {
1728 return !!this.pending;
1729 };
1730
1731 /**
1732 * Increase the pending stack.
1733 *
1734 * @chainable
1735 */
1736 OO.ui.Dialog.prototype.pushPending = function () {
1737 if ( this.pending === 0 ) {
1738 this.frame.$content.addClass( 'oo-ui-dialog-pending' );
1739 this.$head.addClass( 'oo-ui-texture-pending' );
1740 this.$foot.addClass( 'oo-ui-texture-pending' );
1741 }
1742 this.pending++;
1743
1744 return this;
1745 };
1746
1747 /**
1748 * Reduce the pending stack.
1749 *
1750 * Clamped at zero.
1751 *
1752 * @chainable
1753 */
1754 OO.ui.Dialog.prototype.popPending = function () {
1755 if ( this.pending === 1 ) {
1756 this.frame.$content.removeClass( 'oo-ui-dialog-pending' );
1757 this.$head.removeClass( 'oo-ui-texture-pending' );
1758 this.$foot.removeClass( 'oo-ui-texture-pending' );
1759 }
1760 this.pending = Math.max( 0, this.pending - 1 );
1761
1762 return this;
1763 };
1764 /**
1765 * Container for elements.
1766 *
1767 * @abstract
1768 * @class
1769 * @extends OO.ui.Element
1770 * @mixins OO.EventEmitter
1771 *
1772 * @constructor
1773 * @param {Object} [config] Configuration options
1774 */
1775 OO.ui.Layout = function OoUiLayout( config ) {
1776 // Initialize config
1777 config = config || {};
1778
1779 // Parent constructor
1780 OO.ui.Layout.super.call( this, config );
1781
1782 // Mixin constructors
1783 OO.EventEmitter.call( this );
1784
1785 // Initialization
1786 this.$element.addClass( 'oo-ui-layout' );
1787 };
1788
1789 /* Setup */
1790
1791 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1792 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1793 /**
1794 * User interface control.
1795 *
1796 * @abstract
1797 * @class
1798 * @extends OO.ui.Element
1799 * @mixins OO.EventEmitter
1800 *
1801 * @constructor
1802 * @param {Object} [config] Configuration options
1803 * @cfg {boolean} [disabled=false] Disable
1804 */
1805 OO.ui.Widget = function OoUiWidget( config ) {
1806 // Initialize config
1807 config = $.extend( { 'disabled': false }, config );
1808
1809 // Parent constructor
1810 OO.ui.Widget.super.call( this, config );
1811
1812 // Mixin constructors
1813 OO.EventEmitter.call( this );
1814
1815 // Properties
1816 this.disabled = null;
1817 this.wasDisabled = null;
1818
1819 // Initialization
1820 this.$element.addClass( 'oo-ui-widget' );
1821 this.setDisabled( !!config.disabled );
1822 };
1823
1824 /* Setup */
1825
1826 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1827 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1828
1829 /* Events */
1830
1831 /**
1832 * @event disable
1833 * @param {boolean} disabled Widget is disabled
1834 */
1835
1836 /* Methods */
1837
1838 /**
1839 * Check if the widget is disabled.
1840 *
1841 * @param {boolean} Button is disabled
1842 */
1843 OO.ui.Widget.prototype.isDisabled = function () {
1844 return this.disabled;
1845 };
1846
1847 /**
1848 * Update the disabled state, in case of changes in parent widget.
1849 *
1850 * @chainable
1851 */
1852 OO.ui.Widget.prototype.updateDisabled = function () {
1853 this.setDisabled( this.disabled );
1854 return this;
1855 };
1856
1857 /**
1858 * Set the disabled state of the widget.
1859 *
1860 * This should probably change the widgets' appearance and prevent it from being used.
1861 *
1862 * @param {boolean} disabled Disable widget
1863 * @chainable
1864 */
1865 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1866 var isDisabled;
1867
1868 this.disabled = !!disabled;
1869 isDisabled = this.isDisabled();
1870 if ( isDisabled !== this.wasDisabled ) {
1871 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1872 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1873 this.emit( 'disable', isDisabled );
1874 }
1875 this.wasDisabled = isDisabled;
1876 return this;
1877 };
1878 /**
1879 * A list of functions, called in sequence.
1880 *
1881 * If a function added to a process returns boolean false the process will stop; if it returns an
1882 * object with a `promise` method the process will use the promise to either continue to the next
1883 * step when the promise is resolved or stop when the promise is rejected.
1884 *
1885 * @class
1886 *
1887 * @constructor
1888 */
1889 OO.ui.Process = function () {
1890 // Properties
1891 this.steps = [];
1892 };
1893
1894 /* Setup */
1895
1896 OO.initClass( OO.ui.Process );
1897
1898 /* Static Methods */
1899
1900 /**
1901 * Generate a promise which is resolved after a set amount of time.
1902 *
1903 * @param {number} length Number of milliseconds before resolving the promise
1904 * @return {jQuery.Promise} Promise that will be resolved after a set amount of time
1905 */
1906 OO.ui.Process.static.delay = function ( length ) {
1907 var deferred = $.Deferred();
1908
1909 setTimeout( function () {
1910 deferred.resolve();
1911 }, length );
1912
1913 return deferred.promise();
1914 };
1915
1916 /* Methods */
1917
1918 /**
1919 * Start the process.
1920 *
1921 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
1922 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
1923 * process, the remaining steps will not be taken
1924 */
1925 OO.ui.Process.prototype.execute = function () {
1926 var i, len, promise;
1927
1928 /**
1929 * Continue execution.
1930 *
1931 * @ignore
1932 * @param {Array} step A function and the context it should be called in
1933 * @return {Function} Function that continues the process
1934 */
1935 function proceed( step ) {
1936 return function () {
1937 // Execute step in the correct context
1938 var result = step[0].call( step[1] );
1939
1940 if ( result === false ) {
1941 // Use rejected promise for boolean false results
1942 return $.Deferred().reject().promise();
1943 }
1944 // Duck-type the object to see if it can produce a promise
1945 if ( result && $.isFunction( result.promise ) ) {
1946 // Use a promise generated from the result
1947 return result.promise();
1948 }
1949 // Use resolved promise for other results
1950 return $.Deferred().resolve().promise();
1951 };
1952 }
1953
1954 if ( this.steps.length ) {
1955 // Generate a chain reaction of promises
1956 promise = proceed( this.steps[0] )();
1957 for ( i = 1, len = this.steps.length; i < len; i++ ) {
1958 promise = promise.then( proceed( this.steps[i] ) );
1959 }
1960 } else {
1961 promise = $.Deferred().resolve().promise();
1962 }
1963
1964 return promise;
1965 };
1966
1967 /**
1968 * Add step to the beginning of the process.
1969 *
1970 * @param {Function} step Function to execute; if it returns boolean false the process will stop; if
1971 * it returns an object with a `promise` method the process will use the promise to either
1972 * continue to the next step when the promise is resolved or stop when the promise is rejected
1973 * @param {Object} [context=null] Context to call the step function in
1974 * @chainable
1975 */
1976 OO.ui.Process.prototype.first = function ( step, context ) {
1977 this.steps.unshift( [ step, context || null ] );
1978 return this;
1979 };
1980
1981 /**
1982 * Add step to the end of the process.
1983 *
1984 * @param {Function} step Function to execute; if it returns boolean false the process will stop; if
1985 * it returns an object with a `promise` method the process will use the promise to either
1986 * continue to the next step when the promise is resolved or stop when the promise is rejected
1987 * @param {Object} [context=null] Context to call the step function in
1988 * @chainable
1989 */
1990 OO.ui.Process.prototype.next = function ( step, context ) {
1991 this.steps.push( [ step, context || null ] );
1992 return this;
1993 };
1994 /**
1995 * Dialog for showing a confirmation/warning message.
1996 *
1997 * @class
1998 * @extends OO.ui.Dialog
1999 *
2000 * @constructor
2001 * @param {Object} [config] Configuration options
2002 */
2003 OO.ui.ConfirmationDialog = function OoUiConfirmationDialog( config ) {
2004 // Configuration initialization
2005 config = $.extend( { 'size': 'small' }, config );
2006
2007 // Parent constructor
2008 OO.ui.Dialog.call( this, config );
2009 };
2010
2011 /* Inheritance */
2012
2013 OO.inheritClass( OO.ui.ConfirmationDialog, OO.ui.Dialog );
2014
2015 /* Static Properties */
2016
2017 OO.ui.ConfirmationDialog.static.name = 'confirm';
2018
2019 OO.ui.ConfirmationDialog.static.icon = 'help';
2020
2021 OO.ui.ConfirmationDialog.static.title = OO.ui.deferMsg( 'ooui-dialog-confirm-title' );
2022
2023 /* Methods */
2024
2025 /**
2026 * @inheritdoc
2027 */
2028 OO.ui.ConfirmationDialog.prototype.initialize = function () {
2029 // Parent method
2030 OO.ui.Dialog.prototype.initialize.call( this );
2031
2032 // Set up the layout
2033 var contentLayout = new OO.ui.PanelLayout( {
2034 '$': this.$,
2035 'padded': true
2036 } );
2037
2038 this.$promptContainer = this.$( '<div>' ).addClass( 'oo-ui-dialog-confirm-promptContainer' );
2039
2040 this.cancelButton = new OO.ui.ButtonWidget();
2041 this.cancelButton.connect( this, { 'click': [ 'close', 'cancel' ] } );
2042
2043 this.okButton = new OO.ui.ButtonWidget();
2044 this.okButton.connect( this, { 'click': [ 'close', 'ok' ] } );
2045
2046 // Make the buttons
2047 contentLayout.$element.append( this.$promptContainer );
2048 this.$body.append( contentLayout.$element );
2049
2050 this.$foot.append(
2051 this.okButton.$element,
2052 this.cancelButton.$element
2053 );
2054
2055 this.connect( this, { 'teardown': [ 'close', 'cancel' ] } );
2056 };
2057
2058 /*
2059 * Setup a confirmation dialog.
2060 *
2061 * @param {Object} [data] Window opening data including text of the dialog and text for the buttons
2062 * @param {jQuery|string} [data.prompt] Text to display or list of nodes to use as content of the dialog.
2063 * @param {jQuery|string|Function|null} [data.okLabel] Label of the OK button
2064 * @param {jQuery|string|Function|null} [data.cancelLabel] Label of the cancel button
2065 * @param {string|string[]} [data.okFlags="constructive"] Flags for the OK button
2066 * @param {string|string[]} [data.cancelFlags="destructive"] Flags for the cancel button
2067 * @return {OO.ui.Process} Setup process
2068 */
2069 OO.ui.ConfirmationDialog.prototype.getSetupProcess = function ( data ) {
2070 // Parent method
2071 return OO.ui.ConfirmationDialog.super.prototype.getSetupProcess.call( this, data )
2072 .next( function () {
2073 var prompt = data.prompt || OO.ui.deferMsg( 'ooui-dialog-confirm-default-prompt' ),
2074 okLabel = data.okLabel || OO.ui.deferMsg( 'ooui-dialog-confirm-default-ok' ),
2075 cancelLabel = data.cancelLabel || OO.ui.deferMsg( 'ooui-dialog-confirm-default-cancel' ),
2076 okFlags = data.okFlags || 'constructive',
2077 cancelFlags = data.cancelFlags || 'destructive';
2078
2079 if ( typeof prompt === 'string' ) {
2080 this.$promptContainer.text( prompt );
2081 } else {
2082 this.$promptContainer.empty().append( prompt );
2083 }
2084
2085 this.okButton.setLabel( okLabel ).clearFlags().setFlags( okFlags );
2086 this.cancelButton.setLabel( cancelLabel ).clearFlags().setFlags( cancelFlags );
2087 }, this );
2088 };
2089
2090 /**
2091 * @inheritdoc
2092 */
2093 OO.ui.ConfirmationDialog.prototype.getTeardownProcess = function ( data ) {
2094 // Parent method
2095 return OO.ui.ConfirmationDialog.super.prototype.getTeardownProcess.call( this, data )
2096 .first( function () {
2097 if ( data === 'ok' ) {
2098 this.opened.resolve();
2099 } else if ( data === 'cancel' ) {
2100 this.opened.reject();
2101 }
2102 }, this );
2103 };
2104 /**
2105 * Element with a button.
2106 *
2107 * @abstract
2108 * @class
2109 *
2110 * @constructor
2111 * @param {jQuery} $button Button node, assigned to #$button
2112 * @param {Object} [config] Configuration options
2113 * @cfg {boolean} [frameless] Render button without a frame
2114 * @cfg {number} [tabIndex=0] Button's tab index, use -1 to prevent tab focusing
2115 */
2116 OO.ui.ButtonedElement = function OoUiButtonedElement( $button, config ) {
2117 // Configuration initialization
2118 config = config || {};
2119
2120 // Properties
2121 this.$button = $button;
2122 this.tabIndex = null;
2123 this.active = false;
2124 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
2125
2126 // Events
2127 this.$button.on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
2128
2129 // Initialization
2130 this.$element.addClass( 'oo-ui-buttonedElement' );
2131 this.$button
2132 .addClass( 'oo-ui-buttonedElement-button' )
2133 .attr( 'role', 'button' )
2134 .prop( 'tabIndex', config.tabIndex || 0 );
2135 if ( config.frameless ) {
2136 this.$element.addClass( 'oo-ui-buttonedElement-frameless' );
2137 } else {
2138 this.$element.addClass( 'oo-ui-buttonedElement-framed' );
2139 }
2140 };
2141
2142 /* Setup */
2143
2144 OO.initClass( OO.ui.ButtonedElement );
2145
2146 /* Static Properties */
2147
2148 /**
2149 * Cancel mouse down events.
2150 *
2151 * @static
2152 * @inheritable
2153 * @property {boolean}
2154 */
2155 OO.ui.ButtonedElement.static.cancelButtonMouseDownEvents = true;
2156
2157 /* Methods */
2158
2159 /**
2160 * Handles mouse down events.
2161 *
2162 * @param {jQuery.Event} e Mouse down event
2163 */
2164 OO.ui.ButtonedElement.prototype.onMouseDown = function ( e ) {
2165 if ( this.isDisabled() || e.which !== 1 ) {
2166 return false;
2167 }
2168 // tabIndex should generally be interacted with via the property, but it's not possible to
2169 // reliably unset a tabIndex via a property so we use the (lowercase) "tabindex" attribute
2170 this.tabIndex = this.$button.attr( 'tabindex' );
2171 this.$button
2172 // Remove the tab-index while the button is down to prevent the button from stealing focus
2173 .removeAttr( 'tabindex' )
2174 .addClass( 'oo-ui-buttonedElement-pressed' );
2175 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2176 // reliably reapply the tabindex and remove the pressed class
2177 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
2178 // Prevent change of focus unless specifically configured otherwise
2179 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
2180 return false;
2181 }
2182 };
2183
2184 /**
2185 * Handles mouse up events.
2186 *
2187 * @param {jQuery.Event} e Mouse up event
2188 */
2189 OO.ui.ButtonedElement.prototype.onMouseUp = function ( e ) {
2190 if ( this.isDisabled() || e.which !== 1 ) {
2191 return false;
2192 }
2193 this.$button
2194 // Restore the tab-index after the button is up to restore the button's accesssibility
2195 .attr( 'tabindex', this.tabIndex )
2196 .removeClass( 'oo-ui-buttonedElement-pressed' );
2197 // Stop listening for mouseup, since we only needed this once
2198 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
2199 };
2200
2201 /**
2202 * Set active state.
2203 *
2204 * @param {boolean} [value] Make button active
2205 * @chainable
2206 */
2207 OO.ui.ButtonedElement.prototype.setActive = function ( value ) {
2208 this.$button.toggleClass( 'oo-ui-buttonedElement-active', !!value );
2209 return this;
2210 };
2211 /**
2212 * Element that can be automatically clipped to visible boundaies.
2213 *
2214 * @abstract
2215 * @class
2216 *
2217 * @constructor
2218 * @param {jQuery} $clippable Nodes to clip, assigned to #$clippable
2219 * @param {Object} [config] Configuration options
2220 */
2221 OO.ui.ClippableElement = function OoUiClippableElement( $clippable, config ) {
2222 // Configuration initialization
2223 config = config || {};
2224
2225 // Properties
2226 this.$clippable = $clippable;
2227 this.clipping = false;
2228 this.clipped = false;
2229 this.$clippableContainer = null;
2230 this.$clippableScroller = null;
2231 this.$clippableWindow = null;
2232 this.idealWidth = null;
2233 this.idealHeight = null;
2234 this.onClippableContainerScrollHandler = OO.ui.bind( this.clip, this );
2235 this.onClippableWindowResizeHandler = OO.ui.bind( this.clip, this );
2236
2237 // Initialization
2238 this.$clippable.addClass( 'oo-ui-clippableElement-clippable' );
2239 };
2240
2241 /* Methods */
2242
2243 /**
2244 * Set clipping.
2245 *
2246 * @param {boolean} value Enable clipping
2247 * @chainable
2248 */
2249 OO.ui.ClippableElement.prototype.setClipping = function ( value ) {
2250 value = !!value;
2251
2252 if ( this.clipping !== value ) {
2253 this.clipping = value;
2254 if ( this.clipping ) {
2255 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
2256 // If the clippable container is the body, we have to listen to scroll events and check
2257 // jQuery.scrollTop on the window because of browser inconsistencies
2258 this.$clippableScroller = this.$clippableContainer.is( 'body' ) ?
2259 this.$( OO.ui.Element.getWindow( this.$clippableContainer ) ) :
2260 this.$clippableContainer;
2261 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
2262 this.$clippableWindow = this.$( this.getElementWindow() )
2263 .on( 'resize', this.onClippableWindowResizeHandler );
2264 // Initial clip after visible
2265 setTimeout( OO.ui.bind( this.clip, this ) );
2266 } else {
2267 this.$clippableContainer = null;
2268 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
2269 this.$clippableScroller = null;
2270 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
2271 this.$clippableWindow = null;
2272 }
2273 }
2274
2275 return this;
2276 };
2277
2278 /**
2279 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
2280 *
2281 * @return {boolean} Element will be clipped to the visible area
2282 */
2283 OO.ui.ClippableElement.prototype.isClipping = function () {
2284 return this.clipping;
2285 };
2286
2287 /**
2288 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
2289 *
2290 * @return {boolean} Part of the element is being clipped
2291 */
2292 OO.ui.ClippableElement.prototype.isClipped = function () {
2293 return this.clipped;
2294 };
2295
2296 /**
2297 * Set the ideal size.
2298 *
2299 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
2300 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
2301 */
2302 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
2303 this.idealWidth = width;
2304 this.idealHeight = height;
2305 };
2306
2307 /**
2308 * Clip element to visible boundaries and allow scrolling when needed.
2309 *
2310 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
2311 * overlapped by, the visible area of the nearest scrollable container.
2312 *
2313 * @chainable
2314 */
2315 OO.ui.ClippableElement.prototype.clip = function () {
2316 if ( !this.clipping ) {
2317 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
2318 return this;
2319 }
2320
2321 var buffer = 10,
2322 cOffset = this.$clippable.offset(),
2323 ccOffset = this.$clippableContainer.offset() || { 'top': 0, 'left': 0 },
2324 ccHeight = this.$clippableContainer.innerHeight() - buffer,
2325 ccWidth = this.$clippableContainer.innerWidth() - buffer,
2326 scrollTop = this.$clippableScroller.scrollTop(),
2327 scrollLeft = this.$clippableScroller.scrollLeft(),
2328 desiredWidth = ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
2329 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
2330 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
2331 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
2332 clipWidth = desiredWidth < naturalWidth,
2333 clipHeight = desiredHeight < naturalHeight;
2334
2335 if ( clipWidth ) {
2336 this.$clippable.css( { 'overflow-x': 'auto', 'width': desiredWidth } );
2337 } else {
2338 this.$clippable.css( { 'overflow-x': '', 'width': this.idealWidth || '' } );
2339 }
2340 if ( clipHeight ) {
2341 this.$clippable.css( { 'overflow-y': 'auto', 'height': desiredHeight } );
2342 } else {
2343 this.$clippable.css( { 'overflow-y': '', 'height': this.idealHeight || '' } );
2344 }
2345
2346 this.clipped = clipWidth || clipHeight;
2347
2348 return this;
2349 };
2350 /**
2351 * Element with named flags that can be added, removed, listed and checked.
2352 *
2353 * A flag, when set, adds a CSS class on the `$element` by combing `oo-ui-flaggableElement-` with
2354 * the flag name. Flags are primarily useful for styling.
2355 *
2356 * @abstract
2357 * @class
2358 *
2359 * @constructor
2360 * @param {Object} [config] Configuration options
2361 * @cfg {string[]} [flags=[]] Styling flags, e.g. 'primary', 'destructive' or 'constructive'
2362 */
2363 OO.ui.FlaggableElement = function OoUiFlaggableElement( config ) {
2364 // Config initialization
2365 config = config || {};
2366
2367 // Properties
2368 this.flags = {};
2369
2370 // Initialization
2371 this.setFlags( config.flags );
2372 };
2373
2374 /* Methods */
2375
2376 /**
2377 * Check if a flag is set.
2378 *
2379 * @param {string} flag Name of flag
2380 * @return {boolean} Has flag
2381 */
2382 OO.ui.FlaggableElement.prototype.hasFlag = function ( flag ) {
2383 return flag in this.flags;
2384 };
2385
2386 /**
2387 * Get the names of all flags set.
2388 *
2389 * @return {string[]} flags Flag names
2390 */
2391 OO.ui.FlaggableElement.prototype.getFlags = function () {
2392 return Object.keys( this.flags );
2393 };
2394
2395 /**
2396 * Clear all flags.
2397 *
2398 * @chainable
2399 */
2400 OO.ui.FlaggableElement.prototype.clearFlags = function () {
2401 var flag,
2402 classPrefix = 'oo-ui-flaggableElement-';
2403
2404 for ( flag in this.flags ) {
2405 delete this.flags[flag];
2406 this.$element.removeClass( classPrefix + flag );
2407 }
2408
2409 return this;
2410 };
2411
2412 /**
2413 * Add one or more flags.
2414 *
2415 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
2416 * keyed by flag name containing boolean set/remove instructions.
2417 * @chainable
2418 */
2419 OO.ui.FlaggableElement.prototype.setFlags = function ( flags ) {
2420 var i, len, flag,
2421 classPrefix = 'oo-ui-flaggableElement-';
2422
2423 if ( typeof flags === 'string' ) {
2424 // Set
2425 this.flags[flags] = true;
2426 this.$element.addClass( classPrefix + flags );
2427 } else if ( $.isArray( flags ) ) {
2428 for ( i = 0, len = flags.length; i < len; i++ ) {
2429 flag = flags[i];
2430 // Set
2431 this.flags[flag] = true;
2432 this.$element.addClass( classPrefix + flag );
2433 }
2434 } else if ( OO.isPlainObject( flags ) ) {
2435 for ( flag in flags ) {
2436 if ( flags[flag] ) {
2437 // Set
2438 this.flags[flag] = true;
2439 this.$element.addClass( classPrefix + flag );
2440 } else {
2441 // Remove
2442 delete this.flags[flag];
2443 this.$element.removeClass( classPrefix + flag );
2444 }
2445 }
2446 }
2447 return this;
2448 };
2449 /**
2450 * Element containing a sequence of child elements.
2451 *
2452 * @abstract
2453 * @class
2454 *
2455 * @constructor
2456 * @param {jQuery} $group Container node, assigned to #$group
2457 * @param {Object} [config] Configuration options
2458 */
2459 OO.ui.GroupElement = function OoUiGroupElement( $group, config ) {
2460 // Configuration
2461 config = config || {};
2462
2463 // Properties
2464 this.$group = $group;
2465 this.items = [];
2466 this.aggregateItemEvents = {};
2467 };
2468
2469 /* Methods */
2470
2471 /**
2472 * Get items.
2473 *
2474 * @return {OO.ui.Element[]} Items
2475 */
2476 OO.ui.GroupElement.prototype.getItems = function () {
2477 return this.items.slice( 0 );
2478 };
2479
2480 /**
2481 * Add an aggregate item event.
2482 *
2483 * Aggregated events are listened to on each item and then emitted by the group under a new name,
2484 * and with an additional leading parameter containing the item that emitted the original event.
2485 * Other arguments that were emitted from the original event are passed through.
2486 *
2487 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
2488 * event, use null value to remove aggregation
2489 * @throws {Error} If aggregation already exists
2490 */
2491 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
2492 var i, len, item, add, remove, itemEvent, groupEvent;
2493
2494 for ( itemEvent in events ) {
2495 groupEvent = events[itemEvent];
2496
2497 // Remove existing aggregated event
2498 if ( itemEvent in this.aggregateItemEvents ) {
2499 // Don't allow duplicate aggregations
2500 if ( groupEvent ) {
2501 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
2502 }
2503 // Remove event aggregation from existing items
2504 for ( i = 0, len = this.items.length; i < len; i++ ) {
2505 item = this.items[i];
2506 if ( item.connect && item.disconnect ) {
2507 remove = {};
2508 remove[itemEvent] = [ 'emit', groupEvent, item ];
2509 item.disconnect( this, remove );
2510 }
2511 }
2512 // Prevent future items from aggregating event
2513 delete this.aggregateItemEvents[itemEvent];
2514 }
2515
2516 // Add new aggregate event
2517 if ( groupEvent ) {
2518 // Make future items aggregate event
2519 this.aggregateItemEvents[itemEvent] = groupEvent;
2520 // Add event aggregation to existing items
2521 for ( i = 0, len = this.items.length; i < len; i++ ) {
2522 item = this.items[i];
2523 if ( item.connect && item.disconnect ) {
2524 add = {};
2525 add[itemEvent] = [ 'emit', groupEvent, item ];
2526 item.connect( this, add );
2527 }
2528 }
2529 }
2530 }
2531 };
2532
2533 /**
2534 * Add items.
2535 *
2536 * @param {OO.ui.Element[]} items Item
2537 * @param {number} [index] Index to insert items at
2538 * @chainable
2539 */
2540 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
2541 var i, len, item, event, events, currentIndex,
2542 itemElements = [];
2543
2544 for ( i = 0, len = items.length; i < len; i++ ) {
2545 item = items[i];
2546
2547 // Check if item exists then remove it first, effectively "moving" it
2548 currentIndex = $.inArray( item, this.items );
2549 if ( currentIndex >= 0 ) {
2550 this.removeItems( [ item ] );
2551 // Adjust index to compensate for removal
2552 if ( currentIndex < index ) {
2553 index--;
2554 }
2555 }
2556 // Add the item
2557 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
2558 events = {};
2559 for ( event in this.aggregateItemEvents ) {
2560 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
2561 }
2562 item.connect( this, events );
2563 }
2564 item.setElementGroup( this );
2565 itemElements.push( item.$element.get( 0 ) );
2566 }
2567
2568 if ( index === undefined || index < 0 || index >= this.items.length ) {
2569 this.$group.append( itemElements );
2570 this.items.push.apply( this.items, items );
2571 } else if ( index === 0 ) {
2572 this.$group.prepend( itemElements );
2573 this.items.unshift.apply( this.items, items );
2574 } else {
2575 this.items[index].$element.before( itemElements );
2576 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
2577 }
2578
2579 return this;
2580 };
2581
2582 /**
2583 * Remove items.
2584 *
2585 * Items will be detached, not removed, so they can be used later.
2586 *
2587 * @param {OO.ui.Element[]} items Items to remove
2588 * @chainable
2589 */
2590 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
2591 var i, len, item, index, remove, itemEvent;
2592
2593 // Remove specific items
2594 for ( i = 0, len = items.length; i < len; i++ ) {
2595 item = items[i];
2596 index = $.inArray( item, this.items );
2597 if ( index !== -1 ) {
2598 if (
2599 item.connect && item.disconnect &&
2600 !$.isEmptyObject( this.aggregateItemEvents )
2601 ) {
2602 remove = {};
2603 if ( itemEvent in this.aggregateItemEvents ) {
2604 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
2605 }
2606 item.disconnect( this, remove );
2607 }
2608 item.setElementGroup( null );
2609 this.items.splice( index, 1 );
2610 item.$element.detach();
2611 }
2612 }
2613
2614 return this;
2615 };
2616
2617 /**
2618 * Clear all items.
2619 *
2620 * Items will be detached, not removed, so they can be used later.
2621 *
2622 * @chainable
2623 */
2624 OO.ui.GroupElement.prototype.clearItems = function () {
2625 var i, len, item, remove, itemEvent;
2626
2627 // Remove all items
2628 for ( i = 0, len = this.items.length; i < len; i++ ) {
2629 item = this.items[i];
2630 if (
2631 item.connect && item.disconnect &&
2632 !$.isEmptyObject( this.aggregateItemEvents )
2633 ) {
2634 remove = {};
2635 if ( itemEvent in this.aggregateItemEvents ) {
2636 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
2637 }
2638 item.disconnect( this, remove );
2639 }
2640 item.setElementGroup( null );
2641 item.$element.detach();
2642 }
2643
2644 this.items = [];
2645 return this;
2646 };
2647 /**
2648 * Element containing an icon.
2649 *
2650 * @abstract
2651 * @class
2652 *
2653 * @constructor
2654 * @param {jQuery} $icon Icon node, assigned to #$icon
2655 * @param {Object} [config] Configuration options
2656 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
2657 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2658 * language
2659 */
2660 OO.ui.IconedElement = function OoUiIconedElement( $icon, config ) {
2661 // Config intialization
2662 config = config || {};
2663
2664 // Properties
2665 this.$icon = $icon;
2666 this.icon = null;
2667
2668 // Initialization
2669 this.$icon.addClass( 'oo-ui-iconedElement-icon' );
2670 this.setIcon( config.icon || this.constructor.static.icon );
2671 };
2672
2673 /* Setup */
2674
2675 OO.initClass( OO.ui.IconedElement );
2676
2677 /* Static Properties */
2678
2679 /**
2680 * Icon.
2681 *
2682 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
2683 *
2684 * For i18n purposes, this property can be an object containing a `default` icon name property and
2685 * additional icon names keyed by language code.
2686 *
2687 * Example of i18n icon definition:
2688 * { 'default': 'bold-a', 'en': 'bold-b', 'de': 'bold-f' }
2689 *
2690 * @static
2691 * @inheritable
2692 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
2693 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2694 * language
2695 */
2696 OO.ui.IconedElement.static.icon = null;
2697
2698 /* Methods */
2699
2700 /**
2701 * Set icon.
2702 *
2703 * @param {Object|string} icon Symbolic icon name, or map of icon names keyed by language ID;
2704 * use the 'default' key to specify the icon to be used when there is no icon in the user's
2705 * language
2706 * @chainable
2707 */
2708 OO.ui.IconedElement.prototype.setIcon = function ( icon ) {
2709 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
2710
2711 if ( this.icon ) {
2712 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
2713 }
2714 if ( typeof icon === 'string' ) {
2715 icon = icon.trim();
2716 if ( icon.length ) {
2717 this.$icon.addClass( 'oo-ui-icon-' + icon );
2718 this.icon = icon;
2719 }
2720 }
2721 this.$element.toggleClass( 'oo-ui-iconedElement', !!this.icon );
2722
2723 return this;
2724 };
2725
2726 /**
2727 * Get icon.
2728 *
2729 * @return {string} Icon
2730 */
2731 OO.ui.IconedElement.prototype.getIcon = function () {
2732 return this.icon;
2733 };
2734 /**
2735 * Element containing an indicator.
2736 *
2737 * @abstract
2738 * @class
2739 *
2740 * @constructor
2741 * @param {jQuery} $indicator Indicator node, assigned to #$indicator
2742 * @param {Object} [config] Configuration options
2743 * @cfg {string} [indicator] Symbolic indicator name
2744 * @cfg {string} [indicatorTitle] Indicator title text or a function that return text
2745 */
2746 OO.ui.IndicatedElement = function OoUiIndicatedElement( $indicator, config ) {
2747 // Config intialization
2748 config = config || {};
2749
2750 // Properties
2751 this.$indicator = $indicator;
2752 this.indicator = null;
2753 this.indicatorLabel = null;
2754
2755 // Initialization
2756 this.$indicator.addClass( 'oo-ui-indicatedElement-indicator' );
2757 this.setIndicator( config.indicator || this.constructor.static.indicator );
2758 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
2759 };
2760
2761 /* Setup */
2762
2763 OO.initClass( OO.ui.IndicatedElement );
2764
2765 /* Static Properties */
2766
2767 /**
2768 * indicator.
2769 *
2770 * @static
2771 * @inheritable
2772 * @property {string|null} Symbolic indicator name or null for no indicator
2773 */
2774 OO.ui.IndicatedElement.static.indicator = null;
2775
2776 /**
2777 * Indicator title.
2778 *
2779 * @static
2780 * @inheritable
2781 * @property {string|Function|null} Indicator title text, a function that return text or null for no
2782 * indicator title
2783 */
2784 OO.ui.IndicatedElement.static.indicatorTitle = null;
2785
2786 /* Methods */
2787
2788 /**
2789 * Set indicator.
2790 *
2791 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
2792 * @chainable
2793 */
2794 OO.ui.IndicatedElement.prototype.setIndicator = function ( indicator ) {
2795 if ( this.indicator ) {
2796 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
2797 this.indicator = null;
2798 }
2799 if ( typeof indicator === 'string' ) {
2800 indicator = indicator.trim();
2801 if ( indicator.length ) {
2802 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
2803 this.indicator = indicator;
2804 }
2805 }
2806 this.$element.toggleClass( 'oo-ui-indicatedElement', !!this.indicator );
2807
2808 return this;
2809 };
2810
2811 /**
2812 * Set indicator label.
2813 *
2814 * @param {string|Function|null} indicator Indicator title text, a function that return text or null
2815 * for no indicator title
2816 * @chainable
2817 */
2818 OO.ui.IndicatedElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
2819 this.indicatorTitle = indicatorTitle = OO.ui.resolveMsg( indicatorTitle );
2820
2821 if ( typeof indicatorTitle === 'string' && indicatorTitle.length ) {
2822 this.$indicator.attr( 'title', indicatorTitle );
2823 } else {
2824 this.$indicator.removeAttr( 'title' );
2825 }
2826
2827 return this;
2828 };
2829
2830 /**
2831 * Get indicator.
2832 *
2833 * @return {string} title Symbolic name of indicator
2834 */
2835 OO.ui.IndicatedElement.prototype.getIndicator = function () {
2836 return this.indicator;
2837 };
2838
2839 /**
2840 * Get indicator title.
2841 *
2842 * @return {string} Indicator title text
2843 */
2844 OO.ui.IndicatedElement.prototype.getIndicatorTitle = function () {
2845 return this.indicatorTitle;
2846 };
2847 /**
2848 * Element containing a label.
2849 *
2850 * @abstract
2851 * @class
2852 *
2853 * @constructor
2854 * @param {jQuery} $label Label node, assigned to #$label
2855 * @param {Object} [config] Configuration options
2856 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
2857 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
2858 */
2859 OO.ui.LabeledElement = function OoUiLabeledElement( $label, config ) {
2860 // Config intialization
2861 config = config || {};
2862
2863 // Properties
2864 this.$label = $label;
2865 this.label = null;
2866
2867 // Initialization
2868 this.$label.addClass( 'oo-ui-labeledElement-label' );
2869 this.setLabel( config.label || this.constructor.static.label );
2870 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
2871 };
2872
2873 /* Setup */
2874
2875 OO.initClass( OO.ui.LabeledElement );
2876
2877 /* Static Properties */
2878
2879 /**
2880 * Label.
2881 *
2882 * @static
2883 * @inheritable
2884 * @property {string|Function|null} Label text; a function that returns a nodes or text; or null for
2885 * no label
2886 */
2887 OO.ui.LabeledElement.static.label = null;
2888
2889 /* Methods */
2890
2891 /**
2892 * Set the label.
2893 *
2894 * An empty string will result in the label being hidden. A string containing only whitespace will
2895 * be converted to a single &nbsp;
2896 *
2897 * @param {jQuery|string|Function|null} label Label nodes; text; a function that retuns nodes or
2898 * text; or null for no label
2899 * @chainable
2900 */
2901 OO.ui.LabeledElement.prototype.setLabel = function ( label ) {
2902 var empty = false;
2903
2904 this.label = label = OO.ui.resolveMsg( label ) || null;
2905 if ( typeof label === 'string' && label.length ) {
2906 if ( label.match( /^\s*$/ ) ) {
2907 // Convert whitespace only string to a single non-breaking space
2908 this.$label.html( '&nbsp;' );
2909 } else {
2910 this.$label.text( label );
2911 }
2912 } else if ( label instanceof jQuery ) {
2913 this.$label.empty().append( label );
2914 } else {
2915 this.$label.empty();
2916 empty = true;
2917 }
2918 this.$element.toggleClass( 'oo-ui-labeledElement', !empty );
2919 this.$label.css( 'display', empty ? 'none' : '' );
2920
2921 return this;
2922 };
2923
2924 /**
2925 * Get the label.
2926 *
2927 * @return {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
2928 * text; or null for no label
2929 */
2930 OO.ui.LabeledElement.prototype.getLabel = function () {
2931 return this.label;
2932 };
2933
2934 /**
2935 * Fit the label.
2936 *
2937 * @chainable
2938 */
2939 OO.ui.LabeledElement.prototype.fitLabel = function () {
2940 if ( this.$label.autoEllipsis && this.autoFitLabel ) {
2941 this.$label.autoEllipsis( { 'hasSpan': false, 'tooltip': true } );
2942 }
2943 return this;
2944 };
2945 /**
2946 * Popuppable element.
2947 *
2948 * @abstract
2949 * @class
2950 *
2951 * @constructor
2952 * @param {Object} [config] Configuration options
2953 * @cfg {number} [popupWidth=320] Width of popup
2954 * @cfg {number} [popupHeight] Height of popup
2955 * @cfg {Object} [popup] Configuration to pass to popup
2956 */
2957 OO.ui.PopuppableElement = function OoUiPopuppableElement( config ) {
2958 // Configuration initialization
2959 config = $.extend( { 'popupWidth': 320 }, config );
2960
2961 // Properties
2962 this.popup = new OO.ui.PopupWidget( $.extend(
2963 { 'align': 'center', 'autoClose': true },
2964 config.popup,
2965 { '$': this.$, '$autoCloseIgnore': this.$element }
2966 ) );
2967 this.popupWidth = config.popupWidth;
2968 this.popupHeight = config.popupHeight;
2969 };
2970
2971 /* Methods */
2972
2973 /**
2974 * Get popup.
2975 *
2976 * @return {OO.ui.PopupWidget} Popup widget
2977 */
2978 OO.ui.PopuppableElement.prototype.getPopup = function () {
2979 return this.popup;
2980 };
2981
2982 /**
2983 * Show popup.
2984 */
2985 OO.ui.PopuppableElement.prototype.showPopup = function () {
2986 this.popup.show().display( this.popupWidth, this.popupHeight );
2987 };
2988
2989 /**
2990 * Hide popup.
2991 */
2992 OO.ui.PopuppableElement.prototype.hidePopup = function () {
2993 this.popup.hide();
2994 };
2995 /**
2996 * Element with a title.
2997 *
2998 * @abstract
2999 * @class
3000 *
3001 * @constructor
3002 * @param {jQuery} $label Titled node, assigned to #$titled
3003 * @param {Object} [config] Configuration options
3004 * @cfg {string|Function} [title] Title text or a function that returns text
3005 */
3006 OO.ui.TitledElement = function OoUiTitledElement( $titled, config ) {
3007 // Config intialization
3008 config = config || {};
3009
3010 // Properties
3011 this.$titled = $titled;
3012 this.title = null;
3013
3014 // Initialization
3015 this.setTitle( config.title || this.constructor.static.title );
3016 };
3017
3018 /* Setup */
3019
3020 OO.initClass( OO.ui.TitledElement );
3021
3022 /* Static Properties */
3023
3024 /**
3025 * Title.
3026 *
3027 * @static
3028 * @inheritable
3029 * @property {string|Function} Title text or a function that returns text
3030 */
3031 OO.ui.TitledElement.static.title = null;
3032
3033 /* Methods */
3034
3035 /**
3036 * Set title.
3037 *
3038 * @param {string|Function|null} title Title text, a function that returns text or null for no title
3039 * @chainable
3040 */
3041 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
3042 this.title = title = OO.ui.resolveMsg( title ) || null;
3043
3044 if ( typeof title === 'string' && title.length ) {
3045 this.$titled.attr( 'title', title );
3046 } else {
3047 this.$titled.removeAttr( 'title' );
3048 }
3049
3050 return this;
3051 };
3052
3053 /**
3054 * Get title.
3055 *
3056 * @return {string} Title string
3057 */
3058 OO.ui.TitledElement.prototype.getTitle = function () {
3059 return this.title;
3060 };
3061 /**
3062 * Generic toolbar tool.
3063 *
3064 * @abstract
3065 * @class
3066 * @extends OO.ui.Widget
3067 * @mixins OO.ui.IconedElement
3068 *
3069 * @constructor
3070 * @param {OO.ui.ToolGroup} toolGroup
3071 * @param {Object} [config] Configuration options
3072 * @cfg {string|Function} [title] Title text or a function that returns text
3073 */
3074 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
3075 // Config intialization
3076 config = config || {};
3077
3078 // Parent constructor
3079 OO.ui.Tool.super.call( this, config );
3080
3081 // Mixin constructors
3082 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
3083
3084 // Properties
3085 this.toolGroup = toolGroup;
3086 this.toolbar = this.toolGroup.getToolbar();
3087 this.active = false;
3088 this.$title = this.$( '<span>' );
3089 this.$link = this.$( '<a>' );
3090 this.title = null;
3091
3092 // Events
3093 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
3094
3095 // Initialization
3096 this.$title.addClass( 'oo-ui-tool-title' );
3097 this.$link
3098 .addClass( 'oo-ui-tool-link' )
3099 .append( this.$icon, this.$title );
3100 this.$element
3101 .data( 'oo-ui-tool', this )
3102 .addClass(
3103 'oo-ui-tool ' + 'oo-ui-tool-name-' +
3104 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
3105 )
3106 .append( this.$link );
3107 this.setTitle( config.title || this.constructor.static.title );
3108 };
3109
3110 /* Setup */
3111
3112 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
3113 OO.mixinClass( OO.ui.Tool, OO.ui.IconedElement );
3114
3115 /* Events */
3116
3117 /**
3118 * @event select
3119 */
3120
3121 /* Static Properties */
3122
3123 /**
3124 * @static
3125 * @inheritdoc
3126 */
3127 OO.ui.Tool.static.tagName = 'span';
3128
3129 /**
3130 * Symbolic name of tool.
3131 *
3132 * @abstract
3133 * @static
3134 * @inheritable
3135 * @property {string}
3136 */
3137 OO.ui.Tool.static.name = '';
3138
3139 /**
3140 * Tool group.
3141 *
3142 * @abstract
3143 * @static
3144 * @inheritable
3145 * @property {string}
3146 */
3147 OO.ui.Tool.static.group = '';
3148
3149 /**
3150 * Tool title.
3151 *
3152 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
3153 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
3154 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
3155 * appended to the title if the tool is part of a bar tool group.
3156 *
3157 * @abstract
3158 * @static
3159 * @inheritable
3160 * @property {string|Function} Title text or a function that returns text
3161 */
3162 OO.ui.Tool.static.title = '';
3163
3164 /**
3165 * Tool can be automatically added to catch-all groups.
3166 *
3167 * @static
3168 * @inheritable
3169 * @property {boolean}
3170 */
3171 OO.ui.Tool.static.autoAddToCatchall = true;
3172
3173 /**
3174 * Tool can be automatically added to named groups.
3175 *
3176 * @static
3177 * @property {boolean}
3178 * @inheritable
3179 */
3180 OO.ui.Tool.static.autoAddToGroup = true;
3181
3182 /**
3183 * Check if this tool is compatible with given data.
3184 *
3185 * @static
3186 * @inheritable
3187 * @param {Mixed} data Data to check
3188 * @return {boolean} Tool can be used with data
3189 */
3190 OO.ui.Tool.static.isCompatibleWith = function () {
3191 return false;
3192 };
3193
3194 /* Methods */
3195
3196 /**
3197 * Handle the toolbar state being updated.
3198 *
3199 * This is an abstract method that must be overridden in a concrete subclass.
3200 *
3201 * @abstract
3202 */
3203 OO.ui.Tool.prototype.onUpdateState = function () {
3204 throw new Error(
3205 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
3206 );
3207 };
3208
3209 /**
3210 * Handle the tool being selected.
3211 *
3212 * This is an abstract method that must be overridden in a concrete subclass.
3213 *
3214 * @abstract
3215 */
3216 OO.ui.Tool.prototype.onSelect = function () {
3217 throw new Error(
3218 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
3219 );
3220 };
3221
3222 /**
3223 * Check if the button is active.
3224 *
3225 * @param {boolean} Button is active
3226 */
3227 OO.ui.Tool.prototype.isActive = function () {
3228 return this.active;
3229 };
3230
3231 /**
3232 * Make the button appear active or inactive.
3233 *
3234 * @param {boolean} state Make button appear active
3235 */
3236 OO.ui.Tool.prototype.setActive = function ( state ) {
3237 this.active = !!state;
3238 if ( this.active ) {
3239 this.$element.addClass( 'oo-ui-tool-active' );
3240 } else {
3241 this.$element.removeClass( 'oo-ui-tool-active' );
3242 }
3243 };
3244
3245 /**
3246 * Get the tool title.
3247 *
3248 * @param {string|Function} title Title text or a function that returns text
3249 * @chainable
3250 */
3251 OO.ui.Tool.prototype.setTitle = function ( title ) {
3252 this.title = OO.ui.resolveMsg( title );
3253 this.updateTitle();
3254 return this;
3255 };
3256
3257 /**
3258 * Get the tool title.
3259 *
3260 * @return {string} Title text
3261 */
3262 OO.ui.Tool.prototype.getTitle = function () {
3263 return this.title;
3264 };
3265
3266 /**
3267 * Get the tool's symbolic name.
3268 *
3269 * @return {string} Symbolic name of tool
3270 */
3271 OO.ui.Tool.prototype.getName = function () {
3272 return this.constructor.static.name;
3273 };
3274
3275 /**
3276 * Update the title.
3277 */
3278 OO.ui.Tool.prototype.updateTitle = function () {
3279 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
3280 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
3281 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
3282 tooltipParts = [];
3283
3284 this.$title.empty()
3285 .text( this.title )
3286 .append(
3287 this.$( '<span>' )
3288 .addClass( 'oo-ui-tool-accel' )
3289 .text( accel )
3290 );
3291
3292 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
3293 tooltipParts.push( this.title );
3294 }
3295 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
3296 tooltipParts.push( accel );
3297 }
3298 if ( tooltipParts.length ) {
3299 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
3300 } else {
3301 this.$link.removeAttr( 'title' );
3302 }
3303 };
3304
3305 /**
3306 * Destroy tool.
3307 */
3308 OO.ui.Tool.prototype.destroy = function () {
3309 this.toolbar.disconnect( this );
3310 this.$element.remove();
3311 };
3312 /**
3313 * Collection of tool groups.
3314 *
3315 * @class
3316 * @extends OO.ui.Element
3317 * @mixins OO.EventEmitter
3318 * @mixins OO.ui.GroupElement
3319 *
3320 * @constructor
3321 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
3322 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
3323 * @param {Object} [config] Configuration options
3324 * @cfg {boolean} [actions] Add an actions section opposite to the tools
3325 * @cfg {boolean} [shadow] Add a shadow below the toolbar
3326 */
3327 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
3328 // Configuration initialization
3329 config = config || {};
3330
3331 // Parent constructor
3332 OO.ui.Toolbar.super.call( this, config );
3333
3334 // Mixin constructors
3335 OO.EventEmitter.call( this );
3336 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
3337
3338 // Properties
3339 this.toolFactory = toolFactory;
3340 this.toolGroupFactory = toolGroupFactory;
3341 this.groups = [];
3342 this.tools = {};
3343 this.$bar = this.$( '<div>' );
3344 this.$actions = this.$( '<div>' );
3345 this.initialized = false;
3346
3347 // Events
3348 this.$element
3349 .add( this.$bar ).add( this.$group ).add( this.$actions )
3350 .on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
3351
3352 // Initialization
3353 this.$group.addClass( 'oo-ui-toolbar-tools' );
3354 this.$bar.addClass( 'oo-ui-toolbar-bar' ).append( this.$group );
3355 if ( config.actions ) {
3356 this.$actions.addClass( 'oo-ui-toolbar-actions' );
3357 this.$bar.append( this.$actions );
3358 }
3359 this.$bar.append( '<div style="clear:both"></div>' );
3360 if ( config.shadow ) {
3361 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
3362 }
3363 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
3364 };
3365
3366 /* Setup */
3367
3368 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
3369 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
3370 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
3371
3372 /* Methods */
3373
3374 /**
3375 * Get the tool factory.
3376 *
3377 * @return {OO.ui.ToolFactory} Tool factory
3378 */
3379 OO.ui.Toolbar.prototype.getToolFactory = function () {
3380 return this.toolFactory;
3381 };
3382
3383 /**
3384 * Get the tool group factory.
3385 *
3386 * @return {OO.Factory} Tool group factory
3387 */
3388 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
3389 return this.toolGroupFactory;
3390 };
3391
3392 /**
3393 * Handles mouse down events.
3394 *
3395 * @param {jQuery.Event} e Mouse down event
3396 */
3397 OO.ui.Toolbar.prototype.onMouseDown = function ( e ) {
3398 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
3399 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
3400 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
3401 return false;
3402 }
3403 };
3404
3405 /**
3406 * Sets up handles and preloads required information for the toolbar to work.
3407 * This must be called immediately after it is attached to a visible document.
3408 */
3409 OO.ui.Toolbar.prototype.initialize = function () {
3410 this.initialized = true;
3411 };
3412
3413 /**
3414 * Setup toolbar.
3415 *
3416 * Tools can be specified in the following ways:
3417 *
3418 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3419 * - All tools in a group: `{ 'group': 'group-name' }`
3420 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
3421 *
3422 * @param {Object.<string,Array>} groups List of tool group configurations
3423 * @param {Array|string} [groups.include] Tools to include
3424 * @param {Array|string} [groups.exclude] Tools to exclude
3425 * @param {Array|string} [groups.promote] Tools to promote to the beginning
3426 * @param {Array|string} [groups.demote] Tools to demote to the end
3427 */
3428 OO.ui.Toolbar.prototype.setup = function ( groups ) {
3429 var i, len, type, group,
3430 items = [],
3431 defaultType = 'bar';
3432
3433 // Cleanup previous groups
3434 this.reset();
3435
3436 // Build out new groups
3437 for ( i = 0, len = groups.length; i < len; i++ ) {
3438 group = groups[i];
3439 if ( group.include === '*' ) {
3440 // Apply defaults to catch-all groups
3441 if ( group.type === undefined ) {
3442 group.type = 'list';
3443 }
3444 if ( group.label === undefined ) {
3445 group.label = 'ooui-toolbar-more';
3446 }
3447 }
3448 // Check type has been registered
3449 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
3450 items.push(
3451 this.getToolGroupFactory().create( type, this, $.extend( { '$': this.$ }, group ) )
3452 );
3453 }
3454 this.addItems( items );
3455 };
3456
3457 /**
3458 * Remove all tools and groups from the toolbar.
3459 */
3460 OO.ui.Toolbar.prototype.reset = function () {
3461 var i, len;
3462
3463 this.groups = [];
3464 this.tools = {};
3465 for ( i = 0, len = this.items.length; i < len; i++ ) {
3466 this.items[i].destroy();
3467 }
3468 this.clearItems();
3469 };
3470
3471 /**
3472 * Destroys toolbar, removing event handlers and DOM elements.
3473 *
3474 * Call this whenever you are done using a toolbar.
3475 */
3476 OO.ui.Toolbar.prototype.destroy = function () {
3477 this.reset();
3478 this.$element.remove();
3479 };
3480
3481 /**
3482 * Check if tool has not been used yet.
3483 *
3484 * @param {string} name Symbolic name of tool
3485 * @return {boolean} Tool is available
3486 */
3487 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
3488 return !this.tools[name];
3489 };
3490
3491 /**
3492 * Prevent tool from being used again.
3493 *
3494 * @param {OO.ui.Tool} tool Tool to reserve
3495 */
3496 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
3497 this.tools[tool.getName()] = tool;
3498 };
3499
3500 /**
3501 * Allow tool to be used again.
3502 *
3503 * @param {OO.ui.Tool} tool Tool to release
3504 */
3505 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
3506 delete this.tools[tool.getName()];
3507 };
3508
3509 /**
3510 * Get accelerator label for tool.
3511 *
3512 * This is a stub that should be overridden to provide access to accelerator information.
3513 *
3514 * @param {string} name Symbolic name of tool
3515 * @return {string|undefined} Tool accelerator label if available
3516 */
3517 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
3518 return undefined;
3519 };
3520 /**
3521 * Factory for tools.
3522 *
3523 * @class
3524 * @extends OO.Factory
3525 * @constructor
3526 */
3527 OO.ui.ToolFactory = function OoUiToolFactory() {
3528 // Parent constructor
3529 OO.ui.ToolFactory.super.call( this );
3530 };
3531
3532 /* Setup */
3533
3534 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3535
3536 /* Methods */
3537
3538 /** */
3539 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3540 var i, len, included, promoted, demoted,
3541 auto = [],
3542 used = {};
3543
3544 // Collect included and not excluded tools
3545 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3546
3547 // Promotion
3548 promoted = this.extract( promote, used );
3549 demoted = this.extract( demote, used );
3550
3551 // Auto
3552 for ( i = 0, len = included.length; i < len; i++ ) {
3553 if ( !used[included[i]] ) {
3554 auto.push( included[i] );
3555 }
3556 }
3557
3558 return promoted.concat( auto ).concat( demoted );
3559 };
3560
3561 /**
3562 * Get a flat list of names from a list of names or groups.
3563 *
3564 * Tools can be specified in the following ways:
3565 *
3566 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3567 * - All tools in a group: `{ 'group': 'group-name' }`
3568 * - All tools: `'*'`
3569 *
3570 * @private
3571 * @param {Array|string} collection List of tools
3572 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3573 * names will be added as properties
3574 * @return {string[]} List of extracted names
3575 */
3576 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3577 var i, len, item, name, tool,
3578 names = [];
3579
3580 if ( collection === '*' ) {
3581 for ( name in this.registry ) {
3582 tool = this.registry[name];
3583 if (
3584 // Only add tools by group name when auto-add is enabled
3585 tool.static.autoAddToCatchall &&
3586 // Exclude already used tools
3587 ( !used || !used[name] )
3588 ) {
3589 names.push( name );
3590 if ( used ) {
3591 used[name] = true;
3592 }
3593 }
3594 }
3595 } else if ( $.isArray( collection ) ) {
3596 for ( i = 0, len = collection.length; i < len; i++ ) {
3597 item = collection[i];
3598 // Allow plain strings as shorthand for named tools
3599 if ( typeof item === 'string' ) {
3600 item = { 'name': item };
3601 }
3602 if ( OO.isPlainObject( item ) ) {
3603 if ( item.group ) {
3604 for ( name in this.registry ) {
3605 tool = this.registry[name];
3606 if (
3607 // Include tools with matching group
3608 tool.static.group === item.group &&
3609 // Only add tools by group name when auto-add is enabled
3610 tool.static.autoAddToGroup &&
3611 // Exclude already used tools
3612 ( !used || !used[name] )
3613 ) {
3614 names.push( name );
3615 if ( used ) {
3616 used[name] = true;
3617 }
3618 }
3619 }
3620 // Include tools with matching name and exclude already used tools
3621 } else if ( item.name && ( !used || !used[item.name] ) ) {
3622 names.push( item.name );
3623 if ( used ) {
3624 used[item.name] = true;
3625 }
3626 }
3627 }
3628 }
3629 }
3630 return names;
3631 };
3632 /**
3633 * Collection of tools.
3634 *
3635 * Tools can be specified in the following ways:
3636 *
3637 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3638 * - All tools in a group: `{ 'group': 'group-name' }`
3639 * - All tools: `'*'`
3640 *
3641 * @abstract
3642 * @class
3643 * @extends OO.ui.Widget
3644 * @mixins OO.ui.GroupElement
3645 *
3646 * @constructor
3647 * @param {OO.ui.Toolbar} toolbar
3648 * @param {Object} [config] Configuration options
3649 * @cfg {Array|string} [include=[]] List of tools to include
3650 * @cfg {Array|string} [exclude=[]] List of tools to exclude
3651 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
3652 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
3653 */
3654 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
3655 // Configuration initialization
3656 config = config || {};
3657
3658 // Parent constructor
3659 OO.ui.ToolGroup.super.call( this, config );
3660
3661 // Mixin constructors
3662 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
3663
3664 // Properties
3665 this.toolbar = toolbar;
3666 this.tools = {};
3667 this.pressed = null;
3668 this.autoDisabled = false;
3669 this.include = config.include || [];
3670 this.exclude = config.exclude || [];
3671 this.promote = config.promote || [];
3672 this.demote = config.demote || [];
3673 this.onCapturedMouseUpHandler = OO.ui.bind( this.onCapturedMouseUp, this );
3674
3675 // Events
3676 this.$element.on( {
3677 'mousedown': OO.ui.bind( this.onMouseDown, this ),
3678 'mouseup': OO.ui.bind( this.onMouseUp, this ),
3679 'mouseover': OO.ui.bind( this.onMouseOver, this ),
3680 'mouseout': OO.ui.bind( this.onMouseOut, this )
3681 } );
3682 this.toolbar.getToolFactory().connect( this, { 'register': 'onToolFactoryRegister' } );
3683 this.aggregate( { 'disable': 'itemDisable' } );
3684 this.connect( this, { 'itemDisable': 'updateDisabled' } );
3685
3686 // Initialization
3687 this.$group.addClass( 'oo-ui-toolGroup-tools' );
3688 this.$element
3689 .addClass( 'oo-ui-toolGroup' )
3690 .append( this.$group );
3691 this.populate();
3692 };
3693
3694 /* Setup */
3695
3696 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
3697 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
3698
3699 /* Events */
3700
3701 /**
3702 * @event update
3703 */
3704
3705 /* Static Properties */
3706
3707 /**
3708 * Show labels in tooltips.
3709 *
3710 * @static
3711 * @inheritable
3712 * @property {boolean}
3713 */
3714 OO.ui.ToolGroup.static.titleTooltips = false;
3715
3716 /**
3717 * Show acceleration labels in tooltips.
3718 *
3719 * @static
3720 * @inheritable
3721 * @property {boolean}
3722 */
3723 OO.ui.ToolGroup.static.accelTooltips = false;
3724
3725 /**
3726 * Automatically disable the toolgroup when all tools are disabled
3727 *
3728 * @static
3729 * @inheritable
3730 * @property {boolean}
3731 */
3732 OO.ui.ToolGroup.static.autoDisable = true;
3733
3734 /* Methods */
3735
3736 /**
3737 * @inheritdoc
3738 */
3739 OO.ui.ToolGroup.prototype.isDisabled = function () {
3740 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
3741 };
3742
3743 /**
3744 * @inheritdoc
3745 */
3746 OO.ui.ToolGroup.prototype.updateDisabled = function () {
3747 var i, item, allDisabled = true;
3748
3749 if ( this.constructor.static.autoDisable ) {
3750 for ( i = this.items.length - 1; i >= 0; i-- ) {
3751 item = this.items[i];
3752 if ( !item.isDisabled() ) {
3753 allDisabled = false;
3754 break;
3755 }
3756 }
3757 this.autoDisabled = allDisabled;
3758 }
3759 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
3760 };
3761
3762 /**
3763 * Handle mouse down events.
3764 *
3765 * @param {jQuery.Event} e Mouse down event
3766 */
3767 OO.ui.ToolGroup.prototype.onMouseDown = function ( e ) {
3768 if ( !this.isDisabled() && e.which === 1 ) {
3769 this.pressed = this.getTargetTool( e );
3770 if ( this.pressed ) {
3771 this.pressed.setActive( true );
3772 this.getElementDocument().addEventListener(
3773 'mouseup', this.onCapturedMouseUpHandler, true
3774 );
3775 return false;
3776 }
3777 }
3778 };
3779
3780 /**
3781 * Handle captured mouse up events.
3782 *
3783 * @param {Event} e Mouse up event
3784 */
3785 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
3786 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
3787 // onMouseUp may be called a second time, depending on where the mouse is when the button is
3788 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
3789 this.onMouseUp( e );
3790 };
3791
3792 /**
3793 * Handle mouse up events.
3794 *
3795 * @param {jQuery.Event} e Mouse up event
3796 */
3797 OO.ui.ToolGroup.prototype.onMouseUp = function ( e ) {
3798 var tool = this.getTargetTool( e );
3799
3800 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
3801 this.pressed.onSelect();
3802 }
3803
3804 this.pressed = null;
3805 return false;
3806 };
3807
3808 /**
3809 * Handle mouse over events.
3810 *
3811 * @param {jQuery.Event} e Mouse over event
3812 */
3813 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
3814 var tool = this.getTargetTool( e );
3815
3816 if ( this.pressed && this.pressed === tool ) {
3817 this.pressed.setActive( true );
3818 }
3819 };
3820
3821 /**
3822 * Handle mouse out events.
3823 *
3824 * @param {jQuery.Event} e Mouse out event
3825 */
3826 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
3827 var tool = this.getTargetTool( e );
3828
3829 if ( this.pressed && this.pressed === tool ) {
3830 this.pressed.setActive( false );
3831 }
3832 };
3833
3834 /**
3835 * Get the closest tool to a jQuery.Event.
3836 *
3837 * Only tool links are considered, which prevents other elements in the tool such as popups from
3838 * triggering tool group interactions.
3839 *
3840 * @private
3841 * @param {jQuery.Event} e
3842 * @return {OO.ui.Tool|null} Tool, `null` if none was found
3843 */
3844 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
3845 var tool,
3846 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
3847
3848 if ( $item.length ) {
3849 tool = $item.parent().data( 'oo-ui-tool' );
3850 }
3851
3852 return tool && !tool.isDisabled() ? tool : null;
3853 };
3854
3855 /**
3856 * Handle tool registry register events.
3857 *
3858 * If a tool is registered after the group is created, we must repopulate the list to account for:
3859 *
3860 * - a tool being added that may be included
3861 * - a tool already included being overridden
3862 *
3863 * @param {string} name Symbolic name of tool
3864 */
3865 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
3866 this.populate();
3867 };
3868
3869 /**
3870 * Get the toolbar this group is in.
3871 *
3872 * @return {OO.ui.Toolbar} Toolbar of group
3873 */
3874 OO.ui.ToolGroup.prototype.getToolbar = function () {
3875 return this.toolbar;
3876 };
3877
3878 /**
3879 * Add and remove tools based on configuration.
3880 */
3881 OO.ui.ToolGroup.prototype.populate = function () {
3882 var i, len, name, tool,
3883 toolFactory = this.toolbar.getToolFactory(),
3884 names = {},
3885 add = [],
3886 remove = [],
3887 list = this.toolbar.getToolFactory().getTools(
3888 this.include, this.exclude, this.promote, this.demote
3889 );
3890
3891 // Build a list of needed tools
3892 for ( i = 0, len = list.length; i < len; i++ ) {
3893 name = list[i];
3894 if (
3895 // Tool exists
3896 toolFactory.lookup( name ) &&
3897 // Tool is available or is already in this group
3898 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
3899 ) {
3900 tool = this.tools[name];
3901 if ( !tool ) {
3902 // Auto-initialize tools on first use
3903 this.tools[name] = tool = toolFactory.create( name, this );
3904 tool.updateTitle();
3905 }
3906 this.toolbar.reserveTool( tool );
3907 add.push( tool );
3908 names[name] = true;
3909 }
3910 }
3911 // Remove tools that are no longer needed
3912 for ( name in this.tools ) {
3913 if ( !names[name] ) {
3914 this.tools[name].destroy();
3915 this.toolbar.releaseTool( this.tools[name] );
3916 remove.push( this.tools[name] );
3917 delete this.tools[name];
3918 }
3919 }
3920 if ( remove.length ) {
3921 this.removeItems( remove );
3922 }
3923 // Update emptiness state
3924 if ( add.length ) {
3925 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
3926 } else {
3927 this.$element.addClass( 'oo-ui-toolGroup-empty' );
3928 }
3929 // Re-add tools (moving existing ones to new locations)
3930 this.addItems( add );
3931 // Disabled state may depend on items
3932 this.updateDisabled();
3933 };
3934
3935 /**
3936 * Destroy tool group.
3937 */
3938 OO.ui.ToolGroup.prototype.destroy = function () {
3939 var name;
3940
3941 this.clearItems();
3942 this.toolbar.getToolFactory().disconnect( this );
3943 for ( name in this.tools ) {
3944 this.toolbar.releaseTool( this.tools[name] );
3945 this.tools[name].disconnect( this ).destroy();
3946 delete this.tools[name];
3947 }
3948 this.$element.remove();
3949 };
3950 /**
3951 * Factory for tool groups.
3952 *
3953 * @class
3954 * @extends OO.Factory
3955 * @constructor
3956 */
3957 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3958 // Parent constructor
3959 OO.Factory.call( this );
3960
3961 var i, l,
3962 defaultClasses = this.constructor.static.getDefaultClasses();
3963
3964 // Register default toolgroups
3965 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3966 this.register( defaultClasses[i] );
3967 }
3968 };
3969
3970 /* Setup */
3971
3972 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3973
3974 /* Static Methods */
3975
3976 /**
3977 * Get a default set of classes to be registered on construction
3978 *
3979 * @return {Function[]} Default classes
3980 */
3981 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3982 return [
3983 OO.ui.BarToolGroup,
3984 OO.ui.ListToolGroup,
3985 OO.ui.MenuToolGroup
3986 ];
3987 };
3988 /**
3989 * Layout made of a fieldset and optional legend.
3990 *
3991 * Just add OO.ui.FieldLayout items.
3992 *
3993 * @class
3994 * @extends OO.ui.Layout
3995 * @mixins OO.ui.LabeledElement
3996 * @mixins OO.ui.IconedElement
3997 * @mixins OO.ui.GroupElement
3998 *
3999 * @constructor
4000 * @param {Object} [config] Configuration options
4001 * @cfg {string} [icon] Symbolic icon name
4002 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
4003 */
4004 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
4005 // Config initialization
4006 config = config || {};
4007
4008 // Parent constructor
4009 OO.ui.FieldsetLayout.super.call( this, config );
4010
4011 // Mixin constructors
4012 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
4013 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
4014 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
4015
4016 // Initialization
4017 this.$element
4018 .addClass( 'oo-ui-fieldsetLayout' )
4019 .prepend( this.$icon, this.$label, this.$group );
4020 if ( $.isArray( config.items ) ) {
4021 this.addItems( config.items );
4022 }
4023 };
4024
4025 /* Setup */
4026
4027 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
4028 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconedElement );
4029 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabeledElement );
4030 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
4031
4032 /* Static Properties */
4033
4034 OO.ui.FieldsetLayout.static.tagName = 'div';
4035 /**
4036 * Layout made of a field and optional label.
4037 *
4038 * @class
4039 * @extends OO.ui.Layout
4040 * @mixins OO.ui.LabeledElement
4041 *
4042 * Available label alignment modes include:
4043 * - 'left': Label is before the field and aligned away from it, best for when the user will be
4044 * scanning for a specific label in a form with many fields
4045 * - 'right': Label is before the field and aligned toward it, best for forms the user is very
4046 * familiar with and will tab through field checking quickly to verify which field they are in
4047 * - 'top': Label is before the field and above it, best for when the use will need to fill out all
4048 * fields from top to bottom in a form with few fields
4049 * - 'inline': Label is after the field and aligned toward it, best for small boolean fields like
4050 * checkboxes or radio buttons
4051 *
4052 * @constructor
4053 * @param {OO.ui.Widget} field Field widget
4054 * @param {Object} [config] Configuration options
4055 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
4056 */
4057 OO.ui.FieldLayout = function OoUiFieldLayout( field, config ) {
4058 // Config initialization
4059 config = $.extend( { 'align': 'left' }, config );
4060
4061 // Parent constructor
4062 OO.ui.FieldLayout.super.call( this, config );
4063
4064 // Mixin constructors
4065 OO.ui.LabeledElement.call( this, this.$( '<label>' ), config );
4066
4067 // Properties
4068 this.$field = this.$( '<div>' );
4069 this.field = field;
4070 this.align = null;
4071
4072 // Events
4073 if ( this.field instanceof OO.ui.InputWidget ) {
4074 this.$label.on( 'click', OO.ui.bind( this.onLabelClick, this ) );
4075 }
4076 this.field.connect( this, { 'disable': 'onFieldDisable' } );
4077
4078 // Initialization
4079 this.$element.addClass( 'oo-ui-fieldLayout' );
4080 this.$field
4081 .addClass( 'oo-ui-fieldLayout-field' )
4082 .toggleClass( 'oo-ui-fieldLayout-disable', this.field.isDisabled() )
4083 .append( this.field.$element );
4084 this.setAlignment( config.align );
4085 };
4086
4087 /* Setup */
4088
4089 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
4090 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabeledElement );
4091
4092 /* Methods */
4093
4094 /**
4095 * Handle field disable events.
4096 *
4097 * @param {boolean} value Field is disabled
4098 */
4099 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
4100 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
4101 };
4102
4103 /**
4104 * Handle label mouse click events.
4105 *
4106 * @param {jQuery.Event} e Mouse click event
4107 */
4108 OO.ui.FieldLayout.prototype.onLabelClick = function () {
4109 this.field.simulateLabelClick();
4110 return false;
4111 };
4112
4113 /**
4114 * Get the field.
4115 *
4116 * @return {OO.ui.Widget} Field widget
4117 */
4118 OO.ui.FieldLayout.prototype.getField = function () {
4119 return this.field;
4120 };
4121
4122 /**
4123 * Set the field alignment mode.
4124 *
4125 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
4126 * @chainable
4127 */
4128 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
4129 if ( value !== this.align ) {
4130 // Default to 'left'
4131 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
4132 value = 'left';
4133 }
4134 // Reorder elements
4135 if ( value === 'inline' ) {
4136 this.$element.append( this.$field, this.$label );
4137 } else {
4138 this.$element.append( this.$label, this.$field );
4139 }
4140 // Set classes
4141 if ( this.align ) {
4142 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
4143 }
4144 this.align = value;
4145 this.$element.addClass( 'oo-ui-fieldLayout-align-' + this.align );
4146 }
4147
4148 return this;
4149 };
4150 /**
4151 * Layout made of proportionally sized columns and rows.
4152 *
4153 * @class
4154 * @extends OO.ui.Layout
4155 *
4156 * @constructor
4157 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
4158 * @param {Object} [config] Configuration options
4159 * @cfg {number[]} [widths] Widths of columns as ratios
4160 * @cfg {number[]} [heights] Heights of columns as ratios
4161 */
4162 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
4163 var i, len, widths;
4164
4165 // Config initialization
4166 config = config || {};
4167
4168 // Parent constructor
4169 OO.ui.GridLayout.super.call( this, config );
4170
4171 // Properties
4172 this.panels = [];
4173 this.widths = [];
4174 this.heights = [];
4175
4176 // Initialization
4177 this.$element.addClass( 'oo-ui-gridLayout' );
4178 for ( i = 0, len = panels.length; i < len; i++ ) {
4179 this.panels.push( panels[i] );
4180 this.$element.append( panels[i].$element );
4181 }
4182 if ( config.widths || config.heights ) {
4183 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
4184 } else {
4185 // Arrange in columns by default
4186 widths = [];
4187 for ( i = 0, len = this.panels.length; i < len; i++ ) {
4188 widths[i] = 1;
4189 }
4190 this.layout( widths, [ 1 ] );
4191 }
4192 };
4193
4194 /* Setup */
4195
4196 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
4197
4198 /* Events */
4199
4200 /**
4201 * @event layout
4202 */
4203
4204 /**
4205 * @event update
4206 */
4207
4208 /* Static Properties */
4209
4210 OO.ui.GridLayout.static.tagName = 'div';
4211
4212 /* Methods */
4213
4214 /**
4215 * Set grid dimensions.
4216 *
4217 * @param {number[]} widths Widths of columns as ratios
4218 * @param {number[]} heights Heights of rows as ratios
4219 * @fires layout
4220 * @throws {Error} If grid is not large enough to fit all panels
4221 */
4222 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
4223 var x, y,
4224 xd = 0,
4225 yd = 0,
4226 cols = widths.length,
4227 rows = heights.length;
4228
4229 // Verify grid is big enough to fit panels
4230 if ( cols * rows < this.panels.length ) {
4231 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
4232 }
4233
4234 // Sum up denominators
4235 for ( x = 0; x < cols; x++ ) {
4236 xd += widths[x];
4237 }
4238 for ( y = 0; y < rows; y++ ) {
4239 yd += heights[y];
4240 }
4241 // Store factors
4242 this.widths = [];
4243 this.heights = [];
4244 for ( x = 0; x < cols; x++ ) {
4245 this.widths[x] = widths[x] / xd;
4246 }
4247 for ( y = 0; y < rows; y++ ) {
4248 this.heights[y] = heights[y] / yd;
4249 }
4250 // Synchronize view
4251 this.update();
4252 this.emit( 'layout' );
4253 };
4254
4255 /**
4256 * Update panel positions and sizes.
4257 *
4258 * @fires update
4259 */
4260 OO.ui.GridLayout.prototype.update = function () {
4261 var x, y, panel,
4262 i = 0,
4263 left = 0,
4264 top = 0,
4265 dimensions,
4266 width = 0,
4267 height = 0,
4268 cols = this.widths.length,
4269 rows = this.heights.length;
4270
4271 for ( y = 0; y < rows; y++ ) {
4272 for ( x = 0; x < cols; x++ ) {
4273 panel = this.panels[i];
4274 width = this.widths[x];
4275 height = this.heights[y];
4276 dimensions = {
4277 'width': Math.round( width * 100 ) + '%',
4278 'height': Math.round( height * 100 ) + '%',
4279 'top': Math.round( top * 100 ) + '%'
4280 };
4281 // If RTL, reverse:
4282 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
4283 dimensions.right = Math.round( left * 100 ) + '%';
4284 } else {
4285 dimensions.left = Math.round( left * 100 ) + '%';
4286 }
4287 panel.$element.css( dimensions );
4288 i++;
4289 left += width;
4290 }
4291 top += height;
4292 left = 0;
4293 }
4294
4295 this.emit( 'update' );
4296 };
4297
4298 /**
4299 * Get a panel at a given position.
4300 *
4301 * The x and y position is affected by the current grid layout.
4302 *
4303 * @param {number} x Horizontal position
4304 * @param {number} y Vertical position
4305 * @return {OO.ui.PanelLayout} The panel at the given postion
4306 */
4307 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
4308 return this.panels[( x * this.widths.length ) + y];
4309 };
4310 /**
4311 * Layout containing a series of pages.
4312 *
4313 * @class
4314 * @extends OO.ui.Layout
4315 *
4316 * @constructor
4317 * @param {Object} [config] Configuration options
4318 * @cfg {boolean} [continuous=false] Show all pages, one after another
4319 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
4320 * @cfg {boolean} [outlined=false] Show an outline
4321 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
4322 */
4323 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
4324 // Initialize configuration
4325 config = config || {};
4326
4327 // Parent constructor
4328 OO.ui.BookletLayout.super.call( this, config );
4329
4330 // Properties
4331 this.currentPageName = null;
4332 this.pages = {};
4333 this.ignoreFocus = false;
4334 this.stackLayout = new OO.ui.StackLayout( { '$': this.$, 'continuous': !!config.continuous } );
4335 this.autoFocus = config.autoFocus === undefined ? true : !!config.autoFocus;
4336 this.outlineVisible = false;
4337 this.outlined = !!config.outlined;
4338 if ( this.outlined ) {
4339 this.editable = !!config.editable;
4340 this.outlineControlsWidget = null;
4341 this.outlineWidget = new OO.ui.OutlineWidget( { '$': this.$ } );
4342 this.outlinePanel = new OO.ui.PanelLayout( { '$': this.$, 'scrollable': true } );
4343 this.gridLayout = new OO.ui.GridLayout(
4344 [ this.outlinePanel, this.stackLayout ],
4345 { '$': this.$, 'widths': [ 1, 2 ] }
4346 );
4347 this.outlineVisible = true;
4348 if ( this.editable ) {
4349 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
4350 this.outlineWidget, { '$': this.$ }
4351 );
4352 }
4353 }
4354
4355 // Events
4356 this.stackLayout.connect( this, { 'set': 'onStackLayoutSet' } );
4357 if ( this.outlined ) {
4358 this.outlineWidget.connect( this, { 'select': 'onOutlineWidgetSelect' } );
4359 }
4360 if ( this.autoFocus ) {
4361 // Event 'focus' does not bubble, but 'focusin' does
4362 this.stackLayout.onDOMEvent( 'focusin', OO.ui.bind( this.onStackLayoutFocus, this ) );
4363 }
4364
4365 // Initialization
4366 this.$element.addClass( 'oo-ui-bookletLayout' );
4367 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
4368 if ( this.outlined ) {
4369 this.outlinePanel.$element
4370 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
4371 .append( this.outlineWidget.$element );
4372 if ( this.editable ) {
4373 this.outlinePanel.$element
4374 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
4375 .append( this.outlineControlsWidget.$element );
4376 }
4377 this.$element.append( this.gridLayout.$element );
4378 } else {
4379 this.$element.append( this.stackLayout.$element );
4380 }
4381 };
4382
4383 /* Setup */
4384
4385 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
4386
4387 /* Events */
4388
4389 /**
4390 * @event set
4391 * @param {OO.ui.PageLayout} page Current page
4392 */
4393
4394 /**
4395 * @event add
4396 * @param {OO.ui.PageLayout[]} page Added pages
4397 * @param {number} index Index pages were added at
4398 */
4399
4400 /**
4401 * @event remove
4402 * @param {OO.ui.PageLayout[]} pages Removed pages
4403 */
4404
4405 /* Methods */
4406
4407 /**
4408 * Handle stack layout focus.
4409 *
4410 * @param {jQuery.Event} e Focusin event
4411 */
4412 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
4413 var name, $target;
4414
4415 // Find the page that an element was focused within
4416 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
4417 for ( name in this.pages ) {
4418 // Check for page match, exclude current page to find only page changes
4419 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
4420 this.setPage( name );
4421 break;
4422 }
4423 }
4424 };
4425
4426 /**
4427 * Handle stack layout set events.
4428 *
4429 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
4430 */
4431 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
4432 if ( page ) {
4433 page.scrollElementIntoView( { 'complete': OO.ui.bind( function () {
4434 if ( this.autoFocus ) {
4435 // Set focus to the first input if nothing on the page is focused yet
4436 if ( !page.$element.find( ':focus' ).length ) {
4437 page.$element.find( ':input:first' ).focus();
4438 }
4439 }
4440 }, this ) } );
4441 }
4442 };
4443
4444 /**
4445 * Handle outline widget select events.
4446 *
4447 * @param {OO.ui.OptionWidget|null} item Selected item
4448 */
4449 OO.ui.BookletLayout.prototype.onOutlineWidgetSelect = function ( item ) {
4450 if ( item ) {
4451 this.setPage( item.getData() );
4452 }
4453 };
4454
4455 /**
4456 * Check if booklet has an outline.
4457 *
4458 * @return {boolean}
4459 */
4460 OO.ui.BookletLayout.prototype.isOutlined = function () {
4461 return this.outlined;
4462 };
4463
4464 /**
4465 * Check if booklet has editing controls.
4466 *
4467 * @return {boolean}
4468 */
4469 OO.ui.BookletLayout.prototype.isEditable = function () {
4470 return this.editable;
4471 };
4472
4473 /**
4474 * Check if booklet has a visible outline.
4475 *
4476 * @return {boolean}
4477 */
4478 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
4479 return this.outlined && this.outlineVisible;
4480 };
4481
4482 /**
4483 * Hide or show the outline.
4484 *
4485 * @param {boolean} [show] Show outline, omit to invert current state
4486 * @chainable
4487 */
4488 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
4489 if ( this.outlined ) {
4490 show = show === undefined ? !this.outlineVisible : !!show;
4491 this.outlineVisible = show;
4492 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
4493 }
4494
4495 return this;
4496 };
4497
4498 /**
4499 * Get the outline widget.
4500 *
4501 * @param {OO.ui.PageLayout} page Page to be selected
4502 * @return {OO.ui.PageLayout|null} Closest page to another
4503 */
4504 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
4505 var next, prev, level,
4506 pages = this.stackLayout.getItems(),
4507 index = $.inArray( page, pages );
4508
4509 if ( index !== -1 ) {
4510 next = pages[index + 1];
4511 prev = pages[index - 1];
4512 // Prefer adjacent pages at the same level
4513 if ( this.outlined ) {
4514 level = this.outlineWidget.getItemFromData( page.getName() ).getLevel();
4515 if (
4516 prev &&
4517 level === this.outlineWidget.getItemFromData( prev.getName() ).getLevel()
4518 ) {
4519 return prev;
4520 }
4521 if (
4522 next &&
4523 level === this.outlineWidget.getItemFromData( next.getName() ).getLevel()
4524 ) {
4525 return next;
4526 }
4527 }
4528 }
4529 return prev || next || null;
4530 };
4531
4532 /**
4533 * Get the outline widget.
4534 *
4535 * @return {OO.ui.OutlineWidget|null} Outline widget, or null if boolet has no outline
4536 */
4537 OO.ui.BookletLayout.prototype.getOutline = function () {
4538 return this.outlineWidget;
4539 };
4540
4541 /**
4542 * Get the outline controls widget. If the outline is not editable, null is returned.
4543 *
4544 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
4545 */
4546 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
4547 return this.outlineControlsWidget;
4548 };
4549
4550 /**
4551 * Get a page by name.
4552 *
4553 * @param {string} name Symbolic name of page
4554 * @return {OO.ui.PageLayout|undefined} Page, if found
4555 */
4556 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
4557 return this.pages[name];
4558 };
4559
4560 /**
4561 * Get the current page name.
4562 *
4563 * @return {string|null} Current page name
4564 */
4565 OO.ui.BookletLayout.prototype.getPageName = function () {
4566 return this.currentPageName;
4567 };
4568
4569 /**
4570 * Add a page to the layout.
4571 *
4572 * When pages are added with the same names as existing pages, the existing pages will be
4573 * automatically removed before the new pages are added.
4574 *
4575 * @param {OO.ui.PageLayout[]} pages Pages to add
4576 * @param {number} index Index to insert pages after
4577 * @fires add
4578 * @chainable
4579 */
4580 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
4581 var i, len, name, page, item, currentIndex,
4582 stackLayoutPages = this.stackLayout.getItems(),
4583 remove = [],
4584 items = [];
4585
4586 // Remove pages with same names
4587 for ( i = 0, len = pages.length; i < len; i++ ) {
4588 page = pages[i];
4589 name = page.getName();
4590
4591 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
4592 // Correct the insertion index
4593 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
4594 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
4595 index--;
4596 }
4597 remove.push( this.pages[name] );
4598 }
4599 }
4600 if ( remove.length ) {
4601 this.removePages( remove );
4602 }
4603
4604 // Add new pages
4605 for ( i = 0, len = pages.length; i < len; i++ ) {
4606 page = pages[i];
4607 name = page.getName();
4608 this.pages[page.getName()] = page;
4609 if ( this.outlined ) {
4610 item = new OO.ui.OutlineItemWidget( name, page, { '$': this.$ } );
4611 page.setOutlineItem( item );
4612 items.push( item );
4613 }
4614 }
4615
4616 if ( this.outlined && items.length ) {
4617 this.outlineWidget.addItems( items, index );
4618 this.updateOutlineWidget();
4619 }
4620 this.stackLayout.addItems( pages, index );
4621 this.emit( 'add', pages, index );
4622
4623 return this;
4624 };
4625
4626 /**
4627 * Remove a page from the layout.
4628 *
4629 * @fires remove
4630 * @chainable
4631 */
4632 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
4633 var i, len, name, page,
4634 items = [];
4635
4636 for ( i = 0, len = pages.length; i < len; i++ ) {
4637 page = pages[i];
4638 name = page.getName();
4639 delete this.pages[name];
4640 if ( this.outlined ) {
4641 items.push( this.outlineWidget.getItemFromData( name ) );
4642 page.setOutlineItem( null );
4643 }
4644 }
4645 if ( this.outlined && items.length ) {
4646 this.outlineWidget.removeItems( items );
4647 this.updateOutlineWidget();
4648 }
4649 this.stackLayout.removeItems( pages );
4650 this.emit( 'remove', pages );
4651
4652 return this;
4653 };
4654
4655 /**
4656 * Clear all pages from the layout.
4657 *
4658 * @fires remove
4659 * @chainable
4660 */
4661 OO.ui.BookletLayout.prototype.clearPages = function () {
4662 var i, len,
4663 pages = this.stackLayout.getItems();
4664
4665 this.pages = {};
4666 this.currentPageName = null;
4667 if ( this.outlined ) {
4668 this.outlineWidget.clearItems();
4669 for ( i = 0, len = pages.length; i < len; i++ ) {
4670 pages[i].setOutlineItem( null );
4671 }
4672 }
4673 this.stackLayout.clearItems();
4674
4675 this.emit( 'remove', pages );
4676
4677 return this;
4678 };
4679
4680 /**
4681 * Set the current page by name.
4682 *
4683 * @fires set
4684 * @param {string} name Symbolic name of page
4685 */
4686 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
4687 var selectedItem,
4688 page = this.pages[name];
4689
4690 if ( name !== this.currentPageName ) {
4691 if ( this.outlined ) {
4692 selectedItem = this.outlineWidget.getSelectedItem();
4693 if ( selectedItem && selectedItem.getData() !== name ) {
4694 this.outlineWidget.selectItem( this.outlineWidget.getItemFromData( name ) );
4695 }
4696 }
4697 if ( page ) {
4698 if ( this.currentPageName && this.pages[this.currentPageName] ) {
4699 this.pages[this.currentPageName].setActive( false );
4700 // Blur anything focused if the next page doesn't have anything focusable - this
4701 // is not needed if the next page has something focusable because once it is focused
4702 // this blur happens automatically
4703 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
4704 this.pages[this.currentPageName].$element.find( ':focus' ).blur();
4705 }
4706 }
4707 this.currentPageName = name;
4708 this.stackLayout.setItem( page );
4709 page.setActive( true );
4710 this.emit( 'set', page );
4711 }
4712 }
4713 };
4714
4715 /**
4716 * Call this after adding or removing items from the OutlineWidget.
4717 *
4718 * @chainable
4719 */
4720 OO.ui.BookletLayout.prototype.updateOutlineWidget = function () {
4721 // Auto-select first item when nothing is selected anymore
4722 if ( !this.outlineWidget.getSelectedItem() ) {
4723 this.outlineWidget.selectItem( this.outlineWidget.getFirstSelectableItem() );
4724 }
4725
4726 return this;
4727 };
4728 /**
4729 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
4730 *
4731 * @class
4732 * @extends OO.ui.Layout
4733 *
4734 * @constructor
4735 * @param {Object} [config] Configuration options
4736 * @cfg {boolean} [scrollable] Allow vertical scrolling
4737 * @cfg {boolean} [padded] Pad the content from the edges
4738 */
4739 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
4740 // Config initialization
4741 config = config || {};
4742
4743 // Parent constructor
4744 OO.ui.PanelLayout.super.call( this, config );
4745
4746 // Initialization
4747 this.$element.addClass( 'oo-ui-panelLayout' );
4748 if ( config.scrollable ) {
4749 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
4750 }
4751
4752 if ( config.padded ) {
4753 this.$element.addClass( 'oo-ui-panelLayout-padded' );
4754 }
4755 };
4756
4757 /* Setup */
4758
4759 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
4760 /**
4761 * Page within an booklet layout.
4762 *
4763 * @class
4764 * @extends OO.ui.PanelLayout
4765 *
4766 * @constructor
4767 * @param {string} name Unique symbolic name of page
4768 * @param {Object} [config] Configuration options
4769 * @param {string} [outlineItem] Outline item widget
4770 */
4771 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
4772 // Configuration initialization
4773 config = $.extend( { 'scrollable': true }, config );
4774
4775 // Parent constructor
4776 OO.ui.PageLayout.super.call( this, config );
4777
4778 // Properties
4779 this.name = name;
4780 this.outlineItem = config.outlineItem || null;
4781 this.active = false;
4782
4783 // Initialization
4784 this.$element.addClass( 'oo-ui-pageLayout' );
4785 };
4786
4787 /* Setup */
4788
4789 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
4790
4791 /* Events */
4792
4793 /**
4794 * @event active
4795 * @param {boolean} active Page is active
4796 */
4797
4798 /* Methods */
4799
4800 /**
4801 * Get page name.
4802 *
4803 * @return {string} Symbolic name of page
4804 */
4805 OO.ui.PageLayout.prototype.getName = function () {
4806 return this.name;
4807 };
4808
4809 /**
4810 * Check if page is active.
4811 *
4812 * @return {boolean} Page is active
4813 */
4814 OO.ui.PageLayout.prototype.isActive = function () {
4815 return this.active;
4816 };
4817
4818 /**
4819 * Get outline item.
4820 *
4821 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
4822 */
4823 OO.ui.PageLayout.prototype.getOutlineItem = function () {
4824 return this.outlineItem;
4825 };
4826
4827 /**
4828 * Get outline item.
4829 *
4830 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
4831 * @chainable
4832 */
4833 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
4834 this.outlineItem = outlineItem;
4835 return this;
4836 };
4837
4838 /**
4839 * Set page active state.
4840 *
4841 * @param {boolean} Page is active
4842 * @fires active
4843 */
4844 OO.ui.PageLayout.prototype.setActive = function ( active ) {
4845 active = !!active;
4846
4847 if ( active !== this.active ) {
4848 this.active = active;
4849 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
4850 this.emit( 'active', this.active );
4851 }
4852 };
4853 /**
4854 * Layout containing a series of mutually exclusive pages.
4855 *
4856 * @class
4857 * @extends OO.ui.PanelLayout
4858 * @mixins OO.ui.GroupElement
4859 *
4860 * @constructor
4861 * @param {Object} [config] Configuration options
4862 * @cfg {boolean} [continuous=false] Show all pages, one after another
4863 * @cfg {string} [icon=''] Symbolic icon name
4864 * @cfg {OO.ui.Layout[]} [items] Layouts to add
4865 */
4866 OO.ui.StackLayout = function OoUiStackLayout( config ) {
4867 // Config initialization
4868 config = $.extend( { 'scrollable': true }, config );
4869
4870 // Parent constructor
4871 OO.ui.StackLayout.super.call( this, config );
4872
4873 // Mixin constructors
4874 OO.ui.GroupElement.call( this, this.$element, config );
4875
4876 // Properties
4877 this.currentItem = null;
4878 this.continuous = !!config.continuous;
4879
4880 // Initialization
4881 this.$element.addClass( 'oo-ui-stackLayout' );
4882 if ( this.continuous ) {
4883 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
4884 }
4885 if ( $.isArray( config.items ) ) {
4886 this.addItems( config.items );
4887 }
4888 };
4889
4890 /* Setup */
4891
4892 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
4893 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
4894
4895 /* Events */
4896
4897 /**
4898 * @event set
4899 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
4900 */
4901
4902 /* Methods */
4903
4904 /**
4905 * Get the current item.
4906 *
4907 * @return {OO.ui.Layout|null}
4908 */
4909 OO.ui.StackLayout.prototype.getCurrentItem = function () {
4910 return this.currentItem;
4911 };
4912
4913 /**
4914 * Unset the current item.
4915 *
4916 * @private
4917 * @param {OO.ui.StackLayout} layout
4918 * @fires set
4919 */
4920 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
4921 var prevItem = this.currentItem;
4922 if ( prevItem === null ) {
4923 return;
4924 }
4925
4926 this.currentItem = null;
4927 this.emit( 'set', null );
4928 };
4929
4930 /**
4931 * Add items.
4932 *
4933 * Adding an existing item (by value) will move it.
4934 *
4935 * @param {OO.ui.Layout[]} items Items to add
4936 * @param {number} [index] Index to insert items after
4937 * @chainable
4938 */
4939 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
4940 // Mixin method
4941 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
4942
4943 if ( !this.currentItem && items.length ) {
4944 this.setItem( items[0] );
4945 }
4946
4947 return this;
4948 };
4949
4950 /**
4951 * Remove items.
4952 *
4953 * Items will be detached, not removed, so they can be used later.
4954 *
4955 * @param {OO.ui.Layout[]} items Items to remove
4956 * @chainable
4957 * @fires set
4958 */
4959 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
4960 // Mixin method
4961 OO.ui.GroupElement.prototype.removeItems.call( this, items );
4962
4963 if ( $.inArray( this.currentItem, items ) !== -1 ) {
4964 if ( this.items.length ) {
4965 this.setItem( this.items[0] );
4966 } else {
4967 this.unsetCurrentItem();
4968 }
4969 }
4970
4971 return this;
4972 };
4973
4974 /**
4975 * Clear all items.
4976 *
4977 * Items will be detached, not removed, so they can be used later.
4978 *
4979 * @chainable
4980 * @fires set
4981 */
4982 OO.ui.StackLayout.prototype.clearItems = function () {
4983 this.unsetCurrentItem();
4984 OO.ui.GroupElement.prototype.clearItems.call( this );
4985
4986 return this;
4987 };
4988
4989 /**
4990 * Show item.
4991 *
4992 * Any currently shown item will be hidden.
4993 *
4994 * FIXME: If the passed item to show has not been added in the items list, then
4995 * this method drops it and unsets the current item.
4996 *
4997 * @param {OO.ui.Layout} item Item to show
4998 * @chainable
4999 * @fires set
5000 */
5001 OO.ui.StackLayout.prototype.setItem = function ( item ) {
5002 var i, len;
5003
5004 if ( item !== this.currentItem ) {
5005 if ( !this.continuous ) {
5006 for ( i = 0, len = this.items.length; i < len; i++ ) {
5007 this.items[i].$element.css( 'display', '' );
5008 }
5009 }
5010 if ( $.inArray( item, this.items ) !== -1 ) {
5011 if ( !this.continuous ) {
5012 item.$element.css( 'display', 'block' );
5013 }
5014 this.currentItem = item;
5015 this.emit( 'set', item );
5016 } else {
5017 this.unsetCurrentItem();
5018 }
5019 }
5020
5021 return this;
5022 };
5023 /**
5024 * Horizontal bar layout of tools as icon buttons.
5025 *
5026 * @class
5027 * @extends OO.ui.ToolGroup
5028 *
5029 * @constructor
5030 * @param {OO.ui.Toolbar} toolbar
5031 * @param {Object} [config] Configuration options
5032 */
5033 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
5034 // Parent constructor
5035 OO.ui.BarToolGroup.super.call( this, toolbar, config );
5036
5037 // Initialization
5038 this.$element.addClass( 'oo-ui-barToolGroup' );
5039 };
5040
5041 /* Setup */
5042
5043 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
5044
5045 /* Static Properties */
5046
5047 OO.ui.BarToolGroup.static.titleTooltips = true;
5048
5049 OO.ui.BarToolGroup.static.accelTooltips = true;
5050
5051 OO.ui.BarToolGroup.static.name = 'bar';
5052 /**
5053 * Popup list of tools with an icon and optional label.
5054 *
5055 * @abstract
5056 * @class
5057 * @extends OO.ui.ToolGroup
5058 * @mixins OO.ui.IconedElement
5059 * @mixins OO.ui.IndicatedElement
5060 * @mixins OO.ui.LabeledElement
5061 * @mixins OO.ui.TitledElement
5062 * @mixins OO.ui.ClippableElement
5063 *
5064 * @constructor
5065 * @param {OO.ui.Toolbar} toolbar
5066 * @param {Object} [config] Configuration options
5067 * @cfg {string} [header] Text to display at the top of the pop-up
5068 */
5069 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
5070 // Configuration initialization
5071 config = config || {};
5072
5073 // Parent constructor
5074 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
5075
5076 // Mixin constructors
5077 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
5078 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
5079 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
5080 OO.ui.TitledElement.call( this, this.$element, config );
5081 OO.ui.ClippableElement.call( this, this.$group, config );
5082
5083 // Properties
5084 this.active = false;
5085 this.dragging = false;
5086 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
5087 this.$handle = this.$( '<span>' );
5088
5089 // Events
5090 this.$handle.on( {
5091 'mousedown': OO.ui.bind( this.onHandleMouseDown, this ),
5092 'mouseup': OO.ui.bind( this.onHandleMouseUp, this )
5093 } );
5094
5095 // Initialization
5096 this.$handle
5097 .addClass( 'oo-ui-popupToolGroup-handle' )
5098 .append( this.$icon, this.$label, this.$indicator );
5099 // If the pop-up should have a header, add it to the top of the toolGroup.
5100 // Note: If this feature is useful for other widgets, we could abstract it into an
5101 // OO.ui.HeaderedElement mixin constructor.
5102 if ( config.header !== undefined ) {
5103 this.$group
5104 .prepend( this.$( '<span>' )
5105 .addClass( 'oo-ui-popupToolGroup-header' )
5106 .text( config.header )
5107 );
5108 }
5109 this.$element
5110 .addClass( 'oo-ui-popupToolGroup' )
5111 .prepend( this.$handle );
5112 };
5113
5114 /* Setup */
5115
5116 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
5117 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconedElement );
5118 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatedElement );
5119 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabeledElement );
5120 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
5121 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
5122
5123 /* Static Properties */
5124
5125 /* Methods */
5126
5127 /**
5128 * @inheritdoc
5129 */
5130 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
5131 // Parent method
5132 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
5133
5134 if ( this.isDisabled() && this.isElementAttached() ) {
5135 this.setActive( false );
5136 }
5137 };
5138
5139 /**
5140 * Handle focus being lost.
5141 *
5142 * The event is actually generated from a mouseup, so it is not a normal blur event object.
5143 *
5144 * @param {jQuery.Event} e Mouse up event
5145 */
5146 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
5147 // Only deactivate when clicking outside the dropdown element
5148 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
5149 this.setActive( false );
5150 }
5151 };
5152
5153 /**
5154 * @inheritdoc
5155 */
5156 OO.ui.PopupToolGroup.prototype.onMouseUp = function ( e ) {
5157 if ( !this.isDisabled() && e.which === 1 ) {
5158 this.setActive( false );
5159 }
5160 return OO.ui.PopupToolGroup.super.prototype.onMouseUp.call( this, e );
5161 };
5162
5163 /**
5164 * Handle mouse up events.
5165 *
5166 * @param {jQuery.Event} e Mouse up event
5167 */
5168 OO.ui.PopupToolGroup.prototype.onHandleMouseUp = function () {
5169 return false;
5170 };
5171
5172 /**
5173 * Handle mouse down events.
5174 *
5175 * @param {jQuery.Event} e Mouse down event
5176 */
5177 OO.ui.PopupToolGroup.prototype.onHandleMouseDown = function ( e ) {
5178 if ( !this.isDisabled() && e.which === 1 ) {
5179 this.setActive( !this.active );
5180 }
5181 return false;
5182 };
5183
5184 /**
5185 * Switch into active mode.
5186 *
5187 * When active, mouseup events anywhere in the document will trigger deactivation.
5188 */
5189 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
5190 value = !!value;
5191 if ( this.active !== value ) {
5192 this.active = value;
5193 if ( value ) {
5194 this.setClipping( true );
5195 this.$element.addClass( 'oo-ui-popupToolGroup-active' );
5196 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
5197 } else {
5198 this.setClipping( false );
5199 this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
5200 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
5201 }
5202 }
5203 };
5204 /**
5205 * Drop down list layout of tools as labeled icon buttons.
5206 *
5207 * @class
5208 * @extends OO.ui.PopupToolGroup
5209 *
5210 * @constructor
5211 * @param {OO.ui.Toolbar} toolbar
5212 * @param {Object} [config] Configuration options
5213 */
5214 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
5215 // Parent constructor
5216 OO.ui.ListToolGroup.super.call( this, toolbar, config );
5217
5218 // Initialization
5219 this.$element.addClass( 'oo-ui-listToolGroup' );
5220 };
5221
5222 /* Setup */
5223
5224 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
5225
5226 /* Static Properties */
5227
5228 OO.ui.ListToolGroup.static.accelTooltips = true;
5229
5230 OO.ui.ListToolGroup.static.name = 'list';
5231 /**
5232 * Drop down menu layout of tools as selectable menu items.
5233 *
5234 * @class
5235 * @extends OO.ui.PopupToolGroup
5236 *
5237 * @constructor
5238 * @param {OO.ui.Toolbar} toolbar
5239 * @param {Object} [config] Configuration options
5240 */
5241 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
5242 // Configuration initialization
5243 config = config || {};
5244
5245 // Parent constructor
5246 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
5247
5248 // Events
5249 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
5250
5251 // Initialization
5252 this.$element.addClass( 'oo-ui-menuToolGroup' );
5253 };
5254
5255 /* Setup */
5256
5257 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
5258
5259 /* Static Properties */
5260
5261 OO.ui.MenuToolGroup.static.accelTooltips = true;
5262
5263 OO.ui.MenuToolGroup.static.name = 'menu';
5264
5265 /* Methods */
5266
5267 /**
5268 * Handle the toolbar state being updated.
5269 *
5270 * When the state changes, the title of each active item in the menu will be joined together and
5271 * used as a label for the group. The label will be empty if none of the items are active.
5272 */
5273 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
5274 var name,
5275 labelTexts = [];
5276
5277 for ( name in this.tools ) {
5278 if ( this.tools[name].isActive() ) {
5279 labelTexts.push( this.tools[name].getTitle() );
5280 }
5281 }
5282
5283 this.setLabel( labelTexts.join( ', ' ) || ' ' );
5284 };
5285 /**
5286 * Tool that shows a popup when selected.
5287 *
5288 * @abstract
5289 * @class
5290 * @extends OO.ui.Tool
5291 * @mixins OO.ui.PopuppableElement
5292 *
5293 * @constructor
5294 * @param {OO.ui.Toolbar} toolbar
5295 * @param {Object} [config] Configuration options
5296 */
5297 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
5298 // Parent constructor
5299 OO.ui.PopupTool.super.call( this, toolbar, config );
5300
5301 // Mixin constructors
5302 OO.ui.PopuppableElement.call( this, config );
5303
5304 // Initialization
5305 this.$element
5306 .addClass( 'oo-ui-popupTool' )
5307 .append( this.popup.$element );
5308 };
5309
5310 /* Setup */
5311
5312 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
5313 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopuppableElement );
5314
5315 /* Methods */
5316
5317 /**
5318 * Handle the tool being selected.
5319 *
5320 * @inheritdoc
5321 */
5322 OO.ui.PopupTool.prototype.onSelect = function () {
5323 if ( !this.isDisabled() ) {
5324 if ( this.popup.isVisible() ) {
5325 this.hidePopup();
5326 } else {
5327 this.showPopup();
5328 }
5329 }
5330 this.setActive( false );
5331 return false;
5332 };
5333
5334 /**
5335 * Handle the toolbar state being updated.
5336 *
5337 * @inheritdoc
5338 */
5339 OO.ui.PopupTool.prototype.onUpdateState = function () {
5340 this.setActive( false );
5341 };
5342 /**
5343 * Group widget.
5344 *
5345 * Mixin for OO.ui.Widget subclasses.
5346 *
5347 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
5348 *
5349 * @abstract
5350 * @class
5351 * @extends OO.ui.GroupElement
5352 *
5353 * @constructor
5354 * @param {jQuery} $group Container node, assigned to #$group
5355 * @param {Object} [config] Configuration options
5356 */
5357 OO.ui.GroupWidget = function OoUiGroupWidget( $element, config ) {
5358 // Parent constructor
5359 OO.ui.GroupWidget.super.call( this, $element, config );
5360 };
5361
5362 /* Setup */
5363
5364 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
5365
5366 /* Methods */
5367
5368 /**
5369 * Set the disabled state of the widget.
5370 *
5371 * This will also update the disabled state of child widgets.
5372 *
5373 * @param {boolean} disabled Disable widget
5374 * @chainable
5375 */
5376 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
5377 var i, len;
5378
5379 // Parent method
5380 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5381 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5382
5383 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
5384 if ( this.items ) {
5385 for ( i = 0, len = this.items.length; i < len; i++ ) {
5386 this.items[i].updateDisabled();
5387 }
5388 }
5389
5390 return this;
5391 };
5392 /**
5393 * Item widget.
5394 *
5395 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
5396 *
5397 * @abstract
5398 * @class
5399 *
5400 * @constructor
5401 */
5402 OO.ui.ItemWidget = function OoUiItemWidget() {
5403 //
5404 };
5405
5406 /* Methods */
5407
5408 /**
5409 * Check if widget is disabled.
5410 *
5411 * Checks parent if present, making disabled state inheritable.
5412 *
5413 * @return {boolean} Widget is disabled
5414 */
5415 OO.ui.ItemWidget.prototype.isDisabled = function () {
5416 return this.disabled ||
5417 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5418 };
5419
5420 /**
5421 * Set group element is in.
5422 *
5423 * @param {OO.ui.GroupElement|null} group Group element, null if none
5424 * @chainable
5425 */
5426 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
5427 // Parent method
5428 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5429 OO.ui.Element.prototype.setElementGroup.call( this, group );
5430
5431 // Initialize item disabled states
5432 this.updateDisabled();
5433
5434 return this;
5435 };
5436 /**
5437 * Icon widget.
5438 *
5439 * @class
5440 * @extends OO.ui.Widget
5441 * @mixins OO.ui.IconedElement
5442 * @mixins OO.ui.TitledElement
5443 *
5444 * @constructor
5445 * @param {Object} [config] Configuration options
5446 */
5447 OO.ui.IconWidget = function OoUiIconWidget( config ) {
5448 // Config intialization
5449 config = config || {};
5450
5451 // Parent constructor
5452 OO.ui.IconWidget.super.call( this, config );
5453
5454 // Mixin constructors
5455 OO.ui.IconedElement.call( this, this.$element, config );
5456 OO.ui.TitledElement.call( this, this.$element, config );
5457
5458 // Initialization
5459 this.$element.addClass( 'oo-ui-iconWidget' );
5460 };
5461
5462 /* Setup */
5463
5464 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
5465 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconedElement );
5466 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
5467
5468 /* Static Properties */
5469
5470 OO.ui.IconWidget.static.tagName = 'span';
5471 /**
5472 * Indicator widget.
5473 *
5474 * @class
5475 * @extends OO.ui.Widget
5476 * @mixins OO.ui.IndicatedElement
5477 * @mixins OO.ui.TitledElement
5478 *
5479 * @constructor
5480 * @param {Object} [config] Configuration options
5481 */
5482 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
5483 // Config intialization
5484 config = config || {};
5485
5486 // Parent constructor
5487 OO.ui.IndicatorWidget.super.call( this, config );
5488
5489 // Mixin constructors
5490 OO.ui.IndicatedElement.call( this, this.$element, config );
5491 OO.ui.TitledElement.call( this, this.$element, config );
5492
5493 // Initialization
5494 this.$element.addClass( 'oo-ui-indicatorWidget' );
5495 };
5496
5497 /* Setup */
5498
5499 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
5500 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatedElement );
5501 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
5502
5503 /* Static Properties */
5504
5505 OO.ui.IndicatorWidget.static.tagName = 'span';
5506 /**
5507 * Container for multiple related buttons.
5508 *
5509 * Use together with OO.ui.ButtonWidget.
5510 *
5511 * @class
5512 * @extends OO.ui.Widget
5513 * @mixins OO.ui.GroupElement
5514 *
5515 * @constructor
5516 * @param {Object} [config] Configuration options
5517 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
5518 */
5519 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
5520 // Parent constructor
5521 OO.ui.ButtonGroupWidget.super.call( this, config );
5522
5523 // Mixin constructors
5524 OO.ui.GroupElement.call( this, this.$element, config );
5525
5526 // Initialization
5527 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
5528 if ( $.isArray( config.items ) ) {
5529 this.addItems( config.items );
5530 }
5531 };
5532
5533 /* Setup */
5534
5535 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
5536 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
5537 /**
5538 * Button widget.
5539 *
5540 * @class
5541 * @extends OO.ui.Widget
5542 * @mixins OO.ui.ButtonedElement
5543 * @mixins OO.ui.IconedElement
5544 * @mixins OO.ui.IndicatedElement
5545 * @mixins OO.ui.LabeledElement
5546 * @mixins OO.ui.TitledElement
5547 * @mixins OO.ui.FlaggableElement
5548 *
5549 * @constructor
5550 * @param {Object} [config] Configuration options
5551 * @cfg {string} [title=''] Title text
5552 * @cfg {string} [href] Hyperlink to visit when clicked
5553 * @cfg {string} [target] Target to open hyperlink in
5554 */
5555 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
5556 // Configuration initialization
5557 config = $.extend( { 'target': '_blank' }, config );
5558
5559 // Parent constructor
5560 OO.ui.ButtonWidget.super.call( this, config );
5561
5562 // Mixin constructors
5563 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
5564 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
5565 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
5566 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
5567 OO.ui.TitledElement.call( this, this.$button, config );
5568 OO.ui.FlaggableElement.call( this, config );
5569
5570 // Properties
5571 this.isHyperlink = typeof config.href === 'string';
5572
5573 // Events
5574 this.$button.on( {
5575 'click': OO.ui.bind( this.onClick, this ),
5576 'keypress': OO.ui.bind( this.onKeyPress, this )
5577 } );
5578
5579 // Initialization
5580 this.$button
5581 .append( this.$icon, this.$label, this.$indicator )
5582 .attr( { 'href': config.href, 'target': config.target } );
5583 this.$element
5584 .addClass( 'oo-ui-buttonWidget' )
5585 .append( this.$button );
5586 };
5587
5588 /* Setup */
5589
5590 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
5591 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonedElement );
5592 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconedElement );
5593 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatedElement );
5594 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabeledElement );
5595 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
5596 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggableElement );
5597
5598 /* Events */
5599
5600 /**
5601 * @event click
5602 */
5603
5604 /* Methods */
5605
5606 /**
5607 * Handles mouse click events.
5608 *
5609 * @param {jQuery.Event} e Mouse click event
5610 * @fires click
5611 */
5612 OO.ui.ButtonWidget.prototype.onClick = function () {
5613 if ( !this.isDisabled() ) {
5614 this.emit( 'click' );
5615 if ( this.isHyperlink ) {
5616 return true;
5617 }
5618 }
5619 return false;
5620 };
5621
5622 /**
5623 * Handles keypress events.
5624 *
5625 * @param {jQuery.Event} e Keypress event
5626 * @fires click
5627 */
5628 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
5629 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
5630 this.onClick();
5631 if ( this.isHyperlink ) {
5632 return true;
5633 }
5634 }
5635 return false;
5636 };
5637 /**
5638 * Input widget.
5639 *
5640 * @abstract
5641 * @class
5642 * @extends OO.ui.Widget
5643 *
5644 * @constructor
5645 * @param {Object} [config] Configuration options
5646 * @cfg {string} [name=''] HTML input name
5647 * @cfg {string} [value=''] Input value
5648 * @cfg {boolean} [readOnly=false] Prevent changes
5649 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
5650 */
5651 OO.ui.InputWidget = function OoUiInputWidget( config ) {
5652 // Config intialization
5653 config = $.extend( { 'readOnly': false }, config );
5654
5655 // Parent constructor
5656 OO.ui.InputWidget.super.call( this, config );
5657
5658 // Properties
5659 this.$input = this.getInputElement( config );
5660 this.value = '';
5661 this.readOnly = false;
5662 this.inputFilter = config.inputFilter;
5663
5664 // Events
5665 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
5666
5667 // Initialization
5668 this.$input
5669 .attr( 'name', config.name )
5670 .prop( 'disabled', this.isDisabled() );
5671 this.setReadOnly( config.readOnly );
5672 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
5673 this.setValue( config.value );
5674 };
5675
5676 /* Setup */
5677
5678 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
5679
5680 /* Events */
5681
5682 /**
5683 * @event change
5684 * @param value
5685 */
5686
5687 /* Methods */
5688
5689 /**
5690 * Get input element.
5691 *
5692 * @param {Object} [config] Configuration options
5693 * @return {jQuery} Input element
5694 */
5695 OO.ui.InputWidget.prototype.getInputElement = function () {
5696 return this.$( '<input>' );
5697 };
5698
5699 /**
5700 * Handle potentially value-changing events.
5701 *
5702 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
5703 */
5704 OO.ui.InputWidget.prototype.onEdit = function () {
5705 if ( !this.isDisabled() ) {
5706 // Allow the stack to clear so the value will be updated
5707 setTimeout( OO.ui.bind( function () {
5708 this.setValue( this.$input.val() );
5709 }, this ) );
5710 }
5711 };
5712
5713 /**
5714 * Get the value of the input.
5715 *
5716 * @return {string} Input value
5717 */
5718 OO.ui.InputWidget.prototype.getValue = function () {
5719 return this.value;
5720 };
5721
5722 /**
5723 * Sets the direction of the current input, either RTL or LTR
5724 *
5725 * @param {boolean} isRTL
5726 */
5727 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
5728 if ( isRTL ) {
5729 this.$input.removeClass( 'oo-ui-ltr' );
5730 this.$input.addClass( 'oo-ui-rtl' );
5731 } else {
5732 this.$input.removeClass( 'oo-ui-rtl' );
5733 this.$input.addClass( 'oo-ui-ltr' );
5734 }
5735 };
5736
5737 /**
5738 * Set the value of the input.
5739 *
5740 * @param {string} value New value
5741 * @fires change
5742 * @chainable
5743 */
5744 OO.ui.InputWidget.prototype.setValue = function ( value ) {
5745 value = this.sanitizeValue( value );
5746 if ( this.value !== value ) {
5747 this.value = value;
5748 this.emit( 'change', this.value );
5749 }
5750 // Update the DOM if it has changed. Note that with sanitizeValue, it
5751 // is possible for the DOM value to change without this.value changing.
5752 if ( this.$input.val() !== this.value ) {
5753 this.$input.val( this.value );
5754 }
5755 return this;
5756 };
5757
5758 /**
5759 * Sanitize incoming value.
5760 *
5761 * Ensures value is a string, and converts undefined and null to empty strings.
5762 *
5763 * @param {string} value Original value
5764 * @return {string} Sanitized value
5765 */
5766 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
5767 if ( value === undefined || value === null ) {
5768 return '';
5769 } else if ( this.inputFilter ) {
5770 return this.inputFilter( String( value ) );
5771 } else {
5772 return String( value );
5773 }
5774 };
5775
5776 /**
5777 * Simulate the behavior of clicking on a label bound to this input.
5778 */
5779 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
5780 if ( !this.isDisabled() ) {
5781 if ( this.$input.is( ':checkbox,:radio' ) ) {
5782 this.$input.click();
5783 } else if ( this.$input.is( ':input' ) ) {
5784 this.$input.focus();
5785 }
5786 }
5787 };
5788
5789 /**
5790 * Check if the widget is read-only.
5791 *
5792 * @return {boolean}
5793 */
5794 OO.ui.InputWidget.prototype.isReadOnly = function () {
5795 return this.readOnly;
5796 };
5797
5798 /**
5799 * Set the read-only state of the widget.
5800 *
5801 * This should probably change the widgets's appearance and prevent it from being used.
5802 *
5803 * @param {boolean} state Make input read-only
5804 * @chainable
5805 */
5806 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
5807 this.readOnly = !!state;
5808 this.$input.prop( 'readOnly', this.readOnly );
5809 return this;
5810 };
5811
5812 /**
5813 * @inheritdoc
5814 */
5815 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
5816 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
5817 if ( this.$input ) {
5818 this.$input.prop( 'disabled', this.isDisabled() );
5819 }
5820 return this;
5821 };
5822
5823 /**
5824 * Focus the input.
5825 *
5826 * @chainable
5827 */
5828 OO.ui.InputWidget.prototype.focus = function () {
5829 this.$input.focus();
5830 return this;
5831 };
5832 /**
5833 * Checkbox widget.
5834 *
5835 * @class
5836 * @extends OO.ui.InputWidget
5837 *
5838 * @constructor
5839 * @param {Object} [config] Configuration options
5840 */
5841 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
5842 // Parent constructor
5843 OO.ui.CheckboxInputWidget.super.call( this, config );
5844
5845 // Initialization
5846 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
5847 };
5848
5849 /* Setup */
5850
5851 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
5852
5853 /* Events */
5854
5855 /* Methods */
5856
5857 /**
5858 * Get input element.
5859 *
5860 * @return {jQuery} Input element
5861 */
5862 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
5863 return this.$( '<input type="checkbox" />' );
5864 };
5865
5866 /**
5867 * Get checked state of the checkbox
5868 *
5869 * @return {boolean} If the checkbox is checked
5870 */
5871 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
5872 return this.value;
5873 };
5874
5875 /**
5876 * Set value
5877 */
5878 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
5879 value = !!value;
5880 if ( this.value !== value ) {
5881 this.value = value;
5882 this.$input.prop( 'checked', this.value );
5883 this.emit( 'change', this.value );
5884 }
5885 };
5886
5887 /**
5888 * @inheritdoc
5889 */
5890 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
5891 if ( !this.isDisabled() ) {
5892 // Allow the stack to clear so the value will be updated
5893 setTimeout( OO.ui.bind( function () {
5894 this.setValue( this.$input.prop( 'checked' ) );
5895 }, this ) );
5896 }
5897 };
5898 /**
5899 * Label widget.
5900 *
5901 * @class
5902 * @extends OO.ui.Widget
5903 * @mixins OO.ui.LabeledElement
5904 *
5905 * @constructor
5906 * @param {Object} [config] Configuration options
5907 */
5908 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
5909 // Config intialization
5910 config = config || {};
5911
5912 // Parent constructor
5913 OO.ui.LabelWidget.super.call( this, config );
5914
5915 // Mixin constructors
5916 OO.ui.LabeledElement.call( this, this.$element, config );
5917
5918 // Properties
5919 this.input = config.input;
5920
5921 // Events
5922 if ( this.input instanceof OO.ui.InputWidget ) {
5923 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
5924 }
5925
5926 // Initialization
5927 this.$element.addClass( 'oo-ui-labelWidget' );
5928 };
5929
5930 /* Setup */
5931
5932 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
5933 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabeledElement );
5934
5935 /* Static Properties */
5936
5937 OO.ui.LabelWidget.static.tagName = 'label';
5938
5939 /* Methods */
5940
5941 /**
5942 * Handles label mouse click events.
5943 *
5944 * @param {jQuery.Event} e Mouse click event
5945 */
5946 OO.ui.LabelWidget.prototype.onClick = function () {
5947 this.input.simulateLabelClick();
5948 return false;
5949 };
5950 /**
5951 * Lookup input widget.
5952 *
5953 * Mixin that adds a menu showing suggested values to a text input. Subclasses must handle `select`
5954 * and `choose` events on #lookupMenu to make use of selections.
5955 *
5956 * @class
5957 * @abstract
5958 *
5959 * @constructor
5960 * @param {OO.ui.TextInputWidget} input Input widget
5961 * @param {Object} [config] Configuration options
5962 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
5963 */
5964 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
5965 // Config intialization
5966 config = config || {};
5967
5968 // Properties
5969 this.lookupInput = input;
5970 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
5971 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
5972 '$': OO.ui.Element.getJQuery( this.$overlay ),
5973 'input': this.lookupInput,
5974 '$container': config.$container
5975 } );
5976 this.lookupCache = {};
5977 this.lookupQuery = null;
5978 this.lookupRequest = null;
5979 this.populating = false;
5980
5981 // Events
5982 this.$overlay.append( this.lookupMenu.$element );
5983
5984 this.lookupInput.$input.on( {
5985 'focus': OO.ui.bind( this.onLookupInputFocus, this ),
5986 'blur': OO.ui.bind( this.onLookupInputBlur, this ),
5987 'mousedown': OO.ui.bind( this.onLookupInputMouseDown, this )
5988 } );
5989 this.lookupInput.connect( this, { 'change': 'onLookupInputChange' } );
5990
5991 // Initialization
5992 this.$element.addClass( 'oo-ui-lookupWidget' );
5993 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
5994 };
5995
5996 /* Methods */
5997
5998 /**
5999 * Handle input focus event.
6000 *
6001 * @param {jQuery.Event} e Input focus event
6002 */
6003 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
6004 this.openLookupMenu();
6005 };
6006
6007 /**
6008 * Handle input blur event.
6009 *
6010 * @param {jQuery.Event} e Input blur event
6011 */
6012 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
6013 this.lookupMenu.hide();
6014 };
6015
6016 /**
6017 * Handle input mouse down event.
6018 *
6019 * @param {jQuery.Event} e Input mouse down event
6020 */
6021 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
6022 this.openLookupMenu();
6023 };
6024
6025 /**
6026 * Handle input change event.
6027 *
6028 * @param {string} value New input value
6029 */
6030 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
6031 this.openLookupMenu();
6032 };
6033
6034 /**
6035 * Get lookup menu.
6036 *
6037 * @return {OO.ui.TextInputMenuWidget}
6038 */
6039 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
6040 return this.lookupMenu;
6041 };
6042
6043 /**
6044 * Open the menu.
6045 *
6046 * @chainable
6047 */
6048 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
6049 var value = this.lookupInput.getValue();
6050
6051 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
6052 this.populateLookupMenu();
6053 if ( !this.lookupMenu.isVisible() ) {
6054 this.lookupMenu.show();
6055 }
6056 } else {
6057 this.lookupMenu.clearItems();
6058 this.lookupMenu.hide();
6059 }
6060
6061 return this;
6062 };
6063
6064 /**
6065 * Populate lookup menu with current information.
6066 *
6067 * @chainable
6068 */
6069 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
6070 if ( !this.populating ) {
6071 this.populating = true;
6072 this.getLookupMenuItems()
6073 .done( OO.ui.bind( function ( items ) {
6074 this.lookupMenu.clearItems();
6075 if ( items.length ) {
6076 this.lookupMenu.show();
6077 this.lookupMenu.addItems( items );
6078 this.initializeLookupMenuSelection();
6079 this.openLookupMenu();
6080 } else {
6081 this.lookupMenu.hide();
6082 }
6083 this.populating = false;
6084 }, this ) )
6085 .fail( OO.ui.bind( function () {
6086 this.lookupMenu.clearItems();
6087 this.populating = false;
6088 }, this ) );
6089 }
6090
6091 return this;
6092 };
6093
6094 /**
6095 * Set selection in the lookup menu with current information.
6096 *
6097 * @chainable
6098 */
6099 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
6100 if ( !this.lookupMenu.getSelectedItem() ) {
6101 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
6102 }
6103 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
6104 };
6105
6106 /**
6107 * Get lookup menu items for the current query.
6108 *
6109 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
6110 * of the done event
6111 */
6112 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
6113 var value = this.lookupInput.getValue(),
6114 deferred = $.Deferred();
6115
6116 if ( value && value !== this.lookupQuery ) {
6117 // Abort current request if query has changed
6118 if ( this.lookupRequest ) {
6119 this.lookupRequest.abort();
6120 this.lookupQuery = null;
6121 this.lookupRequest = null;
6122 }
6123 if ( value in this.lookupCache ) {
6124 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
6125 } else {
6126 this.lookupQuery = value;
6127 this.lookupRequest = this.getLookupRequest()
6128 .always( OO.ui.bind( function () {
6129 this.lookupQuery = null;
6130 this.lookupRequest = null;
6131 }, this ) )
6132 .done( OO.ui.bind( function ( data ) {
6133 this.lookupCache[value] = this.getLookupCacheItemFromData( data );
6134 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
6135 }, this ) )
6136 .fail( function () {
6137 deferred.reject();
6138 } );
6139 this.pushPending();
6140 this.lookupRequest.always( OO.ui.bind( function () {
6141 this.popPending();
6142 }, this ) );
6143 }
6144 }
6145 return deferred.promise();
6146 };
6147
6148 /**
6149 * Get a new request object of the current lookup query value.
6150 *
6151 * @abstract
6152 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
6153 */
6154 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
6155 // Stub, implemented in subclass
6156 return null;
6157 };
6158
6159 /**
6160 * Handle successful lookup request.
6161 *
6162 * Overriding methods should call #populateLookupMenu when results are available and cache results
6163 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
6164 *
6165 * @abstract
6166 * @param {Mixed} data Response from server
6167 */
6168 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
6169 // Stub, implemented in subclass
6170 };
6171
6172 /**
6173 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
6174 *
6175 * @abstract
6176 * @param {Mixed} data Cached result data, usually an array
6177 * @return {OO.ui.MenuItemWidget[]} Menu items
6178 */
6179 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
6180 // Stub, implemented in subclass
6181 return [];
6182 };
6183 /**
6184 * Option widget.
6185 *
6186 * Use with OO.ui.SelectWidget.
6187 *
6188 * @class
6189 * @extends OO.ui.Widget
6190 * @mixins OO.ui.IconedElement
6191 * @mixins OO.ui.LabeledElement
6192 * @mixins OO.ui.IndicatedElement
6193 * @mixins OO.ui.FlaggableElement
6194 *
6195 * @constructor
6196 * @param {Mixed} data Option data
6197 * @param {Object} [config] Configuration options
6198 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
6199 */
6200 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
6201 // Config intialization
6202 config = config || {};
6203
6204 // Parent constructor
6205 OO.ui.OptionWidget.super.call( this, config );
6206
6207 // Mixin constructors
6208 OO.ui.ItemWidget.call( this );
6209 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
6210 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
6211 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
6212 OO.ui.FlaggableElement.call( this, config );
6213
6214 // Properties
6215 this.data = data;
6216 this.selected = false;
6217 this.highlighted = false;
6218 this.pressed = false;
6219
6220 // Initialization
6221 this.$element
6222 .data( 'oo-ui-optionWidget', this )
6223 .attr( 'rel', config.rel )
6224 .addClass( 'oo-ui-optionWidget' )
6225 .append( this.$label );
6226 this.$element
6227 .prepend( this.$icon )
6228 .append( this.$indicator );
6229 };
6230
6231 /* Setup */
6232
6233 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6234 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
6235 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconedElement );
6236 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabeledElement );
6237 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatedElement );
6238 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggableElement );
6239
6240 /* Static Properties */
6241
6242 OO.ui.OptionWidget.static.tagName = 'li';
6243
6244 OO.ui.OptionWidget.static.selectable = true;
6245
6246 OO.ui.OptionWidget.static.highlightable = true;
6247
6248 OO.ui.OptionWidget.static.pressable = true;
6249
6250 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6251
6252 /* Methods */
6253
6254 /**
6255 * Check if option can be selected.
6256 *
6257 * @return {boolean} Item is selectable
6258 */
6259 OO.ui.OptionWidget.prototype.isSelectable = function () {
6260 return this.constructor.static.selectable && !this.isDisabled();
6261 };
6262
6263 /**
6264 * Check if option can be highlighted.
6265 *
6266 * @return {boolean} Item is highlightable
6267 */
6268 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6269 return this.constructor.static.highlightable && !this.isDisabled();
6270 };
6271
6272 /**
6273 * Check if option can be pressed.
6274 *
6275 * @return {boolean} Item is pressable
6276 */
6277 OO.ui.OptionWidget.prototype.isPressable = function () {
6278 return this.constructor.static.pressable && !this.isDisabled();
6279 };
6280
6281 /**
6282 * Check if option is selected.
6283 *
6284 * @return {boolean} Item is selected
6285 */
6286 OO.ui.OptionWidget.prototype.isSelected = function () {
6287 return this.selected;
6288 };
6289
6290 /**
6291 * Check if option is highlighted.
6292 *
6293 * @return {boolean} Item is highlighted
6294 */
6295 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6296 return this.highlighted;
6297 };
6298
6299 /**
6300 * Check if option is pressed.
6301 *
6302 * @return {boolean} Item is pressed
6303 */
6304 OO.ui.OptionWidget.prototype.isPressed = function () {
6305 return this.pressed;
6306 };
6307
6308 /**
6309 * Set selected state.
6310 *
6311 * @param {boolean} [state=false] Select option
6312 * @chainable
6313 */
6314 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6315 if ( this.constructor.static.selectable ) {
6316 this.selected = !!state;
6317 if ( this.selected ) {
6318 this.$element.addClass( 'oo-ui-optionWidget-selected' );
6319 if ( this.constructor.static.scrollIntoViewOnSelect ) {
6320 this.scrollElementIntoView();
6321 }
6322 } else {
6323 this.$element.removeClass( 'oo-ui-optionWidget-selected' );
6324 }
6325 }
6326 return this;
6327 };
6328
6329 /**
6330 * Set highlighted state.
6331 *
6332 * @param {boolean} [state=false] Highlight option
6333 * @chainable
6334 */
6335 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6336 if ( this.constructor.static.highlightable ) {
6337 this.highlighted = !!state;
6338 if ( this.highlighted ) {
6339 this.$element.addClass( 'oo-ui-optionWidget-highlighted' );
6340 } else {
6341 this.$element.removeClass( 'oo-ui-optionWidget-highlighted' );
6342 }
6343 }
6344 return this;
6345 };
6346
6347 /**
6348 * Set pressed state.
6349 *
6350 * @param {boolean} [state=false] Press option
6351 * @chainable
6352 */
6353 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6354 if ( this.constructor.static.pressable ) {
6355 this.pressed = !!state;
6356 if ( this.pressed ) {
6357 this.$element.addClass( 'oo-ui-optionWidget-pressed' );
6358 } else {
6359 this.$element.removeClass( 'oo-ui-optionWidget-pressed' );
6360 }
6361 }
6362 return this;
6363 };
6364
6365 /**
6366 * Make the option's highlight flash.
6367 *
6368 * While flashing, the visual style of the pressed state is removed if present.
6369 *
6370 * @return {jQuery.Promise} Promise resolved when flashing is done
6371 */
6372 OO.ui.OptionWidget.prototype.flash = function () {
6373 var $this = this.$element,
6374 deferred = $.Deferred();
6375
6376 if ( !this.isDisabled() && this.constructor.static.pressable ) {
6377 $this.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
6378 setTimeout( OO.ui.bind( function () {
6379 // Restore original classes
6380 $this
6381 .toggleClass( 'oo-ui-optionWidget-highlighted', this.highlighted )
6382 .toggleClass( 'oo-ui-optionWidget-pressed', this.pressed );
6383 setTimeout( function () {
6384 deferred.resolve();
6385 }, 100 );
6386 }, this ), 100 );
6387 }
6388
6389 return deferred.promise();
6390 };
6391
6392 /**
6393 * Get option data.
6394 *
6395 * @return {Mixed} Option data
6396 */
6397 OO.ui.OptionWidget.prototype.getData = function () {
6398 return this.data;
6399 };
6400 /**
6401 * Selection of options.
6402 *
6403 * Use together with OO.ui.OptionWidget.
6404 *
6405 * @class
6406 * @extends OO.ui.Widget
6407 * @mixins OO.ui.GroupElement
6408 *
6409 * @constructor
6410 * @param {Object} [config] Configuration options
6411 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
6412 */
6413 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6414 // Config intialization
6415 config = config || {};
6416
6417 // Parent constructor
6418 OO.ui.SelectWidget.super.call( this, config );
6419
6420 // Mixin constructors
6421 OO.ui.GroupWidget.call( this, this.$element, config );
6422
6423 // Properties
6424 this.pressed = false;
6425 this.selecting = null;
6426 this.hashes = {};
6427 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
6428 this.onMouseMoveHandler = OO.ui.bind( this.onMouseMove, this );
6429
6430 // Events
6431 this.$element.on( {
6432 'mousedown': OO.ui.bind( this.onMouseDown, this ),
6433 'mouseover': OO.ui.bind( this.onMouseOver, this ),
6434 'mouseleave': OO.ui.bind( this.onMouseLeave, this )
6435 } );
6436
6437 // Initialization
6438 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
6439 if ( $.isArray( config.items ) ) {
6440 this.addItems( config.items );
6441 }
6442 };
6443
6444 /* Setup */
6445
6446 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6447
6448 // Need to mixin base class as well
6449 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
6450 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
6451
6452 /* Events */
6453
6454 /**
6455 * @event highlight
6456 * @param {OO.ui.OptionWidget|null} item Highlighted item
6457 */
6458
6459 /**
6460 * @event press
6461 * @param {OO.ui.OptionWidget|null} item Pressed item
6462 */
6463
6464 /**
6465 * @event select
6466 * @param {OO.ui.OptionWidget|null} item Selected item
6467 */
6468
6469 /**
6470 * @event choose
6471 * @param {OO.ui.OptionWidget|null} item Chosen item
6472 */
6473
6474 /**
6475 * @event add
6476 * @param {OO.ui.OptionWidget[]} items Added items
6477 * @param {number} index Index items were added at
6478 */
6479
6480 /**
6481 * @event remove
6482 * @param {OO.ui.OptionWidget[]} items Removed items
6483 */
6484
6485 /* Static Properties */
6486
6487 OO.ui.SelectWidget.static.tagName = 'ul';
6488
6489 /* Methods */
6490
6491 /**
6492 * Handle mouse down events.
6493 *
6494 * @private
6495 * @param {jQuery.Event} e Mouse down event
6496 */
6497 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6498 var item;
6499
6500 if ( !this.isDisabled() && e.which === 1 ) {
6501 this.togglePressed( true );
6502 item = this.getTargetItem( e );
6503 if ( item && item.isSelectable() ) {
6504 this.pressItem( item );
6505 this.selecting = item;
6506 this.getElementDocument().addEventListener(
6507 'mouseup', this.onMouseUpHandler, true
6508 );
6509 this.getElementDocument().addEventListener(
6510 'mousemove', this.onMouseMoveHandler, true
6511 );
6512 }
6513 }
6514 return false;
6515 };
6516
6517 /**
6518 * Handle mouse up events.
6519 *
6520 * @private
6521 * @param {jQuery.Event} e Mouse up event
6522 */
6523 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6524 var item;
6525
6526 this.togglePressed( false );
6527 if ( !this.selecting ) {
6528 item = this.getTargetItem( e );
6529 if ( item && item.isSelectable() ) {
6530 this.selecting = item;
6531 }
6532 }
6533 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
6534 this.pressItem( null );
6535 this.chooseItem( this.selecting );
6536 this.selecting = null;
6537 }
6538
6539 this.getElementDocument().removeEventListener(
6540 'mouseup', this.onMouseUpHandler, true
6541 );
6542 this.getElementDocument().removeEventListener(
6543 'mousemove', this.onMouseMoveHandler, true
6544 );
6545
6546 return false;
6547 };
6548
6549 /**
6550 * Handle mouse move events.
6551 *
6552 * @private
6553 * @param {jQuery.Event} e Mouse move event
6554 */
6555 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6556 var item;
6557
6558 if ( !this.isDisabled() && this.pressed ) {
6559 item = this.getTargetItem( e );
6560 if ( item && item !== this.selecting && item.isSelectable() ) {
6561 this.pressItem( item );
6562 this.selecting = item;
6563 }
6564 }
6565 return false;
6566 };
6567
6568 /**
6569 * Handle mouse over events.
6570 *
6571 * @private
6572 * @param {jQuery.Event} e Mouse over event
6573 */
6574 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6575 var item;
6576
6577 if ( !this.isDisabled() ) {
6578 item = this.getTargetItem( e );
6579 this.highlightItem( item && item.isHighlightable() ? item : null );
6580 }
6581 return false;
6582 };
6583
6584 /**
6585 * Handle mouse leave events.
6586 *
6587 * @private
6588 * @param {jQuery.Event} e Mouse over event
6589 */
6590 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6591 if ( !this.isDisabled() ) {
6592 this.highlightItem( null );
6593 }
6594 return false;
6595 };
6596
6597 /**
6598 * Get the closest item to a jQuery.Event.
6599 *
6600 * @private
6601 * @param {jQuery.Event} e
6602 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6603 */
6604 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
6605 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
6606 if ( $item.length ) {
6607 return $item.data( 'oo-ui-optionWidget' );
6608 }
6609 return null;
6610 };
6611
6612 /**
6613 * Get selected item.
6614 *
6615 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6616 */
6617 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
6618 var i, len;
6619
6620 for ( i = 0, len = this.items.length; i < len; i++ ) {
6621 if ( this.items[i].isSelected() ) {
6622 return this.items[i];
6623 }
6624 }
6625 return null;
6626 };
6627
6628 /**
6629 * Get highlighted item.
6630 *
6631 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6632 */
6633 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
6634 var i, len;
6635
6636 for ( i = 0, len = this.items.length; i < len; i++ ) {
6637 if ( this.items[i].isHighlighted() ) {
6638 return this.items[i];
6639 }
6640 }
6641 return null;
6642 };
6643
6644 /**
6645 * Get an existing item with equivilant data.
6646 *
6647 * @param {Object} data Item data to search for
6648 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
6649 */
6650 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
6651 var hash = OO.getHash( data );
6652
6653 if ( hash in this.hashes ) {
6654 return this.hashes[hash];
6655 }
6656
6657 return null;
6658 };
6659
6660 /**
6661 * Toggle pressed state.
6662 *
6663 * @param {boolean} pressed An option is being pressed
6664 */
6665 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6666 if ( pressed === undefined ) {
6667 pressed = !this.pressed;
6668 }
6669 if ( pressed !== this.pressed ) {
6670 this.$element.toggleClass( 'oo-ui-selectWidget-pressed', pressed );
6671 this.$element.toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6672 this.pressed = pressed;
6673 }
6674 };
6675
6676 /**
6677 * Highlight an item.
6678 *
6679 * Highlighting is mutually exclusive.
6680 *
6681 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
6682 * @fires highlight
6683 * @chainable
6684 */
6685 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6686 var i, len, highlighted,
6687 changed = false;
6688
6689 for ( i = 0, len = this.items.length; i < len; i++ ) {
6690 highlighted = this.items[i] === item;
6691 if ( this.items[i].isHighlighted() !== highlighted ) {
6692 this.items[i].setHighlighted( highlighted );
6693 changed = true;
6694 }
6695 }
6696 if ( changed ) {
6697 this.emit( 'highlight', item );
6698 }
6699
6700 return this;
6701 };
6702
6703 /**
6704 * Select an item.
6705 *
6706 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6707 * @fires select
6708 * @chainable
6709 */
6710 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6711 var i, len, selected,
6712 changed = false;
6713
6714 for ( i = 0, len = this.items.length; i < len; i++ ) {
6715 selected = this.items[i] === item;
6716 if ( this.items[i].isSelected() !== selected ) {
6717 this.items[i].setSelected( selected );
6718 changed = true;
6719 }
6720 }
6721 if ( changed ) {
6722 this.emit( 'select', item );
6723 }
6724
6725 return this;
6726 };
6727
6728 /**
6729 * Press an item.
6730 *
6731 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6732 * @fires press
6733 * @chainable
6734 */
6735 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6736 var i, len, pressed,
6737 changed = false;
6738
6739 for ( i = 0, len = this.items.length; i < len; i++ ) {
6740 pressed = this.items[i] === item;
6741 if ( this.items[i].isPressed() !== pressed ) {
6742 this.items[i].setPressed( pressed );
6743 changed = true;
6744 }
6745 }
6746 if ( changed ) {
6747 this.emit( 'press', item );
6748 }
6749
6750 return this;
6751 };
6752
6753 /**
6754 * Choose an item.
6755 *
6756 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
6757 * an item is selected using the keyboard or mouse.
6758 *
6759 * @param {OO.ui.OptionWidget} item Item to choose
6760 * @fires choose
6761 * @chainable
6762 */
6763 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6764 this.selectItem( item );
6765 this.emit( 'choose', item );
6766
6767 return this;
6768 };
6769
6770 /**
6771 * Get an item relative to another one.
6772 *
6773 * @param {OO.ui.OptionWidget} item Item to start at
6774 * @param {number} direction Direction to move in
6775 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
6776 */
6777 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
6778 var inc = direction > 0 ? 1 : -1,
6779 len = this.items.length,
6780 index = item instanceof OO.ui.OptionWidget ?
6781 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
6782 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
6783 i = inc > 0 ?
6784 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
6785 Math.max( index, -1 ) :
6786 // Default to n-1 instead of -1, if nothing is selected let's start at the end
6787 Math.min( index, len );
6788
6789 while ( true ) {
6790 i = ( i + inc + len ) % len;
6791 item = this.items[i];
6792 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6793 return item;
6794 }
6795 // Stop iterating when we've looped all the way around
6796 if ( i === stopAt ) {
6797 break;
6798 }
6799 }
6800 return null;
6801 };
6802
6803 /**
6804 * Get the next selectable item.
6805 *
6806 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
6807 */
6808 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
6809 var i, len, item;
6810
6811 for ( i = 0, len = this.items.length; i < len; i++ ) {
6812 item = this.items[i];
6813 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6814 return item;
6815 }
6816 }
6817
6818 return null;
6819 };
6820
6821 /**
6822 * Add items.
6823 *
6824 * When items are added with the same values as existing items, the existing items will be
6825 * automatically removed before the new items are added.
6826 *
6827 * @param {OO.ui.OptionWidget[]} items Items to add
6828 * @param {number} [index] Index to insert items after
6829 * @fires add
6830 * @chainable
6831 */
6832 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6833 var i, len, item, hash,
6834 remove = [];
6835
6836 for ( i = 0, len = items.length; i < len; i++ ) {
6837 item = items[i];
6838 hash = OO.getHash( item.getData() );
6839 if ( hash in this.hashes ) {
6840 // Remove item with same value
6841 remove.push( this.hashes[hash] );
6842 }
6843 this.hashes[hash] = item;
6844 }
6845 if ( remove.length ) {
6846 this.removeItems( remove );
6847 }
6848
6849 // Mixin method
6850 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
6851
6852 // Always provide an index, even if it was omitted
6853 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
6854
6855 return this;
6856 };
6857
6858 /**
6859 * Remove items.
6860 *
6861 * Items will be detached, not removed, so they can be used later.
6862 *
6863 * @param {OO.ui.OptionWidget[]} items Items to remove
6864 * @fires remove
6865 * @chainable
6866 */
6867 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
6868 var i, len, item, hash;
6869
6870 for ( i = 0, len = items.length; i < len; i++ ) {
6871 item = items[i];
6872 hash = OO.getHash( item.getData() );
6873 if ( hash in this.hashes ) {
6874 // Remove existing item
6875 delete this.hashes[hash];
6876 }
6877 if ( item.isSelected() ) {
6878 this.selectItem( null );
6879 }
6880 }
6881
6882 // Mixin method
6883 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
6884
6885 this.emit( 'remove', items );
6886
6887 return this;
6888 };
6889
6890 /**
6891 * Clear all items.
6892 *
6893 * Items will be detached, not removed, so they can be used later.
6894 *
6895 * @fires remove
6896 * @chainable
6897 */
6898 OO.ui.SelectWidget.prototype.clearItems = function () {
6899 var items = this.items.slice();
6900
6901 // Clear all items
6902 this.hashes = {};
6903 // Mixin method
6904 OO.ui.GroupWidget.prototype.clearItems.call( this );
6905 this.selectItem( null );
6906
6907 this.emit( 'remove', items );
6908
6909 return this;
6910 };
6911 /**
6912 * Menu item widget.
6913 *
6914 * Use with OO.ui.MenuWidget.
6915 *
6916 * @class
6917 * @extends OO.ui.OptionWidget
6918 *
6919 * @constructor
6920 * @param {Mixed} data Item data
6921 * @param {Object} [config] Configuration options
6922 */
6923 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
6924 // Configuration initialization
6925 config = $.extend( { 'icon': 'check' }, config );
6926
6927 // Parent constructor
6928 OO.ui.MenuItemWidget.super.call( this, data, config );
6929
6930 // Initialization
6931 this.$element.addClass( 'oo-ui-menuItemWidget' );
6932 };
6933
6934 /* Setup */
6935
6936 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.OptionWidget );
6937 /**
6938 * Menu widget.
6939 *
6940 * Use together with OO.ui.MenuItemWidget.
6941 *
6942 * @class
6943 * @extends OO.ui.SelectWidget
6944 * @mixins OO.ui.ClippableElement
6945 *
6946 * @constructor
6947 * @param {Object} [config] Configuration options
6948 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
6949 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
6950 */
6951 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
6952 // Config intialization
6953 config = config || {};
6954
6955 // Parent constructor
6956 OO.ui.MenuWidget.super.call( this, config );
6957
6958 // Mixin constructors
6959 OO.ui.ClippableElement.call( this, this.$group, config );
6960
6961 // Properties
6962 this.autoHide = config.autoHide === undefined || !!config.autoHide;
6963 this.newItems = null;
6964 this.$input = config.input ? config.input.$input : null;
6965 this.$previousFocus = null;
6966 this.isolated = !config.input;
6967 this.visible = false;
6968 this.flashing = false;
6969 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
6970 this.onDocumentMouseDownHandler = OO.ui.bind( this.onDocumentMouseDown, this );
6971
6972 // Initialization
6973 this.$element.hide().addClass( 'oo-ui-menuWidget' );
6974 };
6975
6976 /* Setup */
6977
6978 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
6979 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
6980
6981 /* Methods */
6982
6983 /**
6984 * Handles document mouse down events.
6985 *
6986 * @param {jQuery.Event} e Key down event
6987 */
6988 OO.ui.MenuWidget.prototype.onDocumentMouseDown = function ( e ) {
6989 if ( !$.contains( this.$element[0], e.target ) ) {
6990 this.hide();
6991 }
6992 };
6993
6994 /**
6995 * Handles key down events.
6996 *
6997 * @param {jQuery.Event} e Key down event
6998 */
6999 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
7000 var nextItem,
7001 handled = false,
7002 highlightItem = this.getHighlightedItem();
7003
7004 if ( !this.isDisabled() && this.visible ) {
7005 if ( !highlightItem ) {
7006 highlightItem = this.getSelectedItem();
7007 }
7008 switch ( e.keyCode ) {
7009 case OO.ui.Keys.ENTER:
7010 this.chooseItem( highlightItem );
7011 handled = true;
7012 break;
7013 case OO.ui.Keys.UP:
7014 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
7015 handled = true;
7016 break;
7017 case OO.ui.Keys.DOWN:
7018 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
7019 handled = true;
7020 break;
7021 case OO.ui.Keys.ESCAPE:
7022 if ( highlightItem ) {
7023 highlightItem.setHighlighted( false );
7024 }
7025 this.hide();
7026 handled = true;
7027 break;
7028 }
7029
7030 if ( nextItem ) {
7031 this.highlightItem( nextItem );
7032 nextItem.scrollElementIntoView();
7033 }
7034
7035 if ( handled ) {
7036 e.preventDefault();
7037 e.stopPropagation();
7038 return false;
7039 }
7040 }
7041 };
7042
7043 /**
7044 * Check if the menu is visible.
7045 *
7046 * @return {boolean} Menu is visible
7047 */
7048 OO.ui.MenuWidget.prototype.isVisible = function () {
7049 return this.visible;
7050 };
7051
7052 /**
7053 * Bind key down listener.
7054 */
7055 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
7056 if ( this.$input ) {
7057 this.$input.on( 'keydown', this.onKeyDownHandler );
7058 } else {
7059 // Capture menu navigation keys
7060 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
7061 }
7062 };
7063
7064 /**
7065 * Unbind key down listener.
7066 */
7067 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
7068 if ( this.$input ) {
7069 this.$input.off( 'keydown' );
7070 } else {
7071 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
7072 }
7073 };
7074
7075 /**
7076 * Choose an item.
7077 *
7078 * This will close the menu when done, unlike selectItem which only changes selection.
7079 *
7080 * @param {OO.ui.OptionWidget} item Item to choose
7081 * @chainable
7082 */
7083 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
7084 // Parent method
7085 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
7086
7087 if ( item && !this.flashing ) {
7088 this.flashing = true;
7089 item.flash().done( OO.ui.bind( function () {
7090 this.hide();
7091 this.flashing = false;
7092 }, this ) );
7093 } else {
7094 this.hide();
7095 }
7096
7097 return this;
7098 };
7099
7100 /**
7101 * Add items.
7102 *
7103 * Adding an existing item (by value) will move it.
7104 *
7105 * @param {OO.ui.MenuItemWidget[]} items Items to add
7106 * @param {number} [index] Index to insert items after
7107 * @chainable
7108 */
7109 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
7110 var i, len, item;
7111
7112 // Parent method
7113 OO.ui.MenuWidget.super.prototype.addItems.call( this, items, index );
7114
7115 // Auto-initialize
7116 if ( !this.newItems ) {
7117 this.newItems = [];
7118 }
7119
7120 for ( i = 0, len = items.length; i < len; i++ ) {
7121 item = items[i];
7122 if ( this.visible ) {
7123 // Defer fitting label until
7124 item.fitLabel();
7125 } else {
7126 this.newItems.push( item );
7127 }
7128 }
7129
7130 return this;
7131 };
7132
7133 /**
7134 * Show the menu.
7135 *
7136 * @chainable
7137 */
7138 OO.ui.MenuWidget.prototype.show = function () {
7139 var i, len;
7140
7141 if ( this.items.length ) {
7142 this.$element.show();
7143 this.visible = true;
7144 this.bindKeyDownListener();
7145
7146 // Change focus to enable keyboard navigation
7147 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
7148 this.$previousFocus = this.$( ':focus' );
7149 this.$input.focus();
7150 }
7151 if ( this.newItems && this.newItems.length ) {
7152 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
7153 this.newItems[i].fitLabel();
7154 }
7155 this.newItems = null;
7156 }
7157
7158 this.setClipping( true );
7159
7160 // Auto-hide
7161 if ( this.autoHide ) {
7162 this.getElementDocument().addEventListener(
7163 'mousedown', this.onDocumentMouseDownHandler, true
7164 );
7165 }
7166 }
7167
7168 return this;
7169 };
7170
7171 /**
7172 * Hide the menu.
7173 *
7174 * @chainable
7175 */
7176 OO.ui.MenuWidget.prototype.hide = function () {
7177 this.$element.hide();
7178 this.visible = false;
7179 this.unbindKeyDownListener();
7180
7181 if ( this.isolated && this.$previousFocus ) {
7182 this.$previousFocus.focus();
7183 this.$previousFocus = null;
7184 }
7185
7186 this.getElementDocument().removeEventListener(
7187 'mousedown', this.onDocumentMouseDownHandler, true
7188 );
7189
7190 this.setClipping( false );
7191
7192 return this;
7193 };
7194 /**
7195 * Inline menu of options.
7196 *
7197 * Use with OO.ui.MenuOptionWidget.
7198 *
7199 * @class
7200 * @extends OO.ui.Widget
7201 * @mixins OO.ui.IconedElement
7202 * @mixins OO.ui.IndicatedElement
7203 * @mixins OO.ui.LabeledElement
7204 * @mixins OO.ui.TitledElement
7205 *
7206 * @constructor
7207 * @param {Object} [config] Configuration options
7208 * @cfg {Object} [menu] Configuration options to pass to menu widget
7209 */
7210 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
7211 // Configuration initialization
7212 config = $.extend( { 'indicator': 'down' }, config );
7213
7214 // Parent constructor
7215 OO.ui.InlineMenuWidget.super.call( this, config );
7216
7217 // Mixin constructors
7218 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
7219 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
7220 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
7221 OO.ui.TitledElement.call( this, this.$label, config );
7222
7223 // Properties
7224 this.menu = new OO.ui.MenuWidget( $.extend( { '$': this.$ }, config.menu ) );
7225 this.$handle = this.$( '<span>' );
7226
7227 // Events
7228 this.$element.on( { 'click': OO.ui.bind( this.onClick, this ) } );
7229 this.menu.connect( this, { 'select': 'onMenuSelect' } );
7230
7231 // Initialization
7232 this.$handle
7233 .addClass( 'oo-ui-inlineMenuWidget-handle' )
7234 .append( this.$icon, this.$label, this.$indicator );
7235 this.$element
7236 .addClass( 'oo-ui-inlineMenuWidget' )
7237 .append( this.$handle, this.menu.$element );
7238 };
7239
7240 /* Setup */
7241
7242 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
7243 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconedElement );
7244 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatedElement );
7245 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabeledElement );
7246 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
7247
7248 /* Methods */
7249
7250 /**
7251 * Get the menu.
7252 *
7253 * @return {OO.ui.MenuWidget} Menu of widget
7254 */
7255 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
7256 return this.menu;
7257 };
7258
7259 /**
7260 * Handles menu select events.
7261 *
7262 * @param {OO.ui.MenuItemWidget} item Selected menu item
7263 */
7264 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
7265 var selectedLabel;
7266
7267 if ( !item ) {
7268 return;
7269 }
7270
7271 selectedLabel = item.getLabel();
7272
7273 // If the label is a DOM element, clone it, because setLabel will append() it
7274 if ( selectedLabel instanceof jQuery ) {
7275 selectedLabel = selectedLabel.clone();
7276 }
7277
7278 this.setLabel( selectedLabel );
7279 };
7280
7281 /**
7282 * Handles mouse click events.
7283 *
7284 * @param {jQuery.Event} e Mouse click event
7285 */
7286 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
7287 // Skip clicks within the menu
7288 if ( $.contains( this.menu.$element[0], e.target ) ) {
7289 return;
7290 }
7291
7292 if ( !this.isDisabled() ) {
7293 if ( this.menu.isVisible() ) {
7294 this.menu.hide();
7295 } else {
7296 this.menu.show();
7297 }
7298 }
7299 return false;
7300 };
7301 /**
7302 * Menu section item widget.
7303 *
7304 * Use with OO.ui.MenuWidget.
7305 *
7306 * @class
7307 * @extends OO.ui.OptionWidget
7308 *
7309 * @constructor
7310 * @param {Mixed} data Item data
7311 * @param {Object} [config] Configuration options
7312 */
7313 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
7314 // Parent constructor
7315 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
7316
7317 // Initialization
7318 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
7319 };
7320
7321 /* Setup */
7322
7323 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.OptionWidget );
7324
7325 /* Static Properties */
7326
7327 OO.ui.MenuSectionItemWidget.static.selectable = false;
7328
7329 OO.ui.MenuSectionItemWidget.static.highlightable = false;
7330 /**
7331 * Create an OO.ui.OutlineWidget object.
7332 *
7333 * Use with OO.ui.OutlineItemWidget.
7334 *
7335 * @class
7336 * @extends OO.ui.SelectWidget
7337 *
7338 * @constructor
7339 * @param {Object} [config] Configuration options
7340 */
7341 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
7342 // Config intialization
7343 config = config || {};
7344
7345 // Parent constructor
7346 OO.ui.OutlineWidget.super.call( this, config );
7347
7348 // Initialization
7349 this.$element.addClass( 'oo-ui-outlineWidget' );
7350 };
7351
7352 /* Setup */
7353
7354 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
7355 /**
7356 * Creates an OO.ui.OutlineControlsWidget object.
7357 *
7358 * Use together with OO.ui.OutlineWidget.js
7359 *
7360 * @class
7361 *
7362 * @constructor
7363 * @param {OO.ui.OutlineWidget} outline Outline to control
7364 * @param {Object} [config] Configuration options
7365 */
7366 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7367 // Configuration initialization
7368 config = $.extend( { 'icon': 'add-item' }, config );
7369
7370 // Parent constructor
7371 OO.ui.OutlineControlsWidget.super.call( this, config );
7372
7373 // Mixin constructors
7374 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
7375 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
7376
7377 // Properties
7378 this.outline = outline;
7379 this.$movers = this.$( '<div>' );
7380 this.upButton = new OO.ui.ButtonWidget( {
7381 '$': this.$,
7382 'frameless': true,
7383 'icon': 'collapse',
7384 'title': OO.ui.msg( 'ooui-outline-control-move-up' )
7385 } );
7386 this.downButton = new OO.ui.ButtonWidget( {
7387 '$': this.$,
7388 'frameless': true,
7389 'icon': 'expand',
7390 'title': OO.ui.msg( 'ooui-outline-control-move-down' )
7391 } );
7392 this.removeButton = new OO.ui.ButtonWidget( {
7393 '$': this.$,
7394 'frameless': true,
7395 'icon': 'remove',
7396 'title': OO.ui.msg( 'ooui-outline-control-remove' )
7397 } );
7398
7399 // Events
7400 outline.connect( this, {
7401 'select': 'onOutlineChange',
7402 'add': 'onOutlineChange',
7403 'remove': 'onOutlineChange'
7404 } );
7405 this.upButton.connect( this, { 'click': [ 'emit', 'move', -1 ] } );
7406 this.downButton.connect( this, { 'click': [ 'emit', 'move', 1 ] } );
7407 this.removeButton.connect( this, { 'click': [ 'emit', 'remove' ] } );
7408
7409 // Initialization
7410 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7411 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
7412 this.$movers
7413 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7414 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7415 this.$element.append( this.$icon, this.$group, this.$movers );
7416 };
7417
7418 /* Setup */
7419
7420 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7421 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7422 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconedElement );
7423
7424 /* Events */
7425
7426 /**
7427 * @event move
7428 * @param {number} places Number of places to move
7429 */
7430
7431 /**
7432 * @event remove
7433 */
7434
7435 /* Methods */
7436
7437 /**
7438 * Handle outline change events.
7439 */
7440 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7441 var i, len, firstMovable, lastMovable,
7442 items = this.outline.getItems(),
7443 selectedItem = this.outline.getSelectedItem(),
7444 movable = selectedItem && selectedItem.isMovable(),
7445 removable = selectedItem && selectedItem.isRemovable();
7446
7447 if ( movable ) {
7448 i = -1;
7449 len = items.length;
7450 while ( ++i < len ) {
7451 if ( items[i].isMovable() ) {
7452 firstMovable = items[i];
7453 break;
7454 }
7455 }
7456 i = len;
7457 while ( i-- ) {
7458 if ( items[i].isMovable() ) {
7459 lastMovable = items[i];
7460 break;
7461 }
7462 }
7463 }
7464 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7465 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7466 this.removeButton.setDisabled( !removable );
7467 };
7468 /**
7469 * Creates an OO.ui.OutlineItemWidget object.
7470 *
7471 * Use with OO.ui.OutlineWidget.
7472 *
7473 * @class
7474 * @extends OO.ui.OptionWidget
7475 *
7476 * @constructor
7477 * @param {Mixed} data Item data
7478 * @param {Object} [config] Configuration options
7479 * @cfg {number} [level] Indentation level
7480 * @cfg {boolean} [movable] Allow modification from outline controls
7481 */
7482 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
7483 // Config intialization
7484 config = config || {};
7485
7486 // Parent constructor
7487 OO.ui.OutlineItemWidget.super.call( this, data, config );
7488
7489 // Properties
7490 this.level = 0;
7491 this.movable = !!config.movable;
7492 this.removable = !!config.removable;
7493
7494 // Initialization
7495 this.$element.addClass( 'oo-ui-outlineItemWidget' );
7496 this.setLevel( config.level );
7497 };
7498
7499 /* Setup */
7500
7501 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.OptionWidget );
7502
7503 /* Static Properties */
7504
7505 OO.ui.OutlineItemWidget.static.highlightable = false;
7506
7507 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
7508
7509 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
7510
7511 OO.ui.OutlineItemWidget.static.levels = 3;
7512
7513 /* Methods */
7514
7515 /**
7516 * Check if item is movable.
7517 *
7518 * Movablilty is used by outline controls.
7519 *
7520 * @return {boolean} Item is movable
7521 */
7522 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
7523 return this.movable;
7524 };
7525
7526 /**
7527 * Check if item is removable.
7528 *
7529 * Removablilty is used by outline controls.
7530 *
7531 * @return {boolean} Item is removable
7532 */
7533 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
7534 return this.removable;
7535 };
7536
7537 /**
7538 * Get indentation level.
7539 *
7540 * @return {number} Indentation level
7541 */
7542 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
7543 return this.level;
7544 };
7545
7546 /**
7547 * Set movability.
7548 *
7549 * Movablilty is used by outline controls.
7550 *
7551 * @param {boolean} movable Item is movable
7552 * @chainable
7553 */
7554 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
7555 this.movable = !!movable;
7556 return this;
7557 };
7558
7559 /**
7560 * Set removability.
7561 *
7562 * Removablilty is used by outline controls.
7563 *
7564 * @param {boolean} movable Item is removable
7565 * @chainable
7566 */
7567 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
7568 this.removable = !!removable;
7569 return this;
7570 };
7571
7572 /**
7573 * Set indentation level.
7574 *
7575 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
7576 * @chainable
7577 */
7578 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
7579 var levels = this.constructor.static.levels,
7580 levelClass = this.constructor.static.levelClass,
7581 i = levels;
7582
7583 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
7584 while ( i-- ) {
7585 if ( this.level === i ) {
7586 this.$element.addClass( levelClass + i );
7587 } else {
7588 this.$element.removeClass( levelClass + i );
7589 }
7590 }
7591
7592 return this;
7593 };
7594 /**
7595 * Option widget that looks like a button.
7596 *
7597 * Use together with OO.ui.ButtonSelectWidget.
7598 *
7599 * @class
7600 * @extends OO.ui.OptionWidget
7601 * @mixins OO.ui.ButtonedElement
7602 * @mixins OO.ui.FlaggableElement
7603 *
7604 * @constructor
7605 * @param {Mixed} data Option data
7606 * @param {Object} [config] Configuration options
7607 */
7608 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
7609 // Parent constructor
7610 OO.ui.ButtonOptionWidget.super.call( this, data, config );
7611
7612 // Mixin constructors
7613 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
7614 OO.ui.FlaggableElement.call( this, config );
7615
7616 // Initialization
7617 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
7618 this.$button.append( this.$element.contents() );
7619 this.$element.append( this.$button );
7620 };
7621
7622 /* Setup */
7623
7624 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
7625 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonedElement );
7626 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.FlaggableElement );
7627
7628 /* Static Properties */
7629
7630 // Allow button mouse down events to pass through so they can be handled by the parent select widget
7631 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
7632
7633 /* Methods */
7634
7635 /**
7636 * @inheritdoc
7637 */
7638 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
7639 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
7640
7641 if ( this.constructor.static.selectable ) {
7642 this.setActive( state );
7643 }
7644
7645 return this;
7646 };
7647 /**
7648 * Select widget containing button options.
7649 *
7650 * Use together with OO.ui.ButtonOptionWidget.
7651 *
7652 * @class
7653 * @extends OO.ui.SelectWidget
7654 *
7655 * @constructor
7656 * @param {Object} [config] Configuration options
7657 */
7658 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
7659 // Parent constructor
7660 OO.ui.ButtonSelectWidget.super.call( this, config );
7661
7662 // Initialization
7663 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
7664 };
7665
7666 /* Setup */
7667
7668 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
7669 /**
7670 * Container for content that is overlaid and positioned absolutely.
7671 *
7672 * @class
7673 * @extends OO.ui.Widget
7674 * @mixins OO.ui.LabeledElement
7675 *
7676 * @constructor
7677 * @param {Object} [config] Configuration options
7678 * @cfg {boolean} [tail=true] Show tail pointing to origin of popup
7679 * @cfg {string} [align='center'] Alignment of popup to origin
7680 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
7681 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
7682 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
7683 * @cfg {boolean} [head] Show label and close button at the top
7684 */
7685 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
7686 // Config intialization
7687 config = config || {};
7688
7689 // Parent constructor
7690 OO.ui.PopupWidget.super.call( this, config );
7691
7692 // Mixin constructors
7693 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
7694 OO.ui.ClippableElement.call( this, this.$( '<div>' ), config );
7695
7696 // Properties
7697 this.visible = false;
7698 this.$popup = this.$( '<div>' );
7699 this.$head = this.$( '<div>' );
7700 this.$body = this.$clippable;
7701 this.$tail = this.$( '<div>' );
7702 this.$container = config.$container || this.$( 'body' );
7703 this.autoClose = !!config.autoClose;
7704 this.$autoCloseIgnore = config.$autoCloseIgnore;
7705 this.transitionTimeout = null;
7706 this.tail = false;
7707 this.align = config.align || 'center';
7708 this.closeButton = new OO.ui.ButtonWidget( { '$': this.$, 'frameless': true, 'icon': 'close' } );
7709 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
7710
7711 // Events
7712 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
7713
7714 // Initialization
7715 this.useTail( config.tail !== undefined ? !!config.tail : true );
7716 this.$body.addClass( 'oo-ui-popupWidget-body' );
7717 this.$tail.addClass( 'oo-ui-popupWidget-tail' );
7718 this.$head
7719 .addClass( 'oo-ui-popupWidget-head' )
7720 .append( this.$label, this.closeButton.$element );
7721 if ( !config.head ) {
7722 this.$head.hide();
7723 }
7724 this.$popup
7725 .addClass( 'oo-ui-popupWidget-popup' )
7726 .append( this.$head, this.$body );
7727 this.$element.hide()
7728 .addClass( 'oo-ui-popupWidget' )
7729 .append( this.$popup, this.$tail );
7730 };
7731
7732 /* Setup */
7733
7734 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
7735 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabeledElement );
7736 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
7737
7738 /* Events */
7739
7740 /**
7741 * @event hide
7742 */
7743
7744 /**
7745 * @event show
7746 */
7747
7748 /* Methods */
7749
7750 /**
7751 * Handles mouse down events.
7752 *
7753 * @param {jQuery.Event} e Mouse down event
7754 */
7755 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
7756 if (
7757 this.visible &&
7758 !$.contains( this.$element[0], e.target ) &&
7759 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
7760 ) {
7761 this.hide();
7762 }
7763 };
7764
7765 /**
7766 * Bind mouse down listener.
7767 */
7768 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
7769 // Capture clicks outside popup
7770 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
7771 };
7772
7773 /**
7774 * Handles close button click events.
7775 */
7776 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
7777 if ( this.visible ) {
7778 this.hide();
7779 }
7780 };
7781
7782 /**
7783 * Unbind mouse down listener.
7784 */
7785 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
7786 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
7787 };
7788
7789 /**
7790 * Check if the popup is visible.
7791 *
7792 * @return {boolean} Popup is visible
7793 */
7794 OO.ui.PopupWidget.prototype.isVisible = function () {
7795 return this.visible;
7796 };
7797
7798 /**
7799 * Set whether to show a tail.
7800 *
7801 * @return {boolean} Make tail visible
7802 */
7803 OO.ui.PopupWidget.prototype.useTail = function ( value ) {
7804 value = !!value;
7805 if ( this.tail !== value ) {
7806 this.tail = value;
7807 if ( value ) {
7808 this.$element.addClass( 'oo-ui-popupWidget-tailed' );
7809 } else {
7810 this.$element.removeClass( 'oo-ui-popupWidget-tailed' );
7811 }
7812 }
7813 };
7814
7815 /**
7816 * Check if showing a tail.
7817 *
7818 * @return {boolean} tail is visible
7819 */
7820 OO.ui.PopupWidget.prototype.hasTail = function () {
7821 return this.tail;
7822 };
7823
7824 /**
7825 * Show the context.
7826 *
7827 * @fires show
7828 * @chainable
7829 */
7830 OO.ui.PopupWidget.prototype.show = function () {
7831 if ( !this.visible ) {
7832 this.setClipping( true );
7833 this.$element.show();
7834 this.visible = true;
7835 this.emit( 'show' );
7836 if ( this.autoClose ) {
7837 this.bindMouseDownListener();
7838 }
7839 }
7840 return this;
7841 };
7842
7843 /**
7844 * Hide the context.
7845 *
7846 * @fires hide
7847 * @chainable
7848 */
7849 OO.ui.PopupWidget.prototype.hide = function () {
7850 if ( this.visible ) {
7851 this.setClipping( false );
7852 this.$element.hide();
7853 this.visible = false;
7854 this.emit( 'hide' );
7855 if ( this.autoClose ) {
7856 this.unbindMouseDownListener();
7857 }
7858 }
7859 return this;
7860 };
7861
7862 /**
7863 * Updates the position and size.
7864 *
7865 * @param {number} width Width
7866 * @param {number} height Height
7867 * @param {boolean} [transition=false] Use a smooth transition
7868 * @chainable
7869 */
7870 OO.ui.PopupWidget.prototype.display = function ( width, height, transition ) {
7871 var padding = 10,
7872 originOffset = Math.round( this.$element.offset().left ),
7873 containerLeft = Math.round( this.$container.offset().left ),
7874 containerWidth = this.$container.innerWidth(),
7875 containerRight = containerLeft + containerWidth,
7876 popupOffset = width * ( { 'left': 0, 'center': -0.5, 'right': -1 } )[this.align],
7877 popupLeft = popupOffset - padding,
7878 popupRight = popupOffset + padding + width + padding,
7879 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
7880 overlapRight = containerRight - ( originOffset + popupRight );
7881
7882 // Prevent transition from being interrupted
7883 clearTimeout( this.transitionTimeout );
7884 if ( transition ) {
7885 // Enable transition
7886 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
7887 }
7888
7889 if ( overlapRight < 0 ) {
7890 popupOffset += overlapRight;
7891 } else if ( overlapLeft < 0 ) {
7892 popupOffset -= overlapLeft;
7893 }
7894
7895 // Position body relative to anchor and resize
7896 this.$popup.css( {
7897 'left': popupOffset,
7898 'width': width,
7899 'height': height === undefined ? 'auto' : height
7900 } );
7901
7902 if ( transition ) {
7903 // Prevent transitioning after transition is complete
7904 this.transitionTimeout = setTimeout( OO.ui.bind( function () {
7905 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7906 }, this ), 200 );
7907 } else {
7908 // Prevent transitioning immediately
7909 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7910 }
7911
7912 return this;
7913 };
7914 /**
7915 * Button that shows and hides a popup.
7916 *
7917 * @class
7918 * @extends OO.ui.ButtonWidget
7919 * @mixins OO.ui.PopuppableElement
7920 *
7921 * @constructor
7922 * @param {Object} [config] Configuration options
7923 */
7924 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
7925 // Parent constructor
7926 OO.ui.PopupButtonWidget.super.call( this, config );
7927
7928 // Mixin constructors
7929 OO.ui.PopuppableElement.call( this, config );
7930
7931 // Initialization
7932 this.$element
7933 .addClass( 'oo-ui-popupButtonWidget' )
7934 .append( this.popup.$element );
7935 };
7936
7937 /* Setup */
7938
7939 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
7940 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopuppableElement );
7941
7942 /* Methods */
7943
7944 /**
7945 * Handles mouse click events.
7946 *
7947 * @param {jQuery.Event} e Mouse click event
7948 */
7949 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
7950 // Skip clicks within the popup
7951 if ( $.contains( this.popup.$element[0], e.target ) ) {
7952 return;
7953 }
7954
7955 if ( !this.isDisabled() ) {
7956 if ( this.popup.isVisible() ) {
7957 this.hidePopup();
7958 } else {
7959 this.showPopup();
7960 }
7961 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
7962 }
7963 return false;
7964 };
7965 /**
7966 * Search widget.
7967 *
7968 * Combines query and results selection widgets.
7969 *
7970 * @class
7971 * @extends OO.ui.Widget
7972 *
7973 * @constructor
7974 * @param {Object} [config] Configuration options
7975 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
7976 * @cfg {string} [value] Initial query value
7977 */
7978 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
7979 // Configuration intialization
7980 config = config || {};
7981
7982 // Parent constructor
7983 OO.ui.SearchWidget.super.call( this, config );
7984
7985 // Properties
7986 this.query = new OO.ui.TextInputWidget( {
7987 '$': this.$,
7988 'icon': 'search',
7989 'placeholder': config.placeholder,
7990 'value': config.value
7991 } );
7992 this.results = new OO.ui.SelectWidget( { '$': this.$ } );
7993 this.$query = this.$( '<div>' );
7994 this.$results = this.$( '<div>' );
7995
7996 // Events
7997 this.query.connect( this, {
7998 'change': 'onQueryChange',
7999 'enter': 'onQueryEnter'
8000 } );
8001 this.results.connect( this, {
8002 'highlight': 'onResultsHighlight',
8003 'select': 'onResultsSelect'
8004 } );
8005 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
8006
8007 // Initialization
8008 this.$query
8009 .addClass( 'oo-ui-searchWidget-query' )
8010 .append( this.query.$element );
8011 this.$results
8012 .addClass( 'oo-ui-searchWidget-results' )
8013 .append( this.results.$element );
8014 this.$element
8015 .addClass( 'oo-ui-searchWidget' )
8016 .append( this.$results, this.$query );
8017 };
8018
8019 /* Setup */
8020
8021 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
8022
8023 /* Events */
8024
8025 /**
8026 * @event highlight
8027 * @param {Object|null} item Item data or null if no item is highlighted
8028 */
8029
8030 /**
8031 * @event select
8032 * @param {Object|null} item Item data or null if no item is selected
8033 */
8034
8035 /* Methods */
8036
8037 /**
8038 * Handle query key down events.
8039 *
8040 * @param {jQuery.Event} e Key down event
8041 */
8042 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
8043 var highlightedItem, nextItem,
8044 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
8045
8046 if ( dir ) {
8047 highlightedItem = this.results.getHighlightedItem();
8048 if ( !highlightedItem ) {
8049 highlightedItem = this.results.getSelectedItem();
8050 }
8051 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
8052 this.results.highlightItem( nextItem );
8053 nextItem.scrollElementIntoView();
8054 }
8055 };
8056
8057 /**
8058 * Handle select widget select events.
8059 *
8060 * Clears existing results. Subclasses should repopulate items according to new query.
8061 *
8062 * @param {string} value New value
8063 */
8064 OO.ui.SearchWidget.prototype.onQueryChange = function () {
8065 // Reset
8066 this.results.clearItems();
8067 };
8068
8069 /**
8070 * Handle select widget enter key events.
8071 *
8072 * Selects highlighted item.
8073 *
8074 * @param {string} value New value
8075 */
8076 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
8077 // Reset
8078 this.results.selectItem( this.results.getHighlightedItem() );
8079 };
8080
8081 /**
8082 * Handle select widget highlight events.
8083 *
8084 * @param {OO.ui.OptionWidget} item Highlighted item
8085 * @fires highlight
8086 */
8087 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
8088 this.emit( 'highlight', item ? item.getData() : null );
8089 };
8090
8091 /**
8092 * Handle select widget select events.
8093 *
8094 * @param {OO.ui.OptionWidget} item Selected item
8095 * @fires select
8096 */
8097 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
8098 this.emit( 'select', item ? item.getData() : null );
8099 };
8100
8101 /**
8102 * Get the query input.
8103 *
8104 * @return {OO.ui.TextInputWidget} Query input
8105 */
8106 OO.ui.SearchWidget.prototype.getQuery = function () {
8107 return this.query;
8108 };
8109
8110 /**
8111 * Get the results list.
8112 *
8113 * @return {OO.ui.SelectWidget} Select list
8114 */
8115 OO.ui.SearchWidget.prototype.getResults = function () {
8116 return this.results;
8117 };
8118 /**
8119 * Text input widget.
8120 *
8121 * @class
8122 * @extends OO.ui.InputWidget
8123 *
8124 * @constructor
8125 * @param {Object} [config] Configuration options
8126 * @cfg {string} [placeholder] Placeholder text
8127 * @cfg {string} [icon] Symbolic name of icon
8128 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8129 * @cfg {boolean} [autosize=false] Automatically resize to fit content
8130 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
8131 */
8132 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
8133 config = $.extend( { 'maxRows': 10 }, config );
8134
8135 // Parent constructor
8136 OO.ui.TextInputWidget.super.call( this, config );
8137
8138 // Properties
8139 this.pending = 0;
8140 this.multiline = !!config.multiline;
8141 this.autosize = !!config.autosize;
8142 this.maxRows = config.maxRows;
8143
8144 // Events
8145 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
8146 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
8147
8148 // Initialization
8149 this.$element.addClass( 'oo-ui-textInputWidget' );
8150 if ( config.icon ) {
8151 this.$element.addClass( 'oo-ui-textInputWidget-decorated' );
8152 this.$element.append(
8153 this.$( '<span>' )
8154 .addClass( 'oo-ui-textInputWidget-icon oo-ui-icon-' + config.icon )
8155 .mousedown( OO.ui.bind( function () {
8156 this.$input.focus();
8157 return false;
8158 }, this ) )
8159 );
8160 }
8161 if ( config.placeholder ) {
8162 this.$input.attr( 'placeholder', config.placeholder );
8163 }
8164 };
8165
8166 /* Setup */
8167
8168 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8169
8170 /* Events */
8171
8172 /**
8173 * User presses enter inside the text box.
8174 *
8175 * Not called if input is multiline.
8176 *
8177 * @event enter
8178 */
8179
8180 /* Methods */
8181
8182 /**
8183 * Handle key press events.
8184 *
8185 * @param {jQuery.Event} e Key press event
8186 * @fires enter If enter key is pressed and input is not multiline
8187 */
8188 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8189 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8190 this.emit( 'enter' );
8191 }
8192 };
8193
8194 /**
8195 * Handle element attach events.
8196 *
8197 * @param {jQuery.Event} e Element attach event
8198 */
8199 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8200 this.adjustSize();
8201 };
8202
8203 /**
8204 * @inheritdoc
8205 */
8206 OO.ui.TextInputWidget.prototype.onEdit = function () {
8207 this.adjustSize();
8208
8209 // Parent method
8210 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
8211 };
8212
8213 /**
8214 * Automatically adjust the size of the text input.
8215 *
8216 * This only affects multi-line inputs that are auto-sized.
8217 *
8218 * @chainable
8219 */
8220 OO.ui.TextInputWidget.prototype.adjustSize = function () {
8221 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
8222
8223 if ( this.multiline && this.autosize ) {
8224 $clone = this.$input.clone()
8225 .val( this.$input.val() )
8226 .css( { 'height': 0 } )
8227 .insertAfter( this.$input );
8228 // Set inline height property to 0 to measure scroll height
8229 scrollHeight = $clone[0].scrollHeight;
8230 // Remove inline height property to measure natural heights
8231 $clone.css( 'height', '' );
8232 innerHeight = $clone.innerHeight();
8233 outerHeight = $clone.outerHeight();
8234 // Measure max rows height
8235 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
8236 maxInnerHeight = $clone.innerHeight();
8237 $clone.removeAttr( 'rows' ).css( 'height', '' );
8238 $clone.remove();
8239 idealHeight = Math.min( maxInnerHeight, scrollHeight );
8240 // Only apply inline height when expansion beyond natural height is needed
8241 this.$input.css(
8242 'height',
8243 // Use the difference between the inner and outer height as a buffer
8244 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
8245 );
8246 }
8247 return this;
8248 };
8249
8250 /**
8251 * Get input element.
8252 *
8253 * @param {Object} [config] Configuration options
8254 * @return {jQuery} Input element
8255 */
8256 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
8257 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
8258 };
8259
8260 /* Methods */
8261
8262 /**
8263 * Check if input supports multiple lines.
8264 *
8265 * @return {boolean}
8266 */
8267 OO.ui.TextInputWidget.prototype.isMultiline = function () {
8268 return !!this.multiline;
8269 };
8270
8271 /**
8272 * Check if input automatically adjusts its size.
8273 *
8274 * @return {boolean}
8275 */
8276 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
8277 return !!this.autosize;
8278 };
8279
8280 /**
8281 * Check if input is pending.
8282 *
8283 * @return {boolean}
8284 */
8285 OO.ui.TextInputWidget.prototype.isPending = function () {
8286 return !!this.pending;
8287 };
8288
8289 /**
8290 * Increase the pending stack.
8291 *
8292 * @chainable
8293 */
8294 OO.ui.TextInputWidget.prototype.pushPending = function () {
8295 if ( this.pending === 0 ) {
8296 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
8297 this.$input.addClass( 'oo-ui-texture-pending' );
8298 }
8299 this.pending++;
8300
8301 return this;
8302 };
8303
8304 /**
8305 * Reduce the pending stack.
8306 *
8307 * Clamped at zero.
8308 *
8309 * @chainable
8310 */
8311 OO.ui.TextInputWidget.prototype.popPending = function () {
8312 if ( this.pending === 1 ) {
8313 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
8314 this.$input.removeClass( 'oo-ui-texture-pending' );
8315 }
8316 this.pending = Math.max( 0, this.pending - 1 );
8317
8318 return this;
8319 };
8320
8321 /**
8322 * Select the contents of the input.
8323 *
8324 * @chainable
8325 */
8326 OO.ui.TextInputWidget.prototype.select = function () {
8327 this.$input.select();
8328 return this;
8329 };
8330 /**
8331 * Menu for a text input widget.
8332 *
8333 * @class
8334 * @extends OO.ui.MenuWidget
8335 *
8336 * @constructor
8337 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
8338 * @param {Object} [config] Configuration options
8339 * @cfg {jQuery} [$container=input.$element] Element to render menu under
8340 */
8341 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
8342 // Parent constructor
8343 OO.ui.TextInputMenuWidget.super.call( this, config );
8344
8345 // Properties
8346 this.input = input;
8347 this.$container = config.$container || this.input.$element;
8348 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
8349
8350 // Initialization
8351 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
8352 };
8353
8354 /* Setup */
8355
8356 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
8357
8358 /* Methods */
8359
8360 /**
8361 * Handle window resize event.
8362 *
8363 * @param {jQuery.Event} e Window resize event
8364 */
8365 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
8366 this.position();
8367 };
8368
8369 /**
8370 * Show the menu.
8371 *
8372 * @chainable
8373 */
8374 OO.ui.TextInputMenuWidget.prototype.show = function () {
8375 // Parent method
8376 OO.ui.TextInputMenuWidget.super.prototype.show.call( this );
8377
8378 this.position();
8379 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8380 return this;
8381 };
8382
8383 /**
8384 * Hide the menu.
8385 *
8386 * @chainable
8387 */
8388 OO.ui.TextInputMenuWidget.prototype.hide = function () {
8389 // Parent method
8390 OO.ui.TextInputMenuWidget.super.prototype.hide.call( this );
8391
8392 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8393 return this;
8394 };
8395
8396 /**
8397 * Position the menu.
8398 *
8399 * @chainable
8400 */
8401 OO.ui.TextInputMenuWidget.prototype.position = function () {
8402 var frameOffset,
8403 $container = this.$container,
8404 dimensions = $container.offset();
8405
8406 // Position under input
8407 dimensions.top += $container.height();
8408
8409 // Compensate for frame position if in a differnt frame
8410 if ( this.input.$.frame && this.input.$.context !== this.$element[0].ownerDocument ) {
8411 frameOffset = OO.ui.Element.getRelativePosition(
8412 this.input.$.frame.$element, this.$element.offsetParent()
8413 );
8414 dimensions.left += frameOffset.left;
8415 dimensions.top += frameOffset.top;
8416 } else {
8417 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
8418 if ( this.$element.css( 'direction' ) === 'rtl' ) {
8419 dimensions.right = this.$element.parent().position().left -
8420 $container.width() - dimensions.left;
8421 // Erase the value for 'left':
8422 delete dimensions.left;
8423 }
8424 }
8425
8426 this.$element.css( dimensions );
8427 this.setIdealSize( $container.width() );
8428 return this;
8429 };
8430 /**
8431 * Width with on and off states.
8432 *
8433 * Mixin for widgets with a boolean state.
8434 *
8435 * @abstract
8436 * @class
8437 *
8438 * @constructor
8439 * @param {Object} [config] Configuration options
8440 * @cfg {boolean} [value=false] Initial value
8441 */
8442 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
8443 // Configuration initialization
8444 config = config || {};
8445
8446 // Properties
8447 this.value = null;
8448
8449 // Initialization
8450 this.$element.addClass( 'oo-ui-toggleWidget' );
8451 this.setValue( !!config.value );
8452 };
8453
8454 /* Events */
8455
8456 /**
8457 * @event change
8458 * @param {boolean} value Changed value
8459 */
8460
8461 /* Methods */
8462
8463 /**
8464 * Get the value of the toggle.
8465 *
8466 * @return {boolean}
8467 */
8468 OO.ui.ToggleWidget.prototype.getValue = function () {
8469 return this.value;
8470 };
8471
8472 /**
8473 * Set the value of the toggle.
8474 *
8475 * @param {boolean} value New value
8476 * @fires change
8477 * @chainable
8478 */
8479 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
8480 value = !!value;
8481 if ( this.value !== value ) {
8482 this.value = value;
8483 this.emit( 'change', value );
8484 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
8485 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
8486 }
8487 return this;
8488 };
8489 /**
8490 * Button that toggles on and off.
8491 *
8492 * @class
8493 * @extends OO.ui.ButtonWidget
8494 * @mixins OO.ui.ToggleWidget
8495 *
8496 * @constructor
8497 * @param {Object} [config] Configuration options
8498 * @cfg {boolean} [value=false] Initial value
8499 */
8500 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
8501 // Configuration initialization
8502 config = config || {};
8503
8504 // Parent constructor
8505 OO.ui.ToggleButtonWidget.super.call( this, config );
8506
8507 // Mixin constructors
8508 OO.ui.ToggleWidget.call( this, config );
8509
8510 // Initialization
8511 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
8512 };
8513
8514 /* Setup */
8515
8516 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
8517 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
8518
8519 /* Methods */
8520
8521 /**
8522 * @inheritdoc
8523 */
8524 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
8525 if ( !this.isDisabled() ) {
8526 this.setValue( !this.value );
8527 }
8528
8529 // Parent method
8530 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
8531 };
8532
8533 /**
8534 * @inheritdoc
8535 */
8536 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
8537 value = !!value;
8538 if ( value !== this.value ) {
8539 this.setActive( value );
8540 }
8541
8542 // Parent method (from mixin)
8543 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
8544
8545 return this;
8546 };
8547 /**
8548 * Switch that slides on and off.
8549 *
8550 * @class
8551 * @extends OO.ui.Widget
8552 * @mixins OO.ui.ToggleWidget
8553 *
8554 * @constructor
8555 * @param {Object} [config] Configuration options
8556 * @cfg {boolean} [value=false] Initial value
8557 */
8558 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
8559 // Parent constructor
8560 OO.ui.ToggleSwitchWidget.super.call( this, config );
8561
8562 // Mixin constructors
8563 OO.ui.ToggleWidget.call( this, config );
8564
8565 // Properties
8566 this.dragging = false;
8567 this.dragStart = null;
8568 this.sliding = false;
8569 this.$glow = this.$( '<span>' );
8570 this.$grip = this.$( '<span>' );
8571
8572 // Events
8573 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
8574
8575 // Initialization
8576 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
8577 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
8578 this.$element
8579 .addClass( 'oo-ui-toggleSwitchWidget' )
8580 .append( this.$glow, this.$grip );
8581 };
8582
8583 /* Setup */
8584
8585 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
8586 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
8587
8588 /* Methods */
8589
8590 /**
8591 * Handle mouse down events.
8592 *
8593 * @param {jQuery.Event} e Mouse down event
8594 */
8595 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
8596 if ( !this.isDisabled() && e.which === 1 ) {
8597 this.setValue( !this.value );
8598 }
8599 };
8600 }( OO ) );