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