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