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