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