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