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