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