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