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