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