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