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