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