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