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