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