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