Merge "Remove messageTypes.inc and replace it by a hook"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.1.0-pre (80f1797a5c)
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: Wed May 14 2014 14:11:38 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 // Add directionality class:
4645 this.$element.addClass( 'oo-ui-' + OO.ui.Element.getDir( this.$.context ) );
4646 };
4647
4648 /* Setup */
4649
4650 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
4651 /**
4652 * Page within an booklet layout.
4653 *
4654 * @class
4655 * @extends OO.ui.PanelLayout
4656 *
4657 * @constructor
4658 * @param {string} name Unique symbolic name of page
4659 * @param {Object} [config] Configuration options
4660 * @param {string} [outlineItem] Outline item widget
4661 */
4662 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
4663 // Configuration initialization
4664 config = $.extend( { 'scrollable': true }, config );
4665
4666 // Parent constructor
4667 OO.ui.PageLayout.super.call( this, config );
4668
4669 // Properties
4670 this.name = name;
4671 this.outlineItem = config.outlineItem || null;
4672 this.active = false;
4673
4674 // Initialization
4675 this.$element.addClass( 'oo-ui-pageLayout' );
4676 };
4677
4678 /* Setup */
4679
4680 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
4681
4682 /* Events */
4683
4684 /**
4685 * @event active
4686 * @param {boolean} active Page is active
4687 */
4688
4689 /* Methods */
4690
4691 /**
4692 * Get page name.
4693 *
4694 * @return {string} Symbolic name of page
4695 */
4696 OO.ui.PageLayout.prototype.getName = function () {
4697 return this.name;
4698 };
4699
4700 /**
4701 * Check if page is active.
4702 *
4703 * @return {boolean} Page is active
4704 */
4705 OO.ui.PageLayout.prototype.isActive = function () {
4706 return this.active;
4707 };
4708
4709 /**
4710 * Get outline item.
4711 *
4712 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
4713 */
4714 OO.ui.PageLayout.prototype.getOutlineItem = function () {
4715 return this.outlineItem;
4716 };
4717
4718 /**
4719 * Get outline item.
4720 *
4721 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
4722 * @chainable
4723 */
4724 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
4725 this.outlineItem = outlineItem;
4726 return this;
4727 };
4728
4729 /**
4730 * Set page active state.
4731 *
4732 * @param {boolean} Page is active
4733 * @fires active
4734 */
4735 OO.ui.PageLayout.prototype.setActive = function ( active ) {
4736 active = !!active;
4737
4738 if ( active !== this.active ) {
4739 this.active = active;
4740 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
4741 this.emit( 'active', this.active );
4742 }
4743 };
4744 /**
4745 * Layout containing a series of mutually exclusive pages.
4746 *
4747 * @class
4748 * @extends OO.ui.PanelLayout
4749 * @mixins OO.ui.GroupElement
4750 *
4751 * @constructor
4752 * @param {Object} [config] Configuration options
4753 * @cfg {boolean} [continuous=false] Show all pages, one after another
4754 * @cfg {string} [icon=''] Symbolic icon name
4755 * @cfg {OO.ui.Layout[]} [items] Layouts to add
4756 */
4757 OO.ui.StackLayout = function OoUiStackLayout( config ) {
4758 // Config initialization
4759 config = $.extend( { 'scrollable': true }, config );
4760
4761 // Parent constructor
4762 OO.ui.StackLayout.super.call( this, config );
4763
4764 // Mixin constructors
4765 OO.ui.GroupElement.call( this, this.$element, config );
4766
4767 // Properties
4768 this.currentItem = null;
4769 this.continuous = !!config.continuous;
4770
4771 // Initialization
4772 this.$element.addClass( 'oo-ui-stackLayout' );
4773 if ( this.continuous ) {
4774 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
4775 }
4776 if ( $.isArray( config.items ) ) {
4777 this.addItems( config.items );
4778 }
4779 };
4780
4781 /* Setup */
4782
4783 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
4784 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
4785
4786 /* Events */
4787
4788 /**
4789 * @event set
4790 * @param {OO.ui.Layout|null} [item] Current item
4791 */
4792
4793 /* Methods */
4794
4795 /**
4796 * Get the current item.
4797 *
4798 * @return {OO.ui.Layout|null} [description]
4799 */
4800 OO.ui.StackLayout.prototype.getCurrentItem = function () {
4801 return this.currentItem;
4802 };
4803
4804 /**
4805 * Add items.
4806 *
4807 * Adding an existing item (by value) will move it.
4808 *
4809 * @param {OO.ui.Layout[]} items Items to add
4810 * @param {number} [index] Index to insert items after
4811 * @chainable
4812 */
4813 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
4814 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
4815
4816 if ( !this.currentItem && items.length ) {
4817 this.setItem( items[0] );
4818 }
4819
4820 return this;
4821 };
4822
4823 /**
4824 * Remove items.
4825 *
4826 * Items will be detached, not removed, so they can be used later.
4827 *
4828 * @param {OO.ui.Layout[]} items Items to remove
4829 * @chainable
4830 */
4831 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
4832 OO.ui.GroupElement.prototype.removeItems.call( this, items );
4833 if ( $.inArray( this.currentItem, items ) !== -1 ) {
4834 this.currentItem = null;
4835 if ( !this.currentItem && this.items.length ) {
4836 this.setItem( this.items[0] );
4837 }
4838 }
4839
4840 return this;
4841 };
4842
4843 /**
4844 * Clear all items.
4845 *
4846 * Items will be detached, not removed, so they can be used later.
4847 *
4848 * @chainable
4849 */
4850 OO.ui.StackLayout.prototype.clearItems = function () {
4851 this.currentItem = null;
4852 OO.ui.GroupElement.prototype.clearItems.call( this );
4853
4854 return this;
4855 };
4856
4857 /**
4858 * Show item.
4859 *
4860 * Any currently shown item will be hidden.
4861 *
4862 * @param {OO.ui.Layout} item Item to show
4863 * @chainable
4864 */
4865 OO.ui.StackLayout.prototype.setItem = function ( item ) {
4866 if ( item !== this.currentItem ) {
4867 if ( !this.continuous ) {
4868 this.$items.css( 'display', '' );
4869 }
4870 if ( $.inArray( item, this.items ) !== -1 ) {
4871 if ( !this.continuous ) {
4872 item.$element.css( 'display', 'block' );
4873 }
4874 } else {
4875 item = null;
4876 }
4877 this.currentItem = item;
4878 this.emit( 'set', item );
4879 }
4880
4881 return this;
4882 };
4883 /**
4884 * Horizontal bar layout of tools as icon buttons.
4885 *
4886 * @class
4887 * @extends OO.ui.ToolGroup
4888 *
4889 * @constructor
4890 * @param {OO.ui.Toolbar} toolbar
4891 * @param {Object} [config] Configuration options
4892 */
4893 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
4894 // Parent constructor
4895 OO.ui.BarToolGroup.super.call( this, toolbar, config );
4896
4897 // Initialization
4898 this.$element.addClass( 'oo-ui-barToolGroup' );
4899 };
4900
4901 /* Setup */
4902
4903 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
4904
4905 /* Static Properties */
4906
4907 OO.ui.BarToolGroup.static.titleTooltips = true;
4908
4909 OO.ui.BarToolGroup.static.accelTooltips = true;
4910
4911 OO.ui.BarToolGroup.static.name = 'bar';
4912 /**
4913 * Popup list of tools with an icon and optional label.
4914 *
4915 * @abstract
4916 * @class
4917 * @extends OO.ui.ToolGroup
4918 * @mixins OO.ui.IconedElement
4919 * @mixins OO.ui.IndicatedElement
4920 * @mixins OO.ui.LabeledElement
4921 * @mixins OO.ui.TitledElement
4922 * @mixins OO.ui.ClippableElement
4923 *
4924 * @constructor
4925 * @param {OO.ui.Toolbar} toolbar
4926 * @param {Object} [config] Configuration options
4927 */
4928 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
4929 // Configuration initialization
4930 config = config || {};
4931
4932 // Parent constructor
4933 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
4934
4935 // Mixin constructors
4936 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
4937 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
4938 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
4939 OO.ui.TitledElement.call( this, this.$element, config );
4940 OO.ui.ClippableElement.call( this, this.$group, config );
4941
4942 // Properties
4943 this.active = false;
4944 this.dragging = false;
4945 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
4946 this.$handle = this.$( '<span>' );
4947
4948 // Events
4949 this.$handle.on( {
4950 'mousedown': OO.ui.bind( this.onHandleMouseDown, this ),
4951 'mouseup': OO.ui.bind( this.onHandleMouseUp, this )
4952 } );
4953
4954 // Initialization
4955 this.$handle
4956 .addClass( 'oo-ui-popupToolGroup-handle' )
4957 .append( this.$icon, this.$label, this.$indicator );
4958 this.$element
4959 .addClass( 'oo-ui-popupToolGroup' )
4960 .prepend( this.$handle );
4961 };
4962
4963 /* Setup */
4964
4965 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
4966 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconedElement );
4967 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatedElement );
4968 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabeledElement );
4969 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
4970 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
4971
4972 /* Static Properties */
4973
4974 /* Methods */
4975
4976 /**
4977 * @inheritdoc
4978 */
4979 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
4980 // Parent method
4981 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
4982
4983 if ( this.isDisabled() && this.isElementAttached() ) {
4984 this.setActive( false );
4985 }
4986 };
4987
4988 /**
4989 * Handle focus being lost.
4990 *
4991 * The event is actually generated from a mouseup, so it is not a normal blur event object.
4992 *
4993 * @param {jQuery.Event} e Mouse up event
4994 */
4995 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
4996 // Only deactivate when clicking outside the dropdown element
4997 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
4998 this.setActive( false );
4999 }
5000 };
5001
5002 /**
5003 * @inheritdoc
5004 */
5005 OO.ui.PopupToolGroup.prototype.onMouseUp = function ( e ) {
5006 if ( !this.isDisabled() && e.which === 1 ) {
5007 this.setActive( false );
5008 }
5009 return OO.ui.ToolGroup.prototype.onMouseUp.call( this, e );
5010 };
5011
5012 /**
5013 * Handle mouse up events.
5014 *
5015 * @param {jQuery.Event} e Mouse up event
5016 */
5017 OO.ui.PopupToolGroup.prototype.onHandleMouseUp = function () {
5018 return false;
5019 };
5020
5021 /**
5022 * Handle mouse down events.
5023 *
5024 * @param {jQuery.Event} e Mouse down event
5025 */
5026 OO.ui.PopupToolGroup.prototype.onHandleMouseDown = function ( e ) {
5027 if ( !this.isDisabled() && e.which === 1 ) {
5028 this.setActive( !this.active );
5029 }
5030 return false;
5031 };
5032
5033 /**
5034 * Switch into active mode.
5035 *
5036 * When active, mouseup events anywhere in the document will trigger deactivation.
5037 */
5038 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
5039 value = !!value;
5040 if ( this.active !== value ) {
5041 this.active = value;
5042 if ( value ) {
5043 this.setClipping( true );
5044 this.$element.addClass( 'oo-ui-popupToolGroup-active' );
5045 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
5046 } else {
5047 this.setClipping( false );
5048 this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
5049 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
5050 }
5051 }
5052 };
5053 /**
5054 * Drop down list layout of tools as labeled icon buttons.
5055 *
5056 * @class
5057 * @extends OO.ui.PopupToolGroup
5058 *
5059 * @constructor
5060 * @param {OO.ui.Toolbar} toolbar
5061 * @param {Object} [config] Configuration options
5062 */
5063 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
5064 // Parent constructor
5065 OO.ui.ListToolGroup.super.call( this, toolbar, config );
5066
5067 // Initialization
5068 this.$element.addClass( 'oo-ui-listToolGroup' );
5069 };
5070
5071 /* Setup */
5072
5073 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
5074
5075 /* Static Properties */
5076
5077 OO.ui.ListToolGroup.static.accelTooltips = true;
5078
5079 OO.ui.ListToolGroup.static.name = 'list';
5080 /**
5081 * Drop down menu layout of tools as selectable menu items.
5082 *
5083 * @class
5084 * @extends OO.ui.PopupToolGroup
5085 *
5086 * @constructor
5087 * @param {OO.ui.Toolbar} toolbar
5088 * @param {Object} [config] Configuration options
5089 */
5090 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
5091 // Configuration initialization
5092 config = config || {};
5093
5094 // Parent constructor
5095 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
5096
5097 // Events
5098 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
5099
5100 // Initialization
5101 this.$element.addClass( 'oo-ui-menuToolGroup' );
5102 };
5103
5104 /* Setup */
5105
5106 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
5107
5108 /* Static Properties */
5109
5110 OO.ui.MenuToolGroup.static.accelTooltips = true;
5111
5112 OO.ui.MenuToolGroup.static.name = 'menu';
5113
5114 /* Methods */
5115
5116 /**
5117 * Handle the toolbar state being updated.
5118 *
5119 * When the state changes, the title of each active item in the menu will be joined together and
5120 * used as a label for the group. The label will be empty if none of the items are active.
5121 */
5122 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
5123 var name,
5124 labelTexts = [];
5125
5126 for ( name in this.tools ) {
5127 if ( this.tools[name].isActive() ) {
5128 labelTexts.push( this.tools[name].getTitle() );
5129 }
5130 }
5131
5132 this.setLabel( labelTexts.join( ', ' ) || ' ' );
5133 };
5134 /**
5135 * Tool that shows a popup when selected.
5136 *
5137 * @abstract
5138 * @class
5139 * @extends OO.ui.Tool
5140 * @mixins OO.ui.PopuppableElement
5141 *
5142 * @constructor
5143 * @param {OO.ui.Toolbar} toolbar
5144 * @param {Object} [config] Configuration options
5145 */
5146 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
5147 // Parent constructor
5148 OO.ui.PopupTool.super.call( this, toolbar, config );
5149
5150 // Mixin constructors
5151 OO.ui.PopuppableElement.call( this, config );
5152
5153 // Initialization
5154 this.$element
5155 .addClass( 'oo-ui-popupTool' )
5156 .append( this.popup.$element );
5157 };
5158
5159 /* Setup */
5160
5161 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
5162 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopuppableElement );
5163
5164 /* Methods */
5165
5166 /**
5167 * Handle the tool being selected.
5168 *
5169 * @inheritdoc
5170 */
5171 OO.ui.PopupTool.prototype.onSelect = function () {
5172 if ( !this.isDisabled() ) {
5173 if ( this.popup.isVisible() ) {
5174 this.hidePopup();
5175 } else {
5176 this.showPopup();
5177 }
5178 }
5179 this.setActive( false );
5180 return false;
5181 };
5182
5183 /**
5184 * Handle the toolbar state being updated.
5185 *
5186 * @inheritdoc
5187 */
5188 OO.ui.PopupTool.prototype.onUpdateState = function () {
5189 this.setActive( false );
5190 };
5191 /**
5192 * Group widget.
5193 *
5194 * Mixin for OO.ui.Widget subclasses.
5195 *
5196 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
5197 *
5198 * @abstract
5199 * @class
5200 * @extends OO.ui.GroupElement
5201 *
5202 * @constructor
5203 * @param {jQuery} $group Container node, assigned to #$group
5204 * @param {Object} [config] Configuration options
5205 */
5206 OO.ui.GroupWidget = function OoUiGroupWidget( $element, config ) {
5207 // Parent constructor
5208 OO.ui.GroupWidget.super.call( this, $element, config );
5209 };
5210
5211 /* Setup */
5212
5213 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
5214
5215 /* Methods */
5216
5217 /**
5218 * Set the disabled state of the widget.
5219 *
5220 * This will also update the disabled state of child widgets.
5221 *
5222 * @param {boolean} disabled Disable widget
5223 * @chainable
5224 */
5225 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
5226 var i, len;
5227
5228 // Parent method
5229 // Note this is calling OO.ui.Widget; we're assuming the class this is mixed into
5230 // is a subclass of OO.ui.Widget.
5231 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
5232
5233 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
5234 if ( this.items ) {
5235 for ( i = 0, len = this.items.length; i < len; i++ ) {
5236 this.items[i].updateDisabled();
5237 }
5238 }
5239
5240 return this;
5241 };
5242 /**
5243 * Item widget.
5244 *
5245 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
5246 *
5247 * @abstract
5248 * @class
5249 *
5250 * @constructor
5251 */
5252 OO.ui.ItemWidget = function OoUiItemWidget() {
5253 //
5254 };
5255
5256 /* Methods */
5257
5258 /**
5259 * Check if widget is disabled.
5260 *
5261 * Checks parent if present, making disabled state inheritable.
5262 *
5263 * @return {boolean} Widget is disabled
5264 */
5265 OO.ui.ItemWidget.prototype.isDisabled = function () {
5266 return this.disabled ||
5267 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
5268 };
5269
5270 /**
5271 * Set group element is in.
5272 *
5273 * @param {OO.ui.GroupElement|null} group Group element, null if none
5274 * @chainable
5275 */
5276 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
5277 // Parent method
5278 OO.ui.Element.prototype.setElementGroup.call( this, group );
5279
5280 // Initialize item disabled states
5281 this.updateDisabled();
5282
5283 return this;
5284 };
5285 /**
5286 * Icon widget.
5287 *
5288 * @class
5289 * @extends OO.ui.Widget
5290 * @mixins OO.ui.IconedElement
5291 * @mixins OO.ui.TitledElement
5292 *
5293 * @constructor
5294 * @param {Object} [config] Configuration options
5295 */
5296 OO.ui.IconWidget = function OoUiIconWidget( config ) {
5297 // Config intialization
5298 config = config || {};
5299
5300 // Parent constructor
5301 OO.ui.IconWidget.super.call( this, config );
5302
5303 // Mixin constructors
5304 OO.ui.IconedElement.call( this, this.$element, config );
5305 OO.ui.TitledElement.call( this, this.$element, config );
5306
5307 // Initialization
5308 this.$element.addClass( 'oo-ui-iconWidget' );
5309 };
5310
5311 /* Setup */
5312
5313 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
5314 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconedElement );
5315 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
5316
5317 /* Static Properties */
5318
5319 OO.ui.IconWidget.static.tagName = 'span';
5320 /**
5321 * Indicator widget.
5322 *
5323 * @class
5324 * @extends OO.ui.Widget
5325 * @mixins OO.ui.IndicatedElement
5326 * @mixins OO.ui.TitledElement
5327 *
5328 * @constructor
5329 * @param {Object} [config] Configuration options
5330 */
5331 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
5332 // Config intialization
5333 config = config || {};
5334
5335 // Parent constructor
5336 OO.ui.IndicatorWidget.super.call( this, config );
5337
5338 // Mixin constructors
5339 OO.ui.IndicatedElement.call( this, this.$element, config );
5340 OO.ui.TitledElement.call( this, this.$element, config );
5341
5342 // Initialization
5343 this.$element.addClass( 'oo-ui-indicatorWidget' );
5344 };
5345
5346 /* Setup */
5347
5348 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
5349 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatedElement );
5350 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
5351
5352 /* Static Properties */
5353
5354 OO.ui.IndicatorWidget.static.tagName = 'span';
5355 /**
5356 * Container for multiple related buttons.
5357 *
5358 * Use together with OO.ui.ButtonWidget.
5359 *
5360 * @class
5361 * @extends OO.ui.Widget
5362 * @mixins OO.ui.GroupElement
5363 *
5364 * @constructor
5365 * @param {Object} [config] Configuration options
5366 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
5367 */
5368 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
5369 // Parent constructor
5370 OO.ui.ButtonGroupWidget.super.call( this, config );
5371
5372 // Mixin constructors
5373 OO.ui.GroupElement.call( this, this.$element, config );
5374
5375 // Initialization
5376 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
5377 if ( $.isArray( config.items ) ) {
5378 this.addItems( config.items );
5379 }
5380 };
5381
5382 /* Setup */
5383
5384 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
5385 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
5386 /**
5387 * Button widget.
5388 *
5389 * @class
5390 * @extends OO.ui.Widget
5391 * @mixins OO.ui.ButtonedElement
5392 * @mixins OO.ui.IconedElement
5393 * @mixins OO.ui.IndicatedElement
5394 * @mixins OO.ui.LabeledElement
5395 * @mixins OO.ui.TitledElement
5396 * @mixins OO.ui.FlaggableElement
5397 *
5398 * @constructor
5399 * @param {Object} [config] Configuration options
5400 * @cfg {string} [title=''] Title text
5401 * @cfg {string} [href] Hyperlink to visit when clicked
5402 * @cfg {string} [target] Target to open hyperlink in
5403 */
5404 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
5405 // Configuration initialization
5406 config = $.extend( { 'target': '_blank' }, config );
5407
5408 // Parent constructor
5409 OO.ui.ButtonWidget.super.call( this, config );
5410
5411 // Mixin constructors
5412 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
5413 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
5414 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
5415 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
5416 OO.ui.TitledElement.call( this, this.$button, config );
5417 OO.ui.FlaggableElement.call( this, config );
5418
5419 // Properties
5420 this.isHyperlink = typeof config.href === 'string';
5421
5422 // Events
5423 this.$button.on( {
5424 'click': OO.ui.bind( this.onClick, this ),
5425 'keypress': OO.ui.bind( this.onKeyPress, this )
5426 } );
5427
5428 // Initialization
5429 this.$button
5430 .append( this.$icon, this.$label, this.$indicator )
5431 .attr( { 'href': config.href, 'target': config.target } );
5432 this.$element
5433 .addClass( 'oo-ui-buttonWidget' )
5434 .append( this.$button );
5435 };
5436
5437 /* Setup */
5438
5439 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
5440 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonedElement );
5441 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconedElement );
5442 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatedElement );
5443 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabeledElement );
5444 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
5445 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggableElement );
5446
5447 /* Events */
5448
5449 /**
5450 * @event click
5451 */
5452
5453 /* Methods */
5454
5455 /**
5456 * Handles mouse click events.
5457 *
5458 * @param {jQuery.Event} e Mouse click event
5459 * @fires click
5460 */
5461 OO.ui.ButtonWidget.prototype.onClick = function () {
5462 if ( !this.isDisabled() ) {
5463 this.emit( 'click' );
5464 if ( this.isHyperlink ) {
5465 return true;
5466 }
5467 }
5468 return false;
5469 };
5470
5471 /**
5472 * Handles keypress events.
5473 *
5474 * @param {jQuery.Event} e Keypress event
5475 * @fires click
5476 */
5477 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
5478 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
5479 this.onClick();
5480 if ( this.isHyperlink ) {
5481 return true;
5482 }
5483 }
5484 return false;
5485 };
5486 /**
5487 * Input widget.
5488 *
5489 * @abstract
5490 * @class
5491 * @extends OO.ui.Widget
5492 *
5493 * @constructor
5494 * @param {Object} [config] Configuration options
5495 * @cfg {string} [name=''] HTML input name
5496 * @cfg {string} [value=''] Input value
5497 * @cfg {boolean} [readOnly=false] Prevent changes
5498 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
5499 */
5500 OO.ui.InputWidget = function OoUiInputWidget( config ) {
5501 // Config intialization
5502 config = $.extend( { 'readOnly': false }, config );
5503
5504 // Parent constructor
5505 OO.ui.InputWidget.super.call( this, config );
5506
5507 // Properties
5508 this.$input = this.getInputElement( config );
5509 this.value = '';
5510 this.readOnly = false;
5511 this.inputFilter = config.inputFilter;
5512
5513 // Events
5514 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
5515
5516 // Initialization
5517 this.$input
5518 .attr( 'name', config.name )
5519 .prop( 'disabled', this.isDisabled() );
5520 this.setReadOnly( config.readOnly );
5521 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
5522 this.setValue( config.value );
5523 };
5524
5525 /* Setup */
5526
5527 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
5528
5529 /* Events */
5530
5531 /**
5532 * @event change
5533 * @param value
5534 */
5535
5536 /* Methods */
5537
5538 /**
5539 * Get input element.
5540 *
5541 * @param {Object} [config] Configuration options
5542 * @return {jQuery} Input element
5543 */
5544 OO.ui.InputWidget.prototype.getInputElement = function () {
5545 return this.$( '<input>' );
5546 };
5547
5548 /**
5549 * Handle potentially value-changing events.
5550 *
5551 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
5552 */
5553 OO.ui.InputWidget.prototype.onEdit = function () {
5554 if ( !this.isDisabled() ) {
5555 // Allow the stack to clear so the value will be updated
5556 setTimeout( OO.ui.bind( function () {
5557 this.setValue( this.$input.val() );
5558 }, this ) );
5559 }
5560 };
5561
5562 /**
5563 * Get the value of the input.
5564 *
5565 * @return {string} Input value
5566 */
5567 OO.ui.InputWidget.prototype.getValue = function () {
5568 return this.value;
5569 };
5570
5571 /**
5572 * Sets the direction of the current input, either RTL or LTR
5573 *
5574 * @param {boolean} isRTL
5575 */
5576 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
5577 if ( isRTL ) {
5578 this.$input.removeClass( 'oo-ui-ltr' );
5579 this.$input.addClass( 'oo-ui-rtl' );
5580 } else {
5581 this.$input.removeClass( 'oo-ui-rtl' );
5582 this.$input.addClass( 'oo-ui-ltr' );
5583 }
5584 };
5585
5586 /**
5587 * Set the value of the input.
5588 *
5589 * @param {string} value New value
5590 * @fires change
5591 * @chainable
5592 */
5593 OO.ui.InputWidget.prototype.setValue = function ( value ) {
5594 value = this.sanitizeValue( value );
5595 if ( this.value !== value ) {
5596 this.value = value;
5597 this.emit( 'change', this.value );
5598 }
5599 // Update the DOM if it has changed. Note that with sanitizeValue, it
5600 // is possible for the DOM value to change without this.value changing.
5601 if ( this.$input.val() !== this.value ) {
5602 this.$input.val( this.value );
5603 }
5604 return this;
5605 };
5606
5607 /**
5608 * Sanitize incoming value.
5609 *
5610 * Ensures value is a string, and converts undefined and null to empty strings.
5611 *
5612 * @param {string} value Original value
5613 * @return {string} Sanitized value
5614 */
5615 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
5616 if ( value === undefined || value === null ) {
5617 return '';
5618 } else if ( this.inputFilter ) {
5619 return this.inputFilter( String( value ) );
5620 } else {
5621 return String( value );
5622 }
5623 };
5624
5625 /**
5626 * Simulate the behavior of clicking on a label bound to this input.
5627 */
5628 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
5629 if ( !this.isDisabled() ) {
5630 if ( this.$input.is( ':checkbox,:radio' ) ) {
5631 this.$input.click();
5632 } else if ( this.$input.is( ':input' ) ) {
5633 this.$input.focus();
5634 }
5635 }
5636 };
5637
5638 /**
5639 * Check if the widget is read-only.
5640 *
5641 * @return {boolean}
5642 */
5643 OO.ui.InputWidget.prototype.isReadOnly = function () {
5644 return this.readOnly;
5645 };
5646
5647 /**
5648 * Set the read-only state of the widget.
5649 *
5650 * This should probably change the widgets's appearance and prevent it from being used.
5651 *
5652 * @param {boolean} state Make input read-only
5653 * @chainable
5654 */
5655 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
5656 this.readOnly = !!state;
5657 this.$input.prop( 'readOnly', this.readOnly );
5658 return this;
5659 };
5660
5661 /**
5662 * @inheritdoc
5663 */
5664 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
5665 OO.ui.Widget.prototype.setDisabled.call( this, state );
5666 if ( this.$input ) {
5667 this.$input.prop( 'disabled', this.isDisabled() );
5668 }
5669 return this;
5670 };
5671
5672 /**
5673 * Focus the input.
5674 *
5675 * @chainable
5676 */
5677 OO.ui.InputWidget.prototype.focus = function () {
5678 this.$input.focus();
5679 return this;
5680 };
5681 /**
5682 * Checkbox widget.
5683 *
5684 * @class
5685 * @extends OO.ui.InputWidget
5686 *
5687 * @constructor
5688 * @param {Object} [config] Configuration options
5689 */
5690 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
5691 // Parent constructor
5692 OO.ui.CheckboxInputWidget.super.call( this, config );
5693
5694 // Initialization
5695 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
5696 };
5697
5698 /* Setup */
5699
5700 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
5701
5702 /* Events */
5703
5704 /* Methods */
5705
5706 /**
5707 * Get input element.
5708 *
5709 * @return {jQuery} Input element
5710 */
5711 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
5712 return this.$( '<input type="checkbox" />' );
5713 };
5714
5715 /**
5716 * Get checked state of the checkbox
5717 *
5718 * @return {boolean} If the checkbox is checked
5719 */
5720 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
5721 return this.value;
5722 };
5723
5724 /**
5725 * Set value
5726 */
5727 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
5728 value = !!value;
5729 if ( this.value !== value ) {
5730 this.value = value;
5731 this.$input.prop( 'checked', this.value );
5732 this.emit( 'change', this.value );
5733 }
5734 };
5735
5736 /**
5737 * @inheritdoc
5738 */
5739 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
5740 if ( !this.isDisabled() ) {
5741 // Allow the stack to clear so the value will be updated
5742 setTimeout( OO.ui.bind( function () {
5743 this.setValue( this.$input.prop( 'checked' ) );
5744 }, this ) );
5745 }
5746 };
5747 /**
5748 * Label widget.
5749 *
5750 * @class
5751 * @extends OO.ui.Widget
5752 * @mixins OO.ui.LabeledElement
5753 *
5754 * @constructor
5755 * @param {Object} [config] Configuration options
5756 */
5757 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
5758 // Config intialization
5759 config = config || {};
5760
5761 // Parent constructor
5762 OO.ui.LabelWidget.super.call( this, config );
5763
5764 // Mixin constructors
5765 OO.ui.LabeledElement.call( this, this.$element, config );
5766
5767 // Properties
5768 this.input = config.input;
5769
5770 // Events
5771 if ( this.input instanceof OO.ui.InputWidget ) {
5772 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
5773 }
5774
5775 // Initialization
5776 this.$element.addClass( 'oo-ui-labelWidget' );
5777 };
5778
5779 /* Setup */
5780
5781 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
5782 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabeledElement );
5783
5784 /* Static Properties */
5785
5786 OO.ui.LabelWidget.static.tagName = 'label';
5787
5788 /* Methods */
5789
5790 /**
5791 * Handles label mouse click events.
5792 *
5793 * @param {jQuery.Event} e Mouse click event
5794 */
5795 OO.ui.LabelWidget.prototype.onClick = function () {
5796 this.input.simulateLabelClick();
5797 return false;
5798 };
5799 /**
5800 * Lookup input widget.
5801 *
5802 * Mixin that adds a menu showing suggested values to a text input. Subclasses must handle `select`
5803 * and `choose` events on #lookupMenu to make use of selections.
5804 *
5805 * @class
5806 * @abstract
5807 *
5808 * @constructor
5809 * @param {OO.ui.TextInputWidget} input Input widget
5810 * @param {Object} [config] Configuration options
5811 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
5812 */
5813 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
5814 // Config intialization
5815 config = config || {};
5816
5817 // Properties
5818 this.lookupInput = input;
5819 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
5820 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
5821 '$': OO.ui.Element.getJQuery( this.$overlay ),
5822 'input': this.lookupInput,
5823 '$container': config.$container
5824 } );
5825 this.lookupCache = {};
5826 this.lookupQuery = null;
5827 this.lookupRequest = null;
5828 this.populating = false;
5829
5830 // Events
5831 this.$overlay.append( this.lookupMenu.$element );
5832
5833 this.lookupInput.$input.on( {
5834 'focus': OO.ui.bind( this.onLookupInputFocus, this ),
5835 'blur': OO.ui.bind( this.onLookupInputBlur, this ),
5836 'mousedown': OO.ui.bind( this.onLookupInputMouseDown, this )
5837 } );
5838 this.lookupInput.connect( this, { 'change': 'onLookupInputChange' } );
5839
5840 // Initialization
5841 this.$element.addClass( 'oo-ui-lookupWidget' );
5842 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
5843 };
5844
5845 /* Methods */
5846
5847 /**
5848 * Handle input focus event.
5849 *
5850 * @param {jQuery.Event} e Input focus event
5851 */
5852 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
5853 this.openLookupMenu();
5854 };
5855
5856 /**
5857 * Handle input blur event.
5858 *
5859 * @param {jQuery.Event} e Input blur event
5860 */
5861 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
5862 this.lookupMenu.hide();
5863 };
5864
5865 /**
5866 * Handle input mouse down event.
5867 *
5868 * @param {jQuery.Event} e Input mouse down event
5869 */
5870 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
5871 this.openLookupMenu();
5872 };
5873
5874 /**
5875 * Handle input change event.
5876 *
5877 * @param {string} value New input value
5878 */
5879 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
5880 this.openLookupMenu();
5881 };
5882
5883 /**
5884 * Get lookup menu.
5885 *
5886 * @return {OO.ui.TextInputMenuWidget}
5887 */
5888 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
5889 return this.lookupMenu;
5890 };
5891
5892 /**
5893 * Open the menu.
5894 *
5895 * @chainable
5896 */
5897 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
5898 var value = this.lookupInput.getValue();
5899
5900 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
5901 this.populateLookupMenu();
5902 if ( !this.lookupMenu.isVisible() ) {
5903 this.lookupMenu.show();
5904 }
5905 } else {
5906 this.lookupMenu.clearItems();
5907 this.lookupMenu.hide();
5908 }
5909
5910 return this;
5911 };
5912
5913 /**
5914 * Populate lookup menu with current information.
5915 *
5916 * @chainable
5917 */
5918 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
5919 if ( !this.populating ) {
5920 this.populating = true;
5921 this.getLookupMenuItems()
5922 .done( OO.ui.bind( function ( items ) {
5923 this.lookupMenu.clearItems();
5924 if ( items.length ) {
5925 this.lookupMenu.show();
5926 this.lookupMenu.addItems( items );
5927 this.initializeLookupMenuSelection();
5928 this.openLookupMenu();
5929 } else {
5930 this.lookupMenu.hide();
5931 }
5932 this.populating = false;
5933 }, this ) )
5934 .fail( OO.ui.bind( function () {
5935 this.lookupMenu.clearItems();
5936 this.populating = false;
5937 }, this ) );
5938 }
5939
5940 return this;
5941 };
5942
5943 /**
5944 * Set selection in the lookup menu with current information.
5945 *
5946 * @chainable
5947 */
5948 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
5949 if ( !this.lookupMenu.getSelectedItem() ) {
5950 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5951 }
5952 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5953 };
5954
5955 /**
5956 * Get lookup menu items for the current query.
5957 *
5958 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
5959 * of the done event
5960 */
5961 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
5962 var value = this.lookupInput.getValue(),
5963 deferred = $.Deferred();
5964
5965 if ( value && value !== this.lookupQuery ) {
5966 // Abort current request if query has changed
5967 if ( this.lookupRequest ) {
5968 this.lookupRequest.abort();
5969 this.lookupQuery = null;
5970 this.lookupRequest = null;
5971 }
5972 if ( value in this.lookupCache ) {
5973 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
5974 } else {
5975 this.lookupQuery = value;
5976 this.lookupRequest = this.getLookupRequest()
5977 .always( OO.ui.bind( function () {
5978 this.lookupQuery = null;
5979 this.lookupRequest = null;
5980 }, this ) )
5981 .done( OO.ui.bind( function ( data ) {
5982 this.lookupCache[value] = this.getLookupCacheItemFromData( data );
5983 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
5984 }, this ) )
5985 .fail( function () {
5986 deferred.reject();
5987 } );
5988 this.pushPending();
5989 this.lookupRequest.always( OO.ui.bind( function () {
5990 this.popPending();
5991 }, this ) );
5992 }
5993 }
5994 return deferred.promise();
5995 };
5996
5997 /**
5998 * Get a new request object of the current lookup query value.
5999 *
6000 * @abstract
6001 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
6002 */
6003 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
6004 // Stub, implemented in subclass
6005 return null;
6006 };
6007
6008 /**
6009 * Handle successful lookup request.
6010 *
6011 * Overriding methods should call #populateLookupMenu when results are available and cache results
6012 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
6013 *
6014 * @abstract
6015 * @param {Mixed} data Response from server
6016 */
6017 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
6018 // Stub, implemented in subclass
6019 };
6020
6021 /**
6022 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
6023 *
6024 * @abstract
6025 * @param {Mixed} data Cached result data, usually an array
6026 * @return {OO.ui.MenuItemWidget[]} Menu items
6027 */
6028 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
6029 // Stub, implemented in subclass
6030 return [];
6031 };
6032 /**
6033 * Option widget.
6034 *
6035 * Use with OO.ui.SelectWidget.
6036 *
6037 * @class
6038 * @extends OO.ui.Widget
6039 * @mixins OO.ui.IconedElement
6040 * @mixins OO.ui.LabeledElement
6041 * @mixins OO.ui.IndicatedElement
6042 * @mixins OO.ui.FlaggableElement
6043 *
6044 * @constructor
6045 * @param {Mixed} data Option data
6046 * @param {Object} [config] Configuration options
6047 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
6048 */
6049 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
6050 // Config intialization
6051 config = config || {};
6052
6053 // Parent constructor
6054 OO.ui.OptionWidget.super.call( this, config );
6055
6056 // Mixin constructors
6057 OO.ui.ItemWidget.call( this );
6058 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
6059 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
6060 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
6061 OO.ui.FlaggableElement.call( this, config );
6062
6063 // Properties
6064 this.data = data;
6065 this.selected = false;
6066 this.highlighted = false;
6067 this.pressed = false;
6068
6069 // Initialization
6070 this.$element
6071 .data( 'oo-ui-optionWidget', this )
6072 .attr( 'rel', config.rel )
6073 .addClass( 'oo-ui-optionWidget' )
6074 .append( this.$label );
6075 this.$element
6076 .prepend( this.$icon )
6077 .append( this.$indicator );
6078 };
6079
6080 /* Setup */
6081
6082 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
6083 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
6084 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconedElement );
6085 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabeledElement );
6086 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatedElement );
6087 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggableElement );
6088
6089 /* Static Properties */
6090
6091 OO.ui.OptionWidget.static.tagName = 'li';
6092
6093 OO.ui.OptionWidget.static.selectable = true;
6094
6095 OO.ui.OptionWidget.static.highlightable = true;
6096
6097 OO.ui.OptionWidget.static.pressable = true;
6098
6099 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
6100
6101 /* Methods */
6102
6103 /**
6104 * Check if option can be selected.
6105 *
6106 * @return {boolean} Item is selectable
6107 */
6108 OO.ui.OptionWidget.prototype.isSelectable = function () {
6109 return this.constructor.static.selectable && !this.isDisabled();
6110 };
6111
6112 /**
6113 * Check if option can be highlighted.
6114 *
6115 * @return {boolean} Item is highlightable
6116 */
6117 OO.ui.OptionWidget.prototype.isHighlightable = function () {
6118 return this.constructor.static.highlightable && !this.isDisabled();
6119 };
6120
6121 /**
6122 * Check if option can be pressed.
6123 *
6124 * @return {boolean} Item is pressable
6125 */
6126 OO.ui.OptionWidget.prototype.isPressable = function () {
6127 return this.constructor.static.pressable && !this.isDisabled();
6128 };
6129
6130 /**
6131 * Check if option is selected.
6132 *
6133 * @return {boolean} Item is selected
6134 */
6135 OO.ui.OptionWidget.prototype.isSelected = function () {
6136 return this.selected;
6137 };
6138
6139 /**
6140 * Check if option is highlighted.
6141 *
6142 * @return {boolean} Item is highlighted
6143 */
6144 OO.ui.OptionWidget.prototype.isHighlighted = function () {
6145 return this.highlighted;
6146 };
6147
6148 /**
6149 * Check if option is pressed.
6150 *
6151 * @return {boolean} Item is pressed
6152 */
6153 OO.ui.OptionWidget.prototype.isPressed = function () {
6154 return this.pressed;
6155 };
6156
6157 /**
6158 * Set selected state.
6159 *
6160 * @param {boolean} [state=false] Select option
6161 * @chainable
6162 */
6163 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
6164 if ( !this.isDisabled() && this.constructor.static.selectable ) {
6165 this.selected = !!state;
6166 if ( this.selected ) {
6167 this.$element.addClass( 'oo-ui-optionWidget-selected' );
6168 if ( this.constructor.static.scrollIntoViewOnSelect ) {
6169 this.scrollElementIntoView();
6170 }
6171 } else {
6172 this.$element.removeClass( 'oo-ui-optionWidget-selected' );
6173 }
6174 }
6175 return this;
6176 };
6177
6178 /**
6179 * Set highlighted state.
6180 *
6181 * @param {boolean} [state=false] Highlight option
6182 * @chainable
6183 */
6184 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
6185 if ( !this.isDisabled() && this.constructor.static.highlightable ) {
6186 this.highlighted = !!state;
6187 if ( this.highlighted ) {
6188 this.$element.addClass( 'oo-ui-optionWidget-highlighted' );
6189 } else {
6190 this.$element.removeClass( 'oo-ui-optionWidget-highlighted' );
6191 }
6192 }
6193 return this;
6194 };
6195
6196 /**
6197 * Set pressed state.
6198 *
6199 * @param {boolean} [state=false] Press option
6200 * @chainable
6201 */
6202 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
6203 if ( !this.isDisabled() && this.constructor.static.pressable ) {
6204 this.pressed = !!state;
6205 if ( this.pressed ) {
6206 this.$element.addClass( 'oo-ui-optionWidget-pressed' );
6207 } else {
6208 this.$element.removeClass( 'oo-ui-optionWidget-pressed' );
6209 }
6210 }
6211 return this;
6212 };
6213
6214 /**
6215 * Make the option's highlight flash.
6216 *
6217 * While flashing, the visual style of the pressed state is removed if present.
6218 *
6219 * @return {jQuery.Promise} Promise resolved when flashing is done
6220 */
6221 OO.ui.OptionWidget.prototype.flash = function () {
6222 var $this = this.$element,
6223 deferred = $.Deferred();
6224
6225 if ( !this.isDisabled() && this.constructor.static.pressable ) {
6226 $this.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
6227 setTimeout( OO.ui.bind( function () {
6228 // Restore original classes
6229 $this
6230 .toggleClass( 'oo-ui-optionWidget-highlighted', this.highlighted )
6231 .toggleClass( 'oo-ui-optionWidget-pressed', this.pressed );
6232 setTimeout( function () {
6233 deferred.resolve();
6234 }, 100 );
6235 }, this ), 100 );
6236 }
6237
6238 return deferred.promise();
6239 };
6240
6241 /**
6242 * Get option data.
6243 *
6244 * @return {Mixed} Option data
6245 */
6246 OO.ui.OptionWidget.prototype.getData = function () {
6247 return this.data;
6248 };
6249 /**
6250 * Selection of options.
6251 *
6252 * Use together with OO.ui.OptionWidget.
6253 *
6254 * @class
6255 * @extends OO.ui.Widget
6256 * @mixins OO.ui.GroupElement
6257 *
6258 * @constructor
6259 * @param {Object} [config] Configuration options
6260 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
6261 */
6262 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
6263 // Config intialization
6264 config = config || {};
6265
6266 // Parent constructor
6267 OO.ui.SelectWidget.super.call( this, config );
6268
6269 // Mixin constructors
6270 OO.ui.GroupWidget.call( this, this.$element, config );
6271
6272 // Properties
6273 this.pressed = false;
6274 this.selecting = null;
6275 this.hashes = {};
6276
6277 // Events
6278 this.$element.on( {
6279 'mousedown': OO.ui.bind( this.onMouseDown, this ),
6280 'mouseup': OO.ui.bind( this.onMouseUp, this ),
6281 'mousemove': OO.ui.bind( this.onMouseMove, this ),
6282 'mouseover': OO.ui.bind( this.onMouseOver, this ),
6283 'mouseleave': OO.ui.bind( this.onMouseLeave, this )
6284 } );
6285
6286 // Initialization
6287 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
6288 if ( $.isArray( config.items ) ) {
6289 this.addItems( config.items );
6290 }
6291 };
6292
6293 /* Setup */
6294
6295 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
6296
6297 // Need to mixin base class as well
6298 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
6299 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
6300
6301 /* Events */
6302
6303 /**
6304 * @event highlight
6305 * @param {OO.ui.OptionWidget|null} item Highlighted item
6306 */
6307
6308 /**
6309 * @event press
6310 * @param {OO.ui.OptionWidget|null} item Pressed item
6311 */
6312
6313 /**
6314 * @event select
6315 * @param {OO.ui.OptionWidget|null} item Selected item
6316 */
6317
6318 /**
6319 * @event choose
6320 * @param {OO.ui.OptionWidget|null} item Chosen item
6321 */
6322
6323 /**
6324 * @event add
6325 * @param {OO.ui.OptionWidget[]} items Added items
6326 * @param {number} index Index items were added at
6327 */
6328
6329 /**
6330 * @event remove
6331 * @param {OO.ui.OptionWidget[]} items Removed items
6332 */
6333
6334 /* Static Properties */
6335
6336 OO.ui.SelectWidget.static.tagName = 'ul';
6337
6338 /* Methods */
6339
6340 /**
6341 * Handle mouse down events.
6342 *
6343 * @private
6344 * @param {jQuery.Event} e Mouse down event
6345 */
6346 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
6347 var item;
6348
6349 if ( !this.isDisabled() && e.which === 1 ) {
6350 this.togglePressed( true );
6351 item = this.getTargetItem( e );
6352 if ( item && item.isSelectable() ) {
6353 this.pressItem( item );
6354 this.selecting = item;
6355 this.$( this.$.context ).one( 'mouseup', OO.ui.bind( this.onMouseUp, this ) );
6356 }
6357 }
6358 return false;
6359 };
6360
6361 /**
6362 * Handle mouse up events.
6363 *
6364 * @private
6365 * @param {jQuery.Event} e Mouse up event
6366 */
6367 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
6368 var item;
6369
6370 this.togglePressed( false );
6371 if ( !this.selecting ) {
6372 item = this.getTargetItem( e );
6373 if ( item && item.isSelectable() ) {
6374 this.selecting = item;
6375 }
6376 }
6377 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
6378 this.pressItem( null );
6379 this.chooseItem( this.selecting );
6380 this.selecting = null;
6381 }
6382
6383 return false;
6384 };
6385
6386 /**
6387 * Handle mouse move events.
6388 *
6389 * @private
6390 * @param {jQuery.Event} e Mouse move event
6391 */
6392 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
6393 var item;
6394
6395 if ( !this.isDisabled() && this.pressed ) {
6396 item = this.getTargetItem( e );
6397 if ( item && item !== this.selecting && item.isSelectable() ) {
6398 this.pressItem( item );
6399 this.selecting = item;
6400 }
6401 }
6402 return false;
6403 };
6404
6405 /**
6406 * Handle mouse over events.
6407 *
6408 * @private
6409 * @param {jQuery.Event} e Mouse over event
6410 */
6411 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
6412 var item;
6413
6414 if ( !this.isDisabled() ) {
6415 item = this.getTargetItem( e );
6416 this.highlightItem( item && item.isHighlightable() ? item : null );
6417 }
6418 return false;
6419 };
6420
6421 /**
6422 * Handle mouse leave events.
6423 *
6424 * @private
6425 * @param {jQuery.Event} e Mouse over event
6426 */
6427 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
6428 if ( !this.isDisabled() ) {
6429 this.highlightItem( null );
6430 }
6431 return false;
6432 };
6433
6434 /**
6435 * Get the closest item to a jQuery.Event.
6436 *
6437 * @private
6438 * @param {jQuery.Event} e
6439 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6440 */
6441 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
6442 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
6443 if ( $item.length ) {
6444 return $item.data( 'oo-ui-optionWidget' );
6445 }
6446 return null;
6447 };
6448
6449 /**
6450 * Get selected item.
6451 *
6452 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6453 */
6454 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
6455 var i, len;
6456
6457 for ( i = 0, len = this.items.length; i < len; i++ ) {
6458 if ( this.items[i].isSelected() ) {
6459 return this.items[i];
6460 }
6461 }
6462 return null;
6463 };
6464
6465 /**
6466 * Get highlighted item.
6467 *
6468 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6469 */
6470 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
6471 var i, len;
6472
6473 for ( i = 0, len = this.items.length; i < len; i++ ) {
6474 if ( this.items[i].isHighlighted() ) {
6475 return this.items[i];
6476 }
6477 }
6478 return null;
6479 };
6480
6481 /**
6482 * Get an existing item with equivilant data.
6483 *
6484 * @param {Object} data Item data to search for
6485 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
6486 */
6487 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
6488 var hash = OO.getHash( data );
6489
6490 if ( hash in this.hashes ) {
6491 return this.hashes[hash];
6492 }
6493
6494 return null;
6495 };
6496
6497 /**
6498 * Toggle pressed state.
6499 *
6500 * @param {boolean} pressed An option is being pressed
6501 */
6502 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
6503 if ( pressed === undefined ) {
6504 pressed = !this.pressed;
6505 }
6506 if ( pressed !== this.pressed ) {
6507 this.$element.toggleClass( 'oo-ui-selectWidget-pressed', pressed );
6508 this.$element.toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
6509 this.pressed = pressed;
6510 }
6511 };
6512
6513 /**
6514 * Highlight an item.
6515 *
6516 * Highlighting is mutually exclusive.
6517 *
6518 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
6519 * @fires highlight
6520 * @chainable
6521 */
6522 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
6523 var i, len, highlighted,
6524 changed = false;
6525
6526 for ( i = 0, len = this.items.length; i < len; i++ ) {
6527 highlighted = this.items[i] === item;
6528 if ( this.items[i].isHighlighted() !== highlighted ) {
6529 this.items[i].setHighlighted( highlighted );
6530 changed = true;
6531 }
6532 }
6533 if ( changed ) {
6534 this.emit( 'highlight', item );
6535 }
6536
6537 return this;
6538 };
6539
6540 /**
6541 * Select an item.
6542 *
6543 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6544 * @fires select
6545 * @chainable
6546 */
6547 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
6548 var i, len, selected,
6549 changed = false;
6550
6551 for ( i = 0, len = this.items.length; i < len; i++ ) {
6552 selected = this.items[i] === item;
6553 if ( this.items[i].isSelected() !== selected ) {
6554 this.items[i].setSelected( selected );
6555 changed = true;
6556 }
6557 }
6558 if ( changed ) {
6559 this.emit( 'select', item );
6560 }
6561
6562 return this;
6563 };
6564
6565 /**
6566 * Press an item.
6567 *
6568 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6569 * @fires press
6570 * @chainable
6571 */
6572 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
6573 var i, len, pressed,
6574 changed = false;
6575
6576 for ( i = 0, len = this.items.length; i < len; i++ ) {
6577 pressed = this.items[i] === item;
6578 if ( this.items[i].isPressed() !== pressed ) {
6579 this.items[i].setPressed( pressed );
6580 changed = true;
6581 }
6582 }
6583 if ( changed ) {
6584 this.emit( 'press', item );
6585 }
6586
6587 return this;
6588 };
6589
6590 /**
6591 * Choose an item.
6592 *
6593 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
6594 * an item is selected using the keyboard or mouse.
6595 *
6596 * @param {OO.ui.OptionWidget} item Item to choose
6597 * @fires choose
6598 * @chainable
6599 */
6600 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
6601 this.selectItem( item );
6602 this.emit( 'choose', item );
6603
6604 return this;
6605 };
6606
6607 /**
6608 * Get an item relative to another one.
6609 *
6610 * @param {OO.ui.OptionWidget} item Item to start at
6611 * @param {number} direction Direction to move in
6612 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
6613 */
6614 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
6615 var inc = direction > 0 ? 1 : -1,
6616 len = this.items.length,
6617 index = item instanceof OO.ui.OptionWidget ?
6618 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
6619 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
6620 i = inc > 0 ?
6621 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
6622 Math.max( index, -1 ) :
6623 // Default to n-1 instead of -1, if nothing is selected let's start at the end
6624 Math.min( index, len );
6625
6626 while ( true ) {
6627 i = ( i + inc + len ) % len;
6628 item = this.items[i];
6629 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6630 return item;
6631 }
6632 // Stop iterating when we've looped all the way around
6633 if ( i === stopAt ) {
6634 break;
6635 }
6636 }
6637 return null;
6638 };
6639
6640 /**
6641 * Get the next selectable item.
6642 *
6643 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
6644 */
6645 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
6646 var i, len, item;
6647
6648 for ( i = 0, len = this.items.length; i < len; i++ ) {
6649 item = this.items[i];
6650 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
6651 return item;
6652 }
6653 }
6654
6655 return null;
6656 };
6657
6658 /**
6659 * Add items.
6660 *
6661 * When items are added with the same values as existing items, the existing items will be
6662 * automatically removed before the new items are added.
6663 *
6664 * @param {OO.ui.OptionWidget[]} items Items to add
6665 * @param {number} [index] Index to insert items after
6666 * @fires add
6667 * @chainable
6668 */
6669 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
6670 var i, len, item, hash,
6671 remove = [];
6672
6673 for ( i = 0, len = items.length; i < len; i++ ) {
6674 item = items[i];
6675 hash = OO.getHash( item.getData() );
6676 if ( hash in this.hashes ) {
6677 // Remove item with same value
6678 remove.push( this.hashes[hash] );
6679 }
6680 this.hashes[hash] = item;
6681 }
6682 if ( remove.length ) {
6683 this.removeItems( remove );
6684 }
6685
6686 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
6687
6688 // Always provide an index, even if it was omitted
6689 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
6690
6691 return this;
6692 };
6693
6694 /**
6695 * Remove items.
6696 *
6697 * Items will be detached, not removed, so they can be used later.
6698 *
6699 * @param {OO.ui.OptionWidget[]} items Items to remove
6700 * @fires remove
6701 * @chainable
6702 */
6703 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
6704 var i, len, item, hash;
6705
6706 for ( i = 0, len = items.length; i < len; i++ ) {
6707 item = items[i];
6708 hash = OO.getHash( item.getData() );
6709 if ( hash in this.hashes ) {
6710 // Remove existing item
6711 delete this.hashes[hash];
6712 }
6713 if ( item.isSelected() ) {
6714 this.selectItem( null );
6715 }
6716 }
6717 OO.ui.GroupElement.prototype.removeItems.call( this, items );
6718
6719 this.emit( 'remove', items );
6720
6721 return this;
6722 };
6723
6724 /**
6725 * Clear all items.
6726 *
6727 * Items will be detached, not removed, so they can be used later.
6728 *
6729 * @fires remove
6730 * @chainable
6731 */
6732 OO.ui.SelectWidget.prototype.clearItems = function () {
6733 var items = this.items.slice();
6734
6735 // Clear all items
6736 this.hashes = {};
6737 OO.ui.GroupElement.prototype.clearItems.call( this );
6738 this.selectItem( null );
6739
6740 this.emit( 'remove', items );
6741
6742 return this;
6743 };
6744 /**
6745 * Menu item widget.
6746 *
6747 * Use with OO.ui.MenuWidget.
6748 *
6749 * @class
6750 * @extends OO.ui.OptionWidget
6751 *
6752 * @constructor
6753 * @param {Mixed} data Item data
6754 * @param {Object} [config] Configuration options
6755 */
6756 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
6757 // Configuration initialization
6758 config = $.extend( { 'icon': 'check' }, config );
6759
6760 // Parent constructor
6761 OO.ui.MenuItemWidget.super.call( this, data, config );
6762
6763 // Initialization
6764 this.$element.addClass( 'oo-ui-menuItemWidget' );
6765 };
6766
6767 /* Setup */
6768
6769 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.OptionWidget );
6770 /**
6771 * Menu widget.
6772 *
6773 * Use together with OO.ui.MenuItemWidget.
6774 *
6775 * @class
6776 * @extends OO.ui.SelectWidget
6777 * @mixins OO.ui.ClippableElement
6778 *
6779 * @constructor
6780 * @param {Object} [config] Configuration options
6781 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
6782 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
6783 */
6784 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
6785 // Config intialization
6786 config = config || {};
6787
6788 // Parent constructor
6789 OO.ui.MenuWidget.super.call( this, config );
6790
6791 // Mixin constructors
6792 OO.ui.ClippableElement.call( this, this.$group, config );
6793
6794 // Properties
6795 this.autoHide = config.autoHide === undefined || !!config.autoHide;
6796 this.newItems = null;
6797 this.$input = config.input ? config.input.$input : null;
6798 this.$previousFocus = null;
6799 this.isolated = !config.input;
6800 this.visible = false;
6801 this.flashing = false;
6802 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
6803 this.onDocumentMouseDownHandler = OO.ui.bind( this.onDocumentMouseDown, this );
6804
6805 // Initialization
6806 this.$element.hide().addClass( 'oo-ui-menuWidget' );
6807 };
6808
6809 /* Setup */
6810
6811 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
6812 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
6813
6814 /* Methods */
6815
6816 /**
6817 * Handles document mouse down events.
6818 *
6819 * @param {jQuery.Event} e Key down event
6820 */
6821 OO.ui.MenuWidget.prototype.onDocumentMouseDown = function ( e ) {
6822 if ( !$.contains( this.$element[0], e.target ) ) {
6823 this.hide();
6824 }
6825 };
6826
6827 /**
6828 * Handles key down events.
6829 *
6830 * @param {jQuery.Event} e Key down event
6831 */
6832 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
6833 var nextItem,
6834 handled = false,
6835 highlightItem = this.getHighlightedItem();
6836
6837 if ( !this.isDisabled() && this.visible ) {
6838 if ( !highlightItem ) {
6839 highlightItem = this.getSelectedItem();
6840 }
6841 switch ( e.keyCode ) {
6842 case OO.ui.Keys.ENTER:
6843 this.chooseItem( highlightItem );
6844 handled = true;
6845 break;
6846 case OO.ui.Keys.UP:
6847 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
6848 handled = true;
6849 break;
6850 case OO.ui.Keys.DOWN:
6851 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
6852 handled = true;
6853 break;
6854 case OO.ui.Keys.ESCAPE:
6855 if ( highlightItem ) {
6856 highlightItem.setHighlighted( false );
6857 }
6858 this.hide();
6859 handled = true;
6860 break;
6861 }
6862
6863 if ( nextItem ) {
6864 this.highlightItem( nextItem );
6865 nextItem.scrollElementIntoView();
6866 }
6867
6868 if ( handled ) {
6869 e.preventDefault();
6870 e.stopPropagation();
6871 return false;
6872 }
6873 }
6874 };
6875
6876 /**
6877 * Check if the menu is visible.
6878 *
6879 * @return {boolean} Menu is visible
6880 */
6881 OO.ui.MenuWidget.prototype.isVisible = function () {
6882 return this.visible;
6883 };
6884
6885 /**
6886 * Bind key down listener.
6887 */
6888 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
6889 if ( this.$input ) {
6890 this.$input.on( 'keydown', this.onKeyDownHandler );
6891 } else {
6892 // Capture menu navigation keys
6893 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
6894 }
6895 };
6896
6897 /**
6898 * Unbind key down listener.
6899 */
6900 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
6901 if ( this.$input ) {
6902 this.$input.off( 'keydown' );
6903 } else {
6904 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
6905 }
6906 };
6907
6908 /**
6909 * Choose an item.
6910 *
6911 * This will close the menu when done, unlike selectItem which only changes selection.
6912 *
6913 * @param {OO.ui.OptionWidget} item Item to choose
6914 * @chainable
6915 */
6916 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
6917 // Parent method
6918 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
6919
6920 if ( item && !this.flashing ) {
6921 this.flashing = true;
6922 item.flash().done( OO.ui.bind( function () {
6923 this.hide();
6924 this.flashing = false;
6925 }, this ) );
6926 } else {
6927 this.hide();
6928 }
6929
6930 return this;
6931 };
6932
6933 /**
6934 * Add items.
6935 *
6936 * Adding an existing item (by value) will move it.
6937 *
6938 * @param {OO.ui.MenuItemWidget[]} items Items to add
6939 * @param {number} [index] Index to insert items after
6940 * @chainable
6941 */
6942 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
6943 var i, len, item;
6944
6945 // Parent method
6946 OO.ui.SelectWidget.prototype.addItems.call( this, items, index );
6947
6948 // Auto-initialize
6949 if ( !this.newItems ) {
6950 this.newItems = [];
6951 }
6952
6953 for ( i = 0, len = items.length; i < len; i++ ) {
6954 item = items[i];
6955 if ( this.visible ) {
6956 // Defer fitting label until
6957 item.fitLabel();
6958 } else {
6959 this.newItems.push( item );
6960 }
6961 }
6962
6963 return this;
6964 };
6965
6966 /**
6967 * Show the menu.
6968 *
6969 * @chainable
6970 */
6971 OO.ui.MenuWidget.prototype.show = function () {
6972 var i, len;
6973
6974 if ( this.items.length ) {
6975 this.$element.show();
6976 this.visible = true;
6977 this.bindKeyDownListener();
6978
6979 // Change focus to enable keyboard navigation
6980 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
6981 this.$previousFocus = this.$( ':focus' );
6982 this.$input.focus();
6983 }
6984 if ( this.newItems && this.newItems.length ) {
6985 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
6986 this.newItems[i].fitLabel();
6987 }
6988 this.newItems = null;
6989 }
6990
6991 this.setClipping( true );
6992
6993 // Auto-hide
6994 if ( this.autoHide ) {
6995 this.getElementDocument().addEventListener(
6996 'mousedown', this.onDocumentMouseDownHandler, true
6997 );
6998 }
6999 }
7000
7001 return this;
7002 };
7003
7004 /**
7005 * Hide the menu.
7006 *
7007 * @chainable
7008 */
7009 OO.ui.MenuWidget.prototype.hide = function () {
7010 this.$element.hide();
7011 this.visible = false;
7012 this.unbindKeyDownListener();
7013
7014 if ( this.isolated && this.$previousFocus ) {
7015 this.$previousFocus.focus();
7016 this.$previousFocus = null;
7017 }
7018
7019 this.getElementDocument().removeEventListener(
7020 'mousedown', this.onDocumentMouseDownHandler, true
7021 );
7022
7023 this.setClipping( false );
7024
7025 return this;
7026 };
7027 /**
7028 * Inline menu of options.
7029 *
7030 * Use with OO.ui.MenuOptionWidget.
7031 *
7032 * @class
7033 * @extends OO.ui.Widget
7034 * @mixins OO.ui.IconedElement
7035 * @mixins OO.ui.IndicatedElement
7036 * @mixins OO.ui.LabeledElement
7037 * @mixins OO.ui.TitledElement
7038 *
7039 * @constructor
7040 * @param {Object} [config] Configuration options
7041 * @cfg {Object} [menu] Configuration options to pass to menu widget
7042 */
7043 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
7044 // Configuration initialization
7045 config = $.extend( { 'indicator': 'down' }, config );
7046
7047 // Parent constructor
7048 OO.ui.InlineMenuWidget.super.call( this, config );
7049
7050 // Mixin constructors
7051 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
7052 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
7053 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
7054 OO.ui.TitledElement.call( this, this.$label, config );
7055
7056 // Properties
7057 this.menu = new OO.ui.MenuWidget( $.extend( { '$': this.$ }, config.menu ) );
7058 this.$handle = this.$( '<span>' );
7059
7060 // Events
7061 this.$element.on( { 'click': OO.ui.bind( this.onClick, this ) } );
7062 this.menu.connect( this, { 'select': 'onMenuSelect' } );
7063
7064 // Initialization
7065 this.$handle
7066 .addClass( 'oo-ui-inlineMenuWidget-handle' )
7067 .append( this.$icon, this.$label, this.$indicator );
7068 this.$element
7069 .addClass( 'oo-ui-inlineMenuWidget' )
7070 .append( this.$handle, this.menu.$element );
7071 };
7072
7073 /* Setup */
7074
7075 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
7076 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconedElement );
7077 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatedElement );
7078 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabeledElement );
7079 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
7080
7081 /* Methods */
7082
7083 /**
7084 * Get the menu.
7085 *
7086 * @return {OO.ui.MenuWidget} Menu of widget
7087 */
7088 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
7089 return this.menu;
7090 };
7091
7092 /**
7093 * Handles menu select events.
7094 *
7095 * @param {OO.ui.MenuItemWidget} item Selected menu item
7096 */
7097 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
7098 var selectedLabel;
7099
7100 if ( !item ) {
7101 return;
7102 }
7103
7104 selectedLabel = item.getLabel();
7105
7106 // If the label is a DOM element, clone it, because setLabel will append() it
7107 if ( selectedLabel instanceof jQuery ) {
7108 selectedLabel = selectedLabel.clone();
7109 }
7110
7111 this.setLabel( selectedLabel );
7112 };
7113
7114 /**
7115 * Handles mouse click events.
7116 *
7117 * @param {jQuery.Event} e Mouse click event
7118 */
7119 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
7120 // Skip clicks within the menu
7121 if ( $.contains( this.menu.$element[0], e.target ) ) {
7122 return;
7123 }
7124
7125 if ( !this.isDisabled() ) {
7126 if ( this.menu.isVisible() ) {
7127 this.menu.hide();
7128 } else {
7129 this.menu.show();
7130 }
7131 }
7132 return false;
7133 };
7134 /**
7135 * Menu section item widget.
7136 *
7137 * Use with OO.ui.MenuWidget.
7138 *
7139 * @class
7140 * @extends OO.ui.OptionWidget
7141 *
7142 * @constructor
7143 * @param {Mixed} data Item data
7144 * @param {Object} [config] Configuration options
7145 */
7146 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
7147 // Parent constructor
7148 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
7149
7150 // Initialization
7151 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
7152 };
7153
7154 /* Setup */
7155
7156 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.OptionWidget );
7157
7158 /* Static Properties */
7159
7160 OO.ui.MenuSectionItemWidget.static.selectable = false;
7161
7162 OO.ui.MenuSectionItemWidget.static.highlightable = false;
7163 /**
7164 * Create an OO.ui.OutlineWidget object.
7165 *
7166 * Use with OO.ui.OutlineItemWidget.
7167 *
7168 * @class
7169 * @extends OO.ui.SelectWidget
7170 *
7171 * @constructor
7172 * @param {Object} [config] Configuration options
7173 */
7174 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
7175 // Config intialization
7176 config = config || {};
7177
7178 // Parent constructor
7179 OO.ui.OutlineWidget.super.call( this, config );
7180
7181 // Initialization
7182 this.$element.addClass( 'oo-ui-outlineWidget' );
7183 };
7184
7185 /* Setup */
7186
7187 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
7188 /**
7189 * Creates an OO.ui.OutlineControlsWidget object.
7190 *
7191 * Use together with OO.ui.OutlineWidget.js
7192 *
7193 * @class
7194 *
7195 * @constructor
7196 * @param {OO.ui.OutlineWidget} outline Outline to control
7197 * @param {Object} [config] Configuration options
7198 */
7199 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7200 // Configuration initialization
7201 config = $.extend( { 'icon': 'add-item' }, config );
7202
7203 // Parent constructor
7204 OO.ui.OutlineControlsWidget.super.call( this, config );
7205
7206 // Mixin constructors
7207 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
7208 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
7209
7210 // Properties
7211 this.outline = outline;
7212 this.$movers = this.$( '<div>' );
7213 this.upButton = new OO.ui.ButtonWidget( {
7214 '$': this.$,
7215 'frameless': true,
7216 'icon': 'collapse',
7217 'title': OO.ui.msg( 'ooui-outline-control-move-up' )
7218 } );
7219 this.downButton = new OO.ui.ButtonWidget( {
7220 '$': this.$,
7221 'frameless': true,
7222 'icon': 'expand',
7223 'title': OO.ui.msg( 'ooui-outline-control-move-down' )
7224 } );
7225 this.removeButton = new OO.ui.ButtonWidget( {
7226 '$': this.$,
7227 'frameless': true,
7228 'icon': 'remove',
7229 'title': OO.ui.msg( 'ooui-outline-control-remove' )
7230 } );
7231
7232 // Events
7233 outline.connect( this, {
7234 'select': 'onOutlineChange',
7235 'add': 'onOutlineChange',
7236 'remove': 'onOutlineChange'
7237 } );
7238 this.upButton.connect( this, { 'click': ['emit', 'move', -1] } );
7239 this.downButton.connect( this, { 'click': ['emit', 'move', 1] } );
7240 this.removeButton.connect( this, { 'click': ['emit', 'remove'] } );
7241
7242 // Initialization
7243 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7244 this.$group.addClass( 'oo-ui-outlineControlsWidget-adders' );
7245 this.$movers
7246 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7247 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7248 this.$element.append( this.$icon, this.$group, this.$movers );
7249 };
7250
7251 /* Setup */
7252
7253 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7254 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7255 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconedElement );
7256
7257 /* Events */
7258
7259 /**
7260 * @event move
7261 * @param {number} places Number of places to move
7262 */
7263
7264 /**
7265 * @event remove
7266 */
7267
7268 /* Methods */
7269
7270 /**
7271 * Handle outline change events.
7272 */
7273 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7274 var i, len, firstMovable, lastMovable,
7275 items = this.outline.getItems(),
7276 selectedItem = this.outline.getSelectedItem(),
7277 movable = selectedItem && selectedItem.isMovable(),
7278 removable = selectedItem && selectedItem.isRemovable();
7279
7280 if ( movable ) {
7281 i = -1;
7282 len = items.length;
7283 while ( ++i < len ) {
7284 if ( items[i].isMovable() ) {
7285 firstMovable = items[i];
7286 break;
7287 }
7288 }
7289 i = len;
7290 while ( i-- ) {
7291 if ( items[i].isMovable() ) {
7292 lastMovable = items[i];
7293 break;
7294 }
7295 }
7296 }
7297 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7298 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7299 this.removeButton.setDisabled( !removable );
7300 };
7301 /**
7302 * Creates an OO.ui.OutlineItemWidget object.
7303 *
7304 * Use with OO.ui.OutlineWidget.
7305 *
7306 * @class
7307 * @extends OO.ui.OptionWidget
7308 *
7309 * @constructor
7310 * @param {Mixed} data Item data
7311 * @param {Object} [config] Configuration options
7312 * @cfg {number} [level] Indentation level
7313 * @cfg {boolean} [movable] Allow modification from outline controls
7314 */
7315 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
7316 // Config intialization
7317 config = config || {};
7318
7319 // Parent constructor
7320 OO.ui.OutlineItemWidget.super.call( this, data, config );
7321
7322 // Properties
7323 this.level = 0;
7324 this.movable = !!config.movable;
7325 this.removable = !!config.removable;
7326
7327 // Initialization
7328 this.$element.addClass( 'oo-ui-outlineItemWidget' );
7329 this.setLevel( config.level );
7330 };
7331
7332 /* Setup */
7333
7334 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.OptionWidget );
7335
7336 /* Static Properties */
7337
7338 OO.ui.OutlineItemWidget.static.highlightable = false;
7339
7340 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
7341
7342 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
7343
7344 OO.ui.OutlineItemWidget.static.levels = 3;
7345
7346 /* Methods */
7347
7348 /**
7349 * Check if item is movable.
7350 *
7351 * Movablilty is used by outline controls.
7352 *
7353 * @return {boolean} Item is movable
7354 */
7355 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
7356 return this.movable;
7357 };
7358
7359 /**
7360 * Check if item is removable.
7361 *
7362 * Removablilty is used by outline controls.
7363 *
7364 * @return {boolean} Item is removable
7365 */
7366 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
7367 return this.removable;
7368 };
7369
7370 /**
7371 * Get indentation level.
7372 *
7373 * @return {number} Indentation level
7374 */
7375 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
7376 return this.level;
7377 };
7378
7379 /**
7380 * Set movability.
7381 *
7382 * Movablilty is used by outline controls.
7383 *
7384 * @param {boolean} movable Item is movable
7385 * @chainable
7386 */
7387 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
7388 this.movable = !!movable;
7389 return this;
7390 };
7391
7392 /**
7393 * Set removability.
7394 *
7395 * Removablilty is used by outline controls.
7396 *
7397 * @param {boolean} movable Item is removable
7398 * @chainable
7399 */
7400 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
7401 this.removable = !!removable;
7402 return this;
7403 };
7404
7405 /**
7406 * Set indentation level.
7407 *
7408 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
7409 * @chainable
7410 */
7411 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
7412 var levels = this.constructor.static.levels,
7413 levelClass = this.constructor.static.levelClass,
7414 i = levels;
7415
7416 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
7417 while ( i-- ) {
7418 if ( this.level === i ) {
7419 this.$element.addClass( levelClass + i );
7420 } else {
7421 this.$element.removeClass( levelClass + i );
7422 }
7423 }
7424
7425 return this;
7426 };
7427 /**
7428 * Option widget that looks like a button.
7429 *
7430 * Use together with OO.ui.ButtonSelectWidget.
7431 *
7432 * @class
7433 * @extends OO.ui.OptionWidget
7434 * @mixins OO.ui.ButtonedElement
7435 * @mixins OO.ui.FlaggableElement
7436 *
7437 * @constructor
7438 * @param {Mixed} data Option data
7439 * @param {Object} [config] Configuration options
7440 */
7441 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
7442 // Parent constructor
7443 OO.ui.ButtonOptionWidget.super.call( this, data, config );
7444
7445 // Mixin constructors
7446 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
7447 OO.ui.FlaggableElement.call( this, config );
7448
7449 // Initialization
7450 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
7451 this.$button.append( this.$element.contents() );
7452 this.$element.append( this.$button );
7453 };
7454
7455 /* Setup */
7456
7457 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget );
7458 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonedElement );
7459 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.FlaggableElement );
7460
7461 /* Methods */
7462
7463 /**
7464 * @inheritdoc
7465 */
7466 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
7467 OO.ui.OptionWidget.prototype.setSelected.call( this, state );
7468
7469 this.setActive( state );
7470
7471 return this;
7472 };
7473 /**
7474 * Select widget containing button options.
7475 *
7476 * Use together with OO.ui.ButtonOptionWidget.
7477 *
7478 * @class
7479 * @extends OO.ui.SelectWidget
7480 *
7481 * @constructor
7482 * @param {Object} [config] Configuration options
7483 */
7484 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
7485 // Parent constructor
7486 OO.ui.ButtonSelectWidget.super.call( this, config );
7487
7488 // Initialization
7489 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
7490 };
7491
7492 /* Setup */
7493
7494 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
7495 /**
7496 * Container for content that is overlaid and positioned absolutely.
7497 *
7498 * @class
7499 * @extends OO.ui.Widget
7500 * @mixins OO.ui.LabeledElement
7501 *
7502 * @constructor
7503 * @param {Object} [config] Configuration options
7504 * @cfg {boolean} [tail=true] Show tail pointing to origin of popup
7505 * @cfg {string} [align='center'] Alignment of popup to origin
7506 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
7507 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
7508 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
7509 * @cfg {boolean} [head] Show label and close button at the top
7510 */
7511 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
7512 // Config intialization
7513 config = config || {};
7514
7515 // Parent constructor
7516 OO.ui.PopupWidget.super.call( this, config );
7517
7518 // Mixin constructors
7519 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
7520 OO.ui.ClippableElement.call( this, this.$( '<div>' ), config );
7521
7522 // Properties
7523 this.visible = false;
7524 this.$popup = this.$( '<div>' );
7525 this.$head = this.$( '<div>' );
7526 this.$body = this.$clippable;
7527 this.$tail = this.$( '<div>' );
7528 this.$container = config.$container || this.$( 'body' );
7529 this.autoClose = !!config.autoClose;
7530 this.$autoCloseIgnore = config.$autoCloseIgnore;
7531 this.transitionTimeout = null;
7532 this.tail = false;
7533 this.align = config.align || 'center';
7534 this.closeButton = new OO.ui.ButtonWidget( { '$': this.$, 'frameless': true, 'icon': 'close' } );
7535 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
7536
7537 // Events
7538 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
7539
7540 // Initialization
7541 this.useTail( config.tail !== undefined ? !!config.tail : true );
7542 this.$body.addClass( 'oo-ui-popupWidget-body' );
7543 this.$tail.addClass( 'oo-ui-popupWidget-tail' );
7544 this.$head
7545 .addClass( 'oo-ui-popupWidget-head' )
7546 .append( this.$label, this.closeButton.$element );
7547 if ( !config.head ) {
7548 this.$head.hide();
7549 }
7550 this.$popup
7551 .addClass( 'oo-ui-popupWidget-popup' )
7552 .append( this.$head, this.$body );
7553 this.$element.hide()
7554 .addClass( 'oo-ui-popupWidget' )
7555 .append( this.$popup, this.$tail );
7556 };
7557
7558 /* Setup */
7559
7560 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
7561 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabeledElement );
7562 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
7563
7564 /* Events */
7565
7566 /**
7567 * @event hide
7568 */
7569
7570 /**
7571 * @event show
7572 */
7573
7574 /* Methods */
7575
7576 /**
7577 * Handles mouse down events.
7578 *
7579 * @param {jQuery.Event} e Mouse down event
7580 */
7581 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
7582 if (
7583 this.visible &&
7584 !$.contains( this.$element[0], e.target ) &&
7585 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
7586 ) {
7587 this.hide();
7588 }
7589 };
7590
7591 /**
7592 * Bind mouse down listener.
7593 */
7594 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
7595 // Capture clicks outside popup
7596 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
7597 };
7598
7599 /**
7600 * Handles close button click events.
7601 */
7602 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
7603 if ( this.visible ) {
7604 this.hide();
7605 }
7606 };
7607
7608 /**
7609 * Unbind mouse down listener.
7610 */
7611 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
7612 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
7613 };
7614
7615 /**
7616 * Check if the popup is visible.
7617 *
7618 * @return {boolean} Popup is visible
7619 */
7620 OO.ui.PopupWidget.prototype.isVisible = function () {
7621 return this.visible;
7622 };
7623
7624 /**
7625 * Set whether to show a tail.
7626 *
7627 * @return {boolean} Make tail visible
7628 */
7629 OO.ui.PopupWidget.prototype.useTail = function ( value ) {
7630 value = !!value;
7631 if ( this.tail !== value ) {
7632 this.tail = value;
7633 if ( value ) {
7634 this.$element.addClass( 'oo-ui-popupWidget-tailed' );
7635 } else {
7636 this.$element.removeClass( 'oo-ui-popupWidget-tailed' );
7637 }
7638 }
7639 };
7640
7641 /**
7642 * Check if showing a tail.
7643 *
7644 * @return {boolean} tail is visible
7645 */
7646 OO.ui.PopupWidget.prototype.hasTail = function () {
7647 return this.tail;
7648 };
7649
7650 /**
7651 * Show the context.
7652 *
7653 * @fires show
7654 * @chainable
7655 */
7656 OO.ui.PopupWidget.prototype.show = function () {
7657 if ( !this.visible ) {
7658 this.setClipping( true );
7659 this.$element.show();
7660 this.visible = true;
7661 this.emit( 'show' );
7662 if ( this.autoClose ) {
7663 this.bindMouseDownListener();
7664 }
7665 }
7666 return this;
7667 };
7668
7669 /**
7670 * Hide the context.
7671 *
7672 * @fires hide
7673 * @chainable
7674 */
7675 OO.ui.PopupWidget.prototype.hide = function () {
7676 if ( this.visible ) {
7677 this.setClipping( false );
7678 this.$element.hide();
7679 this.visible = false;
7680 this.emit( 'hide' );
7681 if ( this.autoClose ) {
7682 this.unbindMouseDownListener();
7683 }
7684 }
7685 return this;
7686 };
7687
7688 /**
7689 * Updates the position and size.
7690 *
7691 * @param {number} width Width
7692 * @param {number} height Height
7693 * @param {boolean} [transition=false] Use a smooth transition
7694 * @chainable
7695 */
7696 OO.ui.PopupWidget.prototype.display = function ( width, height, transition ) {
7697 var padding = 10,
7698 originOffset = Math.round( this.$element.offset().left ),
7699 containerLeft = Math.round( this.$container.offset().left ),
7700 containerWidth = this.$container.innerWidth(),
7701 containerRight = containerLeft + containerWidth,
7702 popupOffset = width * ( { 'left': 0, 'center': -0.5, 'right': -1 } )[this.align],
7703 popupLeft = popupOffset - padding,
7704 popupRight = popupOffset + padding + width + padding,
7705 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
7706 overlapRight = containerRight - ( originOffset + popupRight );
7707
7708 // Prevent transition from being interrupted
7709 clearTimeout( this.transitionTimeout );
7710 if ( transition ) {
7711 // Enable transition
7712 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
7713 }
7714
7715 if ( overlapRight < 0 ) {
7716 popupOffset += overlapRight;
7717 } else if ( overlapLeft < 0 ) {
7718 popupOffset -= overlapLeft;
7719 }
7720
7721 // Position body relative to anchor and resize
7722 this.$popup.css( {
7723 'left': popupOffset,
7724 'width': width,
7725 'height': height === undefined ? 'auto' : height
7726 } );
7727
7728 if ( transition ) {
7729 // Prevent transitioning after transition is complete
7730 this.transitionTimeout = setTimeout( OO.ui.bind( function () {
7731 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7732 }, this ), 200 );
7733 } else {
7734 // Prevent transitioning immediately
7735 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
7736 }
7737
7738 return this;
7739 };
7740 /**
7741 * Button that shows and hides a popup.
7742 *
7743 * @class
7744 * @extends OO.ui.ButtonWidget
7745 * @mixins OO.ui.PopuppableElement
7746 *
7747 * @constructor
7748 * @param {Object} [config] Configuration options
7749 */
7750 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
7751 // Parent constructor
7752 OO.ui.PopupButtonWidget.super.call( this, config );
7753
7754 // Mixin constructors
7755 OO.ui.PopuppableElement.call( this, config );
7756
7757 // Initialization
7758 this.$element
7759 .addClass( 'oo-ui-popupButtonWidget' )
7760 .append( this.popup.$element );
7761 };
7762
7763 /* Setup */
7764
7765 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
7766 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopuppableElement );
7767
7768 /* Methods */
7769
7770 /**
7771 * Handles mouse click events.
7772 *
7773 * @param {jQuery.Event} e Mouse click event
7774 */
7775 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
7776 // Skip clicks within the popup
7777 if ( $.contains( this.popup.$element[0], e.target ) ) {
7778 return;
7779 }
7780
7781 if ( !this.isDisabled() ) {
7782 if ( this.popup.isVisible() ) {
7783 this.hidePopup();
7784 } else {
7785 this.showPopup();
7786 }
7787 OO.ui.ButtonWidget.prototype.onClick.call( this );
7788 }
7789 return false;
7790 };
7791 /**
7792 * Search widget.
7793 *
7794 * Combines query and results selection widgets.
7795 *
7796 * @class
7797 * @extends OO.ui.Widget
7798 *
7799 * @constructor
7800 * @param {Object} [config] Configuration options
7801 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
7802 * @cfg {string} [value] Initial query value
7803 */
7804 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
7805 // Configuration intialization
7806 config = config || {};
7807
7808 // Parent constructor
7809 OO.ui.SearchWidget.super.call( this, config );
7810
7811 // Properties
7812 this.query = new OO.ui.TextInputWidget( {
7813 '$': this.$,
7814 'icon': 'search',
7815 'placeholder': config.placeholder,
7816 'value': config.value
7817 } );
7818 this.results = new OO.ui.SelectWidget( { '$': this.$ } );
7819 this.$query = this.$( '<div>' );
7820 this.$results = this.$( '<div>' );
7821
7822 // Events
7823 this.query.connect( this, {
7824 'change': 'onQueryChange',
7825 'enter': 'onQueryEnter'
7826 } );
7827 this.results.connect( this, {
7828 'highlight': 'onResultsHighlight',
7829 'select': 'onResultsSelect'
7830 } );
7831 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
7832
7833 // Initialization
7834 this.$query
7835 .addClass( 'oo-ui-searchWidget-query' )
7836 .append( this.query.$element );
7837 this.$results
7838 .addClass( 'oo-ui-searchWidget-results' )
7839 .append( this.results.$element );
7840 this.$element
7841 .addClass( 'oo-ui-searchWidget' )
7842 .append( this.$results, this.$query );
7843 };
7844
7845 /* Setup */
7846
7847 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
7848
7849 /* Events */
7850
7851 /**
7852 * @event highlight
7853 * @param {Object|null} item Item data or null if no item is highlighted
7854 */
7855
7856 /**
7857 * @event select
7858 * @param {Object|null} item Item data or null if no item is selected
7859 */
7860
7861 /* Methods */
7862
7863 /**
7864 * Handle query key down events.
7865 *
7866 * @param {jQuery.Event} e Key down event
7867 */
7868 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
7869 var highlightedItem, nextItem,
7870 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
7871
7872 if ( dir ) {
7873 highlightedItem = this.results.getHighlightedItem();
7874 if ( !highlightedItem ) {
7875 highlightedItem = this.results.getSelectedItem();
7876 }
7877 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
7878 this.results.highlightItem( nextItem );
7879 nextItem.scrollElementIntoView();
7880 }
7881 };
7882
7883 /**
7884 * Handle select widget select events.
7885 *
7886 * Clears existing results. Subclasses should repopulate items according to new query.
7887 *
7888 * @param {string} value New value
7889 */
7890 OO.ui.SearchWidget.prototype.onQueryChange = function () {
7891 // Reset
7892 this.results.clearItems();
7893 };
7894
7895 /**
7896 * Handle select widget enter key events.
7897 *
7898 * Selects highlighted item.
7899 *
7900 * @param {string} value New value
7901 */
7902 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
7903 // Reset
7904 this.results.selectItem( this.results.getHighlightedItem() );
7905 };
7906
7907 /**
7908 * Handle select widget highlight events.
7909 *
7910 * @param {OO.ui.OptionWidget} item Highlighted item
7911 * @fires highlight
7912 */
7913 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
7914 this.emit( 'highlight', item ? item.getData() : null );
7915 };
7916
7917 /**
7918 * Handle select widget select events.
7919 *
7920 * @param {OO.ui.OptionWidget} item Selected item
7921 * @fires select
7922 */
7923 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
7924 this.emit( 'select', item ? item.getData() : null );
7925 };
7926
7927 /**
7928 * Get the query input.
7929 *
7930 * @return {OO.ui.TextInputWidget} Query input
7931 */
7932 OO.ui.SearchWidget.prototype.getQuery = function () {
7933 return this.query;
7934 };
7935
7936 /**
7937 * Get the results list.
7938 *
7939 * @return {OO.ui.SelectWidget} Select list
7940 */
7941 OO.ui.SearchWidget.prototype.getResults = function () {
7942 return this.results;
7943 };
7944 /**
7945 * Text input widget.
7946 *
7947 * @class
7948 * @extends OO.ui.InputWidget
7949 *
7950 * @constructor
7951 * @param {Object} [config] Configuration options
7952 * @cfg {string} [placeholder] Placeholder text
7953 * @cfg {string} [icon] Symbolic name of icon
7954 * @cfg {boolean} [multiline=false] Allow multiple lines of text
7955 * @cfg {boolean} [autosize=false] Automatically resize to fit content
7956 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
7957 */
7958 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
7959 config = $.extend( { 'maxRows': 10 }, config );
7960
7961 // Parent constructor
7962 OO.ui.TextInputWidget.super.call( this, config );
7963
7964 // Properties
7965 this.pending = 0;
7966 this.multiline = !!config.multiline;
7967 this.autosize = !!config.autosize;
7968 this.maxRows = config.maxRows;
7969
7970 // Events
7971 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
7972 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
7973
7974 // Initialization
7975 this.$element.addClass( 'oo-ui-textInputWidget' );
7976 if ( config.icon ) {
7977 this.$element.addClass( 'oo-ui-textInputWidget-decorated' );
7978 this.$element.append(
7979 this.$( '<span>' )
7980 .addClass( 'oo-ui-textInputWidget-icon oo-ui-icon-' + config.icon )
7981 .mousedown( OO.ui.bind( function () {
7982 this.$input.focus();
7983 return false;
7984 }, this ) )
7985 );
7986 }
7987 if ( config.placeholder ) {
7988 this.$input.attr( 'placeholder', config.placeholder );
7989 }
7990 };
7991
7992 /* Setup */
7993
7994 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
7995
7996 /* Events */
7997
7998 /**
7999 * User presses enter inside the text box.
8000 *
8001 * Not called if input is multiline.
8002 *
8003 * @event enter
8004 */
8005
8006 /* Methods */
8007
8008 /**
8009 * Handle key press events.
8010 *
8011 * @param {jQuery.Event} e Key press event
8012 * @fires enter If enter key is pressed and input is not multiline
8013 */
8014 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8015 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8016 this.emit( 'enter' );
8017 }
8018 };
8019
8020 /**
8021 * Handle element attach events.
8022 *
8023 * @param {jQuery.Event} e Element attach event
8024 */
8025 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8026 this.adjustSize();
8027 };
8028
8029 /**
8030 * @inheritdoc
8031 */
8032 OO.ui.TextInputWidget.prototype.onEdit = function () {
8033 this.adjustSize();
8034
8035 // Parent method
8036 return OO.ui.InputWidget.prototype.onEdit.call( this );
8037 };
8038
8039 /**
8040 * Automatically adjust the size of the text input.
8041 *
8042 * This only affects multi-line inputs that are auto-sized.
8043 *
8044 * @chainable
8045 */
8046 OO.ui.TextInputWidget.prototype.adjustSize = function () {
8047 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
8048
8049 if ( this.multiline && this.autosize ) {
8050 $clone = this.$input.clone()
8051 .val( this.$input.val() )
8052 .css( { 'height': 0 } )
8053 .insertAfter( this.$input );
8054 // Set inline height property to 0 to measure scroll height
8055 scrollHeight = $clone[0].scrollHeight;
8056 // Remove inline height property to measure natural heights
8057 $clone.css( 'height', '' );
8058 innerHeight = $clone.innerHeight();
8059 outerHeight = $clone.outerHeight();
8060 // Measure max rows height
8061 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
8062 maxInnerHeight = $clone.innerHeight();
8063 $clone.removeAttr( 'rows' ).css( 'height', '' );
8064 $clone.remove();
8065 idealHeight = Math.min( maxInnerHeight, scrollHeight );
8066 // Only apply inline height when expansion beyond natural height is needed
8067 this.$input.css(
8068 'height',
8069 // Use the difference between the inner and outer height as a buffer
8070 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
8071 );
8072 }
8073 return this;
8074 };
8075
8076 /**
8077 * Get input element.
8078 *
8079 * @param {Object} [config] Configuration options
8080 * @return {jQuery} Input element
8081 */
8082 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
8083 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
8084 };
8085
8086 /* Methods */
8087
8088 /**
8089 * Check if input supports multiple lines.
8090 *
8091 * @return {boolean}
8092 */
8093 OO.ui.TextInputWidget.prototype.isMultiline = function () {
8094 return !!this.multiline;
8095 };
8096
8097 /**
8098 * Check if input automatically adjusts its size.
8099 *
8100 * @return {boolean}
8101 */
8102 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
8103 return !!this.autosize;
8104 };
8105
8106 /**
8107 * Check if input is pending.
8108 *
8109 * @return {boolean}
8110 */
8111 OO.ui.TextInputWidget.prototype.isPending = function () {
8112 return !!this.pending;
8113 };
8114
8115 /**
8116 * Increase the pending stack.
8117 *
8118 * @chainable
8119 */
8120 OO.ui.TextInputWidget.prototype.pushPending = function () {
8121 if ( this.pending === 0 ) {
8122 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
8123 this.$input.addClass( 'oo-ui-texture-pending' );
8124 }
8125 this.pending++;
8126
8127 return this;
8128 };
8129
8130 /**
8131 * Reduce the pending stack.
8132 *
8133 * Clamped at zero.
8134 *
8135 * @chainable
8136 */
8137 OO.ui.TextInputWidget.prototype.popPending = function () {
8138 if ( this.pending === 1 ) {
8139 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
8140 this.$input.removeClass( 'oo-ui-texture-pending' );
8141 }
8142 this.pending = Math.max( 0, this.pending - 1 );
8143
8144 return this;
8145 };
8146
8147 /**
8148 * Select the contents of the input.
8149 *
8150 * @chainable
8151 */
8152 OO.ui.TextInputWidget.prototype.select = function () {
8153 this.$input.select();
8154 return this;
8155 };
8156 /**
8157 * Menu for a text input widget.
8158 *
8159 * @class
8160 * @extends OO.ui.MenuWidget
8161 *
8162 * @constructor
8163 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
8164 * @param {Object} [config] Configuration options
8165 * @cfg {jQuery} [$container=input.$element] Element to render menu under
8166 */
8167 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
8168 // Parent constructor
8169 OO.ui.TextInputMenuWidget.super.call( this, config );
8170
8171 // Properties
8172 this.input = input;
8173 this.$container = config.$container || this.input.$element;
8174 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
8175
8176 // Initialization
8177 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
8178 };
8179
8180 /* Setup */
8181
8182 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
8183
8184 /* Methods */
8185
8186 /**
8187 * Handle window resize event.
8188 *
8189 * @param {jQuery.Event} e Window resize event
8190 */
8191 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
8192 this.position();
8193 };
8194
8195 /**
8196 * Show the menu.
8197 *
8198 * @chainable
8199 */
8200 OO.ui.TextInputMenuWidget.prototype.show = function () {
8201 // Parent method
8202 OO.ui.MenuWidget.prototype.show.call( this );
8203
8204 this.position();
8205 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
8206 return this;
8207 };
8208
8209 /**
8210 * Hide the menu.
8211 *
8212 * @chainable
8213 */
8214 OO.ui.TextInputMenuWidget.prototype.hide = function () {
8215 // Parent method
8216 OO.ui.MenuWidget.prototype.hide.call( this );
8217
8218 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
8219 return this;
8220 };
8221
8222 /**
8223 * Position the menu.
8224 *
8225 * @chainable
8226 */
8227 OO.ui.TextInputMenuWidget.prototype.position = function () {
8228 var frameOffset,
8229 $container = this.$container,
8230 dimensions = $container.offset();
8231
8232 // Position under input
8233 dimensions.top += $container.height();
8234
8235 // Compensate for frame position if in a differnt frame
8236 if ( this.input.$.frame && this.input.$.context !== this.$element[0].ownerDocument ) {
8237 frameOffset = OO.ui.Element.getRelativePosition(
8238 this.input.$.frame.$element, this.$element.offsetParent()
8239 );
8240 dimensions.left += frameOffset.left;
8241 dimensions.top += frameOffset.top;
8242 } else {
8243 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
8244 if ( this.$element.css( 'direction' ) === 'rtl' ) {
8245 dimensions.right = this.$element.parent().position().left -
8246 dimensions.width - dimensions.left;
8247 // Erase the value for 'left':
8248 delete dimensions.left;
8249 }
8250 }
8251
8252 this.$element.css( dimensions );
8253 this.setIdealSize( $container.width() );
8254 return this;
8255 };
8256 /**
8257 * Width with on and off states.
8258 *
8259 * Mixin for widgets with a boolean state.
8260 *
8261 * @abstract
8262 * @class
8263 *
8264 * @constructor
8265 * @param {Object} [config] Configuration options
8266 * @cfg {boolean} [value=false] Initial value
8267 */
8268 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
8269 // Configuration initialization
8270 config = config || {};
8271
8272 // Properties
8273 this.value = null;
8274
8275 // Initialization
8276 this.$element.addClass( 'oo-ui-toggleWidget' );
8277 this.setValue( !!config.value );
8278 };
8279
8280 /* Events */
8281
8282 /**
8283 * @event change
8284 * @param {boolean} value Changed value
8285 */
8286
8287 /* Methods */
8288
8289 /**
8290 * Get the value of the toggle.
8291 *
8292 * @return {boolean}
8293 */
8294 OO.ui.ToggleWidget.prototype.getValue = function () {
8295 return this.value;
8296 };
8297
8298 /**
8299 * Set the value of the toggle.
8300 *
8301 * @param {boolean} value New value
8302 * @fires change
8303 * @chainable
8304 */
8305 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
8306 value = !!value;
8307 if ( this.value !== value ) {
8308 this.value = value;
8309 this.emit( 'change', value );
8310 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
8311 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
8312 }
8313 return this;
8314 };
8315 /**
8316 * Button that toggles on and off.
8317 *
8318 * @class
8319 * @extends OO.ui.ButtonWidget
8320 * @mixins OO.ui.ToggleWidget
8321 *
8322 * @constructor
8323 * @param {Object} [config] Configuration options
8324 * @cfg {boolean} [value=false] Initial value
8325 */
8326 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
8327 // Configuration initialization
8328 config = config || {};
8329
8330 // Parent constructor
8331 OO.ui.ToggleButtonWidget.super.call( this, config );
8332
8333 // Mixin constructors
8334 OO.ui.ToggleWidget.call( this, config );
8335
8336 // Initialization
8337 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
8338 };
8339
8340 /* Setup */
8341
8342 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
8343 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
8344
8345 /* Methods */
8346
8347 /**
8348 * @inheritdoc
8349 */
8350 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
8351 if ( !this.isDisabled() ) {
8352 this.setValue( !this.value );
8353 }
8354
8355 // Parent method
8356 return OO.ui.ButtonWidget.prototype.onClick.call( this );
8357 };
8358
8359 /**
8360 * @inheritdoc
8361 */
8362 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
8363 value = !!value;
8364 if ( value !== this.value ) {
8365 this.setActive( value );
8366 }
8367
8368 // Parent method
8369 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
8370
8371 return this;
8372 };
8373 /**
8374 * Switch that slides on and off.
8375 *
8376 * @class
8377 * @extends OO.ui.Widget
8378 * @mixins OO.ui.ToggleWidget
8379 *
8380 * @constructor
8381 * @param {Object} [config] Configuration options
8382 * @cfg {boolean} [value=false] Initial value
8383 */
8384 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
8385 // Parent constructor
8386 OO.ui.ToggleSwitchWidget.super.call( this, config );
8387
8388 // Mixin constructors
8389 OO.ui.ToggleWidget.call( this, config );
8390
8391 // Properties
8392 this.dragging = false;
8393 this.dragStart = null;
8394 this.sliding = false;
8395 this.$glow = this.$( '<span>' );
8396 this.$grip = this.$( '<span>' );
8397
8398 // Events
8399 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
8400
8401 // Initialization
8402 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
8403 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
8404 this.$element
8405 .addClass( 'oo-ui-toggleSwitchWidget' )
8406 .append( this.$glow, this.$grip );
8407 };
8408
8409 /* Setup */
8410
8411 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
8412 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
8413
8414 /* Methods */
8415
8416 /**
8417 * Handle mouse down events.
8418 *
8419 * @param {jQuery.Event} e Mouse down event
8420 */
8421 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
8422 if ( !this.isDisabled() && e.which === 1 ) {
8423 this.setValue( !this.value );
8424 }
8425 };
8426 }( OO ) );