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