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