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