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