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