Update OOjs UI to v0.1.0-pre (97dbb50137)
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.1.0-pre (97dbb50137)
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: 2014-07-16T22:59:48Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 'UNDEFINED': 0,
30 'BACKSPACE': 8,
31 'DELETE': 46,
32 'LEFT': 37,
33 'RIGHT': 39,
34 'UP': 38,
35 'DOWN': 40,
36 'ENTER': 13,
37 'END': 35,
38 'HOME': 36,
39 'TAB': 9,
40 'PAGEUP': 33,
41 'PAGEDOWN': 34,
42 'ESCAPE': 27,
43 'SHIFT': 16,
44 'SPACE': 32
45 };
46
47 /**
48 * Get the user's language and any fallback languages.
49 *
50 * These language codes are used to localize user interface elements in the user's language.
51 *
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
54 *
55 * @return {string[]} Language codes, in descending order of priority
56 */
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
59 };
60
61 /**
62 * Get a value in an object keyed by language code.
63 *
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
68 */
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
71
72 // Requested language
73 if ( obj[lang] ) {
74 return obj[lang];
75 }
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[i];
80 if ( obj[lang] ) {
81 return obj[lang];
82 }
83 }
84 // Fallback language
85 if ( obj[fallback] ) {
86 return obj[fallback];
87 }
88 // First existing language
89 for ( lang in obj ) {
90 return obj[lang];
91 }
92
93 return undefined;
94 };
95
96 ( function () {
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 // Tool tip for a button that moves items in a list down one place
107 'ooui-outline-control-move-down': 'Move item down',
108 // Tool tip for a button that moves items in a list up one place
109 'ooui-outline-control-move-up': 'Move item up',
110 // Tool tip for a button that removes items from a list
111 'ooui-outline-control-remove': 'Remove item',
112 // Label for the toolbar group that contains a list of all other available tools
113 'ooui-toolbar-more': 'More',
114 // Default label for the accept button of a confirmation dialog
115 'ooui-dialog-message-accept': 'OK',
116 // Default label for the reject button of a confirmation dialog
117 'ooui-dialog-message-reject': 'Cancel',
118 // Title for process dialog error description
119 'ooui-dialog-process-error': 'Something went wrong',
120 // Label for process dialog dismiss error button, visible when describing errors
121 'ooui-dialog-process-dismiss': 'Dismiss',
122 // Label for process dialog retry action button, visible when describing recoverable errors
123 'ooui-dialog-process-retry': 'Try again'
124 };
125
126 /**
127 * Get a localized message.
128 *
129 * In environments that provide a localization system, this function should be overridden to
130 * return the message translated in the user's language. The default implementation always returns
131 * English messages.
132 *
133 * After the message key, message parameters may optionally be passed. In the default implementation,
134 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
135 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
136 * they support unnamed, ordered message parameters.
137 *
138 * @abstract
139 * @param {string} key Message key
140 * @param {Mixed...} [params] Message parameters
141 * @return {string} Translated message with parameters substituted
142 */
143 OO.ui.msg = function ( key ) {
144 var message = messages[key], params = Array.prototype.slice.call( arguments, 1 );
145 if ( typeof message === 'string' ) {
146 // Perform $1 substitution
147 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
148 var i = parseInt( n, 10 );
149 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
150 } );
151 } else {
152 // Return placeholder if message not found
153 message = '[' + key + ']';
154 }
155 return message;
156 };
157
158 /**
159 * Package a message and arguments for deferred resolution.
160 *
161 * Use this when you are statically specifying a message and the message may not yet be present.
162 *
163 * @param {string} key Message key
164 * @param {Mixed...} [params] Message parameters
165 * @return {Function} Function that returns the resolved message when executed
166 */
167 OO.ui.deferMsg = function () {
168 var args = arguments;
169 return function () {
170 return OO.ui.msg.apply( OO.ui, args );
171 };
172 };
173
174 /**
175 * Resolve a message.
176 *
177 * If the message is a function it will be executed, otherwise it will pass through directly.
178 *
179 * @param {Function|string} msg Deferred message, or message text
180 * @return {string} Resolved message
181 */
182 OO.ui.resolveMsg = function ( msg ) {
183 if ( $.isFunction( msg ) ) {
184 return msg();
185 }
186 return msg;
187 };
188
189 } )();
190
191 /**
192 * List of actions.
193 *
194 * @abstract
195 * @class
196 * @mixins OO.EventEmitter
197 *
198 * @constructor
199 * @param {Object} [config] Configuration options
200 */
201 OO.ui.ActionSet = function OoUiActionSet( config ) {
202 // Configuration intialization
203 config = config || {};
204
205 // Mixin constructors
206 OO.EventEmitter.call( this );
207
208 // Properties
209 this.list = [];
210 this.categories = {
211 'actions': 'getAction',
212 'flags': 'getFlags',
213 'modes': 'getModes'
214 };
215 this.categorized = {};
216 this.special = {};
217 this.others = [];
218 this.organized = false;
219 this.changing = false;
220 this.changed = false;
221 };
222
223 /* Setup */
224
225 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
226
227 /* Static Properties */
228
229 /**
230 * Symbolic name of dialog.
231 *
232 * @abstract
233 * @static
234 * @inheritable
235 * @property {string}
236 */
237 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
238
239 /* Events */
240
241 /**
242 * @event click
243 * @param {OO.ui.ActionWidget} action Action that was clicked
244 */
245
246 /**
247 * @event resize
248 * @param {OO.ui.ActionWidget} action Action that was resized
249 */
250
251 /**
252 * @event add
253 * @param {OO.ui.ActionWidget[]} added Actions added
254 */
255
256 /**
257 * @event remove
258 * @param {OO.ui.ActionWidget[]} added Actions removed
259 */
260
261 /**
262 * @event change
263 */
264
265 /* Methods */
266
267 /**
268 * Handle action change events.
269 *
270 * @fires change
271 */
272 OO.ui.ActionSet.prototype.onActionChange = function () {
273 this.organized = false;
274 if ( this.changing ) {
275 this.changed = true;
276 } else {
277 this.emit( 'change' );
278 }
279 };
280
281 /**
282 * Check if a action is one of the special actions.
283 *
284 * @param {OO.ui.ActionWidget} action Action to check
285 * @return {boolean} Action is special
286 */
287 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
288 var flag;
289
290 for ( flag in this.special ) {
291 if ( action === this.special[flag] ) {
292 return true;
293 }
294 }
295
296 return false;
297 };
298
299 /**
300 * Get actions.
301 *
302 * @param {Object} [filters] Filters to use, omit to get all actions
303 * @param {string|string[]} [filters.actions] Actions that actions must have
304 * @param {string|string[]} [filters.flags] Flags that actions must have
305 * @param {string|string[]} [filters.modes] Modes that actions must have
306 * @param {boolean} [filters.visible] Actions must be visible
307 * @param {boolean} [filters.disabled] Actions must be disabled
308 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
309 */
310 OO.ui.ActionSet.prototype.get = function ( filters ) {
311 var i, len, list, category, actions, index, match, matches;
312
313 if ( filters ) {
314 this.organize();
315
316 // Collect category candidates
317 matches = [];
318 for ( category in this.categorized ) {
319 list = filters[category];
320 if ( list ) {
321 if ( !Array.isArray( list ) ) {
322 list = [ list ];
323 }
324 for ( i = 0, len = list.length; i < len; i++ ) {
325 actions = this.categorized[category][list[i]];
326 if ( Array.isArray( actions ) ) {
327 matches.push.apply( matches, actions );
328 }
329 }
330 }
331 }
332 // Remove by boolean filters
333 for ( i = 0, len = matches.length; i < len; i++ ) {
334 match = matches[i];
335 if (
336 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
337 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
338 ) {
339 matches.splice( i, 1 );
340 len--;
341 i--;
342 }
343 }
344 // Remove duplicates
345 for ( i = 0, len = matches.length; i < len; i++ ) {
346 match = matches[i];
347 index = matches.lastIndexOf( match );
348 while ( index !== i ) {
349 matches.splice( index, 1 );
350 len--;
351 index = matches.lastIndexOf( match );
352 }
353 }
354 return matches;
355 }
356 return this.list.slice();
357 };
358
359 /**
360 * Get special actions.
361 *
362 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
363 * Special flags can be configured by changing #static-specialFlags in a subclass.
364 *
365 * @return {OO.ui.ActionWidget|null} Safe action
366 */
367 OO.ui.ActionSet.prototype.getSpecial = function () {
368 this.organize();
369 return $.extend( {}, this.special );
370 };
371
372 /**
373 * Get other actions.
374 *
375 * Other actions include all non-special visible actions.
376 *
377 * @return {OO.ui.ActionWidget[]} Other actions
378 */
379 OO.ui.ActionSet.prototype.getOthers = function () {
380 this.organize();
381 return this.others.slice();
382 };
383
384 /**
385 * Toggle actions based on their modes.
386 *
387 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
388 * visibility; matching actions will be shown, non-matching actions will be hidden.
389 *
390 * @param {string} mode Mode actions must have
391 * @chainable
392 * @fires toggle
393 * @fires change
394 */
395 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
396 var i, len, action;
397
398 this.changing = true;
399 for ( i = 0, len = this.list.length; i < len; i++ ) {
400 action = this.list[i];
401 action.toggle( action.hasMode( mode ) );
402 }
403
404 this.organized = false;
405 this.changing = false;
406 this.emit( 'change' );
407
408 return this;
409 };
410
411 /**
412 * Change which actions are able to be performed.
413 *
414 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
415 *
416 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
417 * indicate actions are able to be performed
418 * @chainable
419 */
420 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
421 var i, len, action, item;
422
423 for ( i = 0, len = this.list.length; i < len; i++ ) {
424 item = this.list[i];
425 action = item.getAction();
426 if ( actions[action] !== undefined ) {
427 item.setDisabled( !actions[action] );
428 }
429 }
430
431 return this;
432 };
433
434 /**
435 * Executes a function once per action.
436 *
437 * When making changes to multiple actions, use this method instead of iterating over the actions
438 * manually to defer emitting a change event until after all actions have been changed.
439 *
440 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
441 * @param {Function} callback Callback to run for each action; callback is invoked with three
442 * arguments: the action, the action's index, the list of actions being iterated over
443 * @chainable
444 */
445 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
446 this.changed = false;
447 this.changing = true;
448 this.get( filter ).forEach( callback );
449 this.changing = false;
450 if ( this.changed ) {
451 this.emit( 'change' );
452 }
453
454 return this;
455 };
456
457 /**
458 * Add actions.
459 *
460 * @param {OO.ui.ActionWidget[]} actions Actions to add
461 * @chainable
462 * @fires add
463 * @fires change
464 */
465 OO.ui.ActionSet.prototype.add = function ( actions ) {
466 var i, len, action;
467
468 this.changing = true;
469 for ( i = 0, len = actions.length; i < len; i++ ) {
470 action = actions[i];
471 action.connect( this, {
472 'click': [ 'emit', 'click', action ],
473 'resize': [ 'emit', 'resize', action ],
474 'toggle': [ 'onActionChange' ]
475 } );
476 this.list.push( action );
477 }
478 this.organized = false;
479 this.emit( 'add', actions );
480 this.changing = false;
481 this.emit( 'change' );
482
483 return this;
484 };
485
486 /**
487 * Remove actions.
488 *
489 * @param {OO.ui.ActionWidget[]} actions Actions to remove
490 * @chainable
491 * @fires remove
492 * @fires change
493 */
494 OO.ui.ActionSet.prototype.remove = function ( actions ) {
495 var i, len, index, action;
496
497 this.changing = true;
498 for ( i = 0, len = actions.length; i < len; i++ ) {
499 action = actions[i];
500 index = this.list.indexOf( action );
501 if ( index !== -1 ) {
502 action.disconnect( this );
503 this.list.splice( index, 1 );
504 }
505 }
506 this.organized = false;
507 this.emit( 'remove', actions );
508 this.changing = false;
509 this.emit( 'change' );
510
511 return this;
512 };
513
514 /**
515 * Remove all actions.
516 *
517 * @chainable
518 * @fires remove
519 * @fires change
520 */
521 OO.ui.ActionSet.prototype.clear = function () {
522 var i, len, action,
523 removed = this.list.slice();
524
525 this.changing = true;
526 for ( i = 0, len = this.list.length; i < len; i++ ) {
527 action = this.list[i];
528 action.disconnect( this );
529 }
530
531 this.list = [];
532
533 this.organized = false;
534 this.emit( 'remove', removed );
535 this.changing = false;
536 this.emit( 'change' );
537
538 return this;
539 };
540
541 /**
542 * Organize actions.
543 *
544 * This is called whenver organized information is requested. It will only reorganize the actions
545 * if something has changed since the last time it ran.
546 *
547 * @private
548 * @chainable
549 */
550 OO.ui.ActionSet.prototype.organize = function () {
551 var i, iLen, j, jLen, flag, action, category, list, item, special,
552 specialFlags = this.constructor.static.specialFlags;
553
554 if ( !this.organized ) {
555 this.categorized = {};
556 this.special = {};
557 this.others = [];
558 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
559 action = this.list[i];
560 if ( action.isVisible() ) {
561 // Populate catgeories
562 for ( category in this.categories ) {
563 if ( !this.categorized[category] ) {
564 this.categorized[category] = {};
565 }
566 list = action[this.categories[category]]();
567 if ( !Array.isArray( list ) ) {
568 list = [ list ];
569 }
570 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
571 item = list[j];
572 if ( !this.categorized[category][item] ) {
573 this.categorized[category][item] = [];
574 }
575 this.categorized[category][item].push( action );
576 }
577 }
578 // Populate special/others
579 special = false;
580 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
581 flag = specialFlags[j];
582 if ( !this.special[flag] && action.hasFlag( flag ) ) {
583 this.special[flag] = action;
584 special = true;
585 break;
586 }
587 }
588 if ( !special ) {
589 this.others.push( action );
590 }
591 }
592 }
593 this.organized = true;
594 }
595
596 return this;
597 };
598
599 /**
600 * DOM element abstraction.
601 *
602 * @abstract
603 * @class
604 *
605 * @constructor
606 * @param {Object} [config] Configuration options
607 * @cfg {Function} [$] jQuery for the frame the widget is in
608 * @cfg {string[]} [classes] CSS class names
609 * @cfg {string} [text] Text to insert
610 * @cfg {jQuery} [$content] Content elements to append (after text)
611 */
612 OO.ui.Element = function OoUiElement( config ) {
613 // Configuration initialization
614 config = config || {};
615
616 // Properties
617 this.$ = config.$ || OO.ui.Element.getJQuery( document );
618 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
619 this.elementGroup = null;
620
621 // Initialization
622 if ( $.isArray( config.classes ) ) {
623 this.$element.addClass( config.classes.join( ' ' ) );
624 }
625 if ( config.text ) {
626 this.$element.text( config.text );
627 }
628 if ( config.$content ) {
629 this.$element.append( config.$content );
630 }
631 };
632
633 /* Setup */
634
635 OO.initClass( OO.ui.Element );
636
637 /* Static Properties */
638
639 /**
640 * HTML tag name.
641 *
642 * This may be ignored if getTagName is overridden.
643 *
644 * @static
645 * @inheritable
646 * @property {string}
647 */
648 OO.ui.Element.static.tagName = 'div';
649
650 /* Static Methods */
651
652 /**
653 * Get a jQuery function within a specific document.
654 *
655 * @static
656 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
657 * @param {OO.ui.Frame} [frame] Frame of the document context
658 * @return {Function} Bound jQuery function
659 */
660 OO.ui.Element.getJQuery = function ( context, frame ) {
661 function wrapper( selector ) {
662 return $( selector, wrapper.context );
663 }
664
665 wrapper.context = this.getDocument( context );
666
667 if ( frame ) {
668 wrapper.frame = frame;
669 }
670
671 return wrapper;
672 };
673
674 /**
675 * Get the document of an element.
676 *
677 * @static
678 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
679 * @return {HTMLDocument|null} Document object
680 */
681 OO.ui.Element.getDocument = function ( obj ) {
682 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
683 return ( obj[0] && obj[0].ownerDocument ) ||
684 // Empty jQuery selections might have a context
685 obj.context ||
686 // HTMLElement
687 obj.ownerDocument ||
688 // Window
689 obj.document ||
690 // HTMLDocument
691 ( obj.nodeType === 9 && obj ) ||
692 null;
693 };
694
695 /**
696 * Get the window of an element or document.
697 *
698 * @static
699 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
700 * @return {Window} Window object
701 */
702 OO.ui.Element.getWindow = function ( obj ) {
703 var doc = this.getDocument( obj );
704 return doc.parentWindow || doc.defaultView;
705 };
706
707 /**
708 * Get the direction of an element or document.
709 *
710 * @static
711 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
712 * @return {string} Text direction, either `ltr` or `rtl`
713 */
714 OO.ui.Element.getDir = function ( obj ) {
715 var isDoc, isWin;
716
717 if ( obj instanceof jQuery ) {
718 obj = obj[0];
719 }
720 isDoc = obj.nodeType === 9;
721 isWin = obj.document !== undefined;
722 if ( isDoc || isWin ) {
723 if ( isWin ) {
724 obj = obj.document;
725 }
726 obj = obj.body;
727 }
728 return $( obj ).css( 'direction' );
729 };
730
731 /**
732 * Get the offset between two frames.
733 *
734 * TODO: Make this function not use recursion.
735 *
736 * @static
737 * @param {Window} from Window of the child frame
738 * @param {Window} [to=window] Window of the parent frame
739 * @param {Object} [offset] Offset to start with, used internally
740 * @return {Object} Offset object, containing left and top properties
741 */
742 OO.ui.Element.getFrameOffset = function ( from, to, offset ) {
743 var i, len, frames, frame, rect;
744
745 if ( !to ) {
746 to = window;
747 }
748 if ( !offset ) {
749 offset = { 'top': 0, 'left': 0 };
750 }
751 if ( from.parent === from ) {
752 return offset;
753 }
754
755 // Get iframe element
756 frames = from.parent.document.getElementsByTagName( 'iframe' );
757 for ( i = 0, len = frames.length; i < len; i++ ) {
758 if ( frames[i].contentWindow === from ) {
759 frame = frames[i];
760 break;
761 }
762 }
763
764 // Recursively accumulate offset values
765 if ( frame ) {
766 rect = frame.getBoundingClientRect();
767 offset.left += rect.left;
768 offset.top += rect.top;
769 if ( from !== to ) {
770 this.getFrameOffset( from.parent, offset );
771 }
772 }
773 return offset;
774 };
775
776 /**
777 * Get the offset between two elements.
778 *
779 * @static
780 * @param {jQuery} $from
781 * @param {jQuery} $to
782 * @return {Object} Translated position coordinates, containing top and left properties
783 */
784 OO.ui.Element.getRelativePosition = function ( $from, $to ) {
785 var from = $from.offset(),
786 to = $to.offset();
787 return { 'top': Math.round( from.top - to.top ), 'left': Math.round( from.left - to.left ) };
788 };
789
790 /**
791 * Get element border sizes.
792 *
793 * @static
794 * @param {HTMLElement} el Element to measure
795 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
796 */
797 OO.ui.Element.getBorders = function ( el ) {
798 var doc = el.ownerDocument,
799 win = doc.parentWindow || doc.defaultView,
800 style = win && win.getComputedStyle ?
801 win.getComputedStyle( el, null ) :
802 el.currentStyle,
803 $el = $( el ),
804 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
805 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
806 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
807 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
808
809 return {
810 'top': Math.round( top ),
811 'left': Math.round( left ),
812 'bottom': Math.round( bottom ),
813 'right': Math.round( right )
814 };
815 };
816
817 /**
818 * Get dimensions of an element or window.
819 *
820 * @static
821 * @param {HTMLElement|Window} el Element to measure
822 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
823 */
824 OO.ui.Element.getDimensions = function ( el ) {
825 var $el, $win,
826 doc = el.ownerDocument || el.document,
827 win = doc.parentWindow || doc.defaultView;
828
829 if ( win === el || el === doc.documentElement ) {
830 $win = $( win );
831 return {
832 'borders': { 'top': 0, 'left': 0, 'bottom': 0, 'right': 0 },
833 'scroll': {
834 'top': $win.scrollTop(),
835 'left': $win.scrollLeft()
836 },
837 'scrollbar': { 'right': 0, 'bottom': 0 },
838 'rect': {
839 'top': 0,
840 'left': 0,
841 'bottom': $win.innerHeight(),
842 'right': $win.innerWidth()
843 }
844 };
845 } else {
846 $el = $( el );
847 return {
848 'borders': this.getBorders( el ),
849 'scroll': {
850 'top': $el.scrollTop(),
851 'left': $el.scrollLeft()
852 },
853 'scrollbar': {
854 'right': $el.innerWidth() - el.clientWidth,
855 'bottom': $el.innerHeight() - el.clientHeight
856 },
857 'rect': el.getBoundingClientRect()
858 };
859 }
860 };
861
862 /**
863 * Get closest scrollable container.
864 *
865 * Traverses up until either a scrollable element or the root is reached, in which case the window
866 * will be returned.
867 *
868 * @static
869 * @param {HTMLElement} el Element to find scrollable container for
870 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
871 * @return {HTMLElement|Window} Closest scrollable container
872 */
873 OO.ui.Element.getClosestScrollableContainer = function ( el, dimension ) {
874 var i, val,
875 props = [ 'overflow' ],
876 $parent = $( el ).parent();
877
878 if ( dimension === 'x' || dimension === 'y' ) {
879 props.push( 'overflow-' + dimension );
880 }
881
882 while ( $parent.length ) {
883 if ( $parent[0] === el.ownerDocument.body ) {
884 return $parent[0];
885 }
886 i = props.length;
887 while ( i-- ) {
888 val = $parent.css( props[i] );
889 if ( val === 'auto' || val === 'scroll' ) {
890 return $parent[0];
891 }
892 }
893 $parent = $parent.parent();
894 }
895 return this.getDocument( el ).body;
896 };
897
898 /**
899 * Scroll element into view.
900 *
901 * @static
902 * @param {HTMLElement} el Element to scroll into view
903 * @param {Object} [config={}] Configuration config
904 * @param {string} [config.duration] jQuery animation duration value
905 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
906 * to scroll in both directions
907 * @param {Function} [config.complete] Function to call when scrolling completes
908 */
909 OO.ui.Element.scrollIntoView = function ( el, config ) {
910 // Configuration initialization
911 config = config || {};
912
913 var rel, anim = {},
914 callback = typeof config.complete === 'function' && config.complete,
915 sc = this.getClosestScrollableContainer( el, config.direction ),
916 $sc = $( sc ),
917 eld = this.getDimensions( el ),
918 scd = this.getDimensions( sc ),
919 $win = $( this.getWindow( el ) );
920
921 // Compute the distances between the edges of el and the edges of the scroll viewport
922 if ( $sc.is( 'body' ) ) {
923 // If the scrollable container is the <body> this is easy
924 rel = {
925 'top': eld.rect.top,
926 'bottom': $win.innerHeight() - eld.rect.bottom,
927 'left': eld.rect.left,
928 'right': $win.innerWidth() - eld.rect.right
929 };
930 } else {
931 // Otherwise, we have to subtract el's coordinates from sc's coordinates
932 rel = {
933 'top': eld.rect.top - ( scd.rect.top + scd.borders.top ),
934 'bottom': scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
935 'left': eld.rect.left - ( scd.rect.left + scd.borders.left ),
936 'right': scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
937 };
938 }
939
940 if ( !config.direction || config.direction === 'y' ) {
941 if ( rel.top < 0 ) {
942 anim.scrollTop = scd.scroll.top + rel.top;
943 } else if ( rel.top > 0 && rel.bottom < 0 ) {
944 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
945 }
946 }
947 if ( !config.direction || config.direction === 'x' ) {
948 if ( rel.left < 0 ) {
949 anim.scrollLeft = scd.scroll.left + rel.left;
950 } else if ( rel.left > 0 && rel.right < 0 ) {
951 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
952 }
953 }
954 if ( !$.isEmptyObject( anim ) ) {
955 $sc.stop( true ).animate( anim, config.duration || 'fast' );
956 if ( callback ) {
957 $sc.queue( function ( next ) {
958 callback();
959 next();
960 } );
961 }
962 } else {
963 if ( callback ) {
964 callback();
965 }
966 }
967 };
968
969 /* Methods */
970
971 /**
972 * Get the HTML tag name.
973 *
974 * Override this method to base the result on instance information.
975 *
976 * @return {string} HTML tag name
977 */
978 OO.ui.Element.prototype.getTagName = function () {
979 return this.constructor.static.tagName;
980 };
981
982 /**
983 * Check if the element is attached to the DOM
984 * @return {boolean} The element is attached to the DOM
985 */
986 OO.ui.Element.prototype.isElementAttached = function () {
987 return $.contains( this.getElementDocument(), this.$element[0] );
988 };
989
990 /**
991 * Get the DOM document.
992 *
993 * @return {HTMLDocument} Document object
994 */
995 OO.ui.Element.prototype.getElementDocument = function () {
996 return OO.ui.Element.getDocument( this.$element );
997 };
998
999 /**
1000 * Get the DOM window.
1001 *
1002 * @return {Window} Window object
1003 */
1004 OO.ui.Element.prototype.getElementWindow = function () {
1005 return OO.ui.Element.getWindow( this.$element );
1006 };
1007
1008 /**
1009 * Get closest scrollable container.
1010 */
1011 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1012 return OO.ui.Element.getClosestScrollableContainer( this.$element[0] );
1013 };
1014
1015 /**
1016 * Get group element is in.
1017 *
1018 * @return {OO.ui.GroupElement|null} Group element, null if none
1019 */
1020 OO.ui.Element.prototype.getElementGroup = function () {
1021 return this.elementGroup;
1022 };
1023
1024 /**
1025 * Set group element is in.
1026 *
1027 * @param {OO.ui.GroupElement|null} group Group element, null if none
1028 * @chainable
1029 */
1030 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1031 this.elementGroup = group;
1032 return this;
1033 };
1034
1035 /**
1036 * Scroll element into view.
1037 *
1038 * @param {Object} [config={}]
1039 */
1040 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1041 return OO.ui.Element.scrollIntoView( this.$element[0], config );
1042 };
1043
1044 /**
1045 * Bind a handler for an event on this.$element
1046 *
1047 * @deprecated Use jQuery#on instead.
1048 * @param {string} event
1049 * @param {Function} callback
1050 */
1051 OO.ui.Element.prototype.onDOMEvent = function ( event, callback ) {
1052 OO.ui.Element.onDOMEvent( this.$element, event, callback );
1053 };
1054
1055 /**
1056 * Unbind a handler bound with #offDOMEvent
1057 *
1058 * @deprecated Use jQuery#off instead.
1059 * @param {string} event
1060 * @param {Function} callback
1061 */
1062 OO.ui.Element.prototype.offDOMEvent = function ( event, callback ) {
1063 OO.ui.Element.offDOMEvent( this.$element, event, callback );
1064 };
1065
1066 ( function () {
1067 /**
1068 * Bind a handler for an event on a DOM element.
1069 *
1070 * Used to be for working around a jQuery bug (jqbug.com/14180),
1071 * but obsolete as of jQuery 1.11.0.
1072 *
1073 * @static
1074 * @deprecated Use jQuery#on instead.
1075 * @param {HTMLElement|jQuery} el DOM element
1076 * @param {string} event Event to bind
1077 * @param {Function} callback Callback to call when the event fires
1078 */
1079 OO.ui.Element.onDOMEvent = function ( el, event, callback ) {
1080 $( el ).on( event, callback );
1081 };
1082
1083 /**
1084 * Unbind a handler bound with #static-method-onDOMEvent.
1085 *
1086 * @deprecated Use jQuery#off instead.
1087 * @static
1088 * @param {HTMLElement|jQuery} el DOM element
1089 * @param {string} event Event to unbind
1090 * @param {Function} [callback] Callback to unbind
1091 */
1092 OO.ui.Element.offDOMEvent = function ( el, event, callback ) {
1093 $( el ).off( event, callback );
1094 };
1095 }() );
1096
1097 /**
1098 * Embedded iframe with the same styles as its parent.
1099 *
1100 * @class
1101 * @extends OO.ui.Element
1102 * @mixins OO.EventEmitter
1103 *
1104 * @constructor
1105 * @param {Object} [config] Configuration options
1106 */
1107 OO.ui.Frame = function OoUiFrame( config ) {
1108 // Parent constructor
1109 OO.ui.Frame.super.call( this, config );
1110
1111 // Mixin constructors
1112 OO.EventEmitter.call( this );
1113
1114 // Properties
1115 this.loading = null;
1116 this.config = config;
1117
1118 // Initialize
1119 this.$element
1120 .addClass( 'oo-ui-frame' )
1121 .attr( { 'frameborder': 0, 'scrolling': 'no' } );
1122
1123 };
1124
1125 /* Setup */
1126
1127 OO.inheritClass( OO.ui.Frame, OO.ui.Element );
1128 OO.mixinClass( OO.ui.Frame, OO.EventEmitter );
1129
1130 /* Static Properties */
1131
1132 /**
1133 * @static
1134 * @inheritdoc
1135 */
1136 OO.ui.Frame.static.tagName = 'iframe';
1137
1138 /* Events */
1139
1140 /**
1141 * @event load
1142 */
1143
1144 /* Static Methods */
1145
1146 /**
1147 * Transplant the CSS styles from as parent document to a frame's document.
1148 *
1149 * This loops over the style sheets in the parent document, and copies their nodes to the
1150 * frame's document. It then polls the document to see when all styles have loaded, and once they
1151 * have, resolves the promise.
1152 *
1153 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1154 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1155 * Firefox, where the styles won't load until the iframe becomes visible.
1156 *
1157 * For details of how we arrived at the strategy used in this function, see #load.
1158 *
1159 * @static
1160 * @inheritable
1161 * @param {HTMLDocument} parentDoc Document to transplant styles from
1162 * @param {HTMLDocument} frameDoc Document to transplant styles to
1163 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1164 * @return {jQuery.Promise} Promise resolved when styles have loaded
1165 */
1166 OO.ui.Frame.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1167 var i, numSheets, styleNode, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1168 $pollNodes = $( [] ),
1169 // Fake font-family value
1170 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1171 deferred = $.Deferred();
1172
1173 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1174 styleNode = parentDoc.styleSheets[i].ownerNode;
1175 if ( styleNode.disabled ) {
1176 continue;
1177 }
1178 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1179 // External stylesheet
1180 // Create a node with a unique ID that we're going to monitor to see when the CSS
1181 // has loaded
1182 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + i;
1183 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1184 .attr( 'id', pollNodeId )
1185 .appendTo( frameDoc.body )
1186 );
1187
1188 // Add <style>@import url(...); #pollNodeId { font-family: ... }</style>
1189 // The font-family rule will only take effect once the @import finishes
1190 newNode = frameDoc.createElement( 'style' );
1191 newNode.textContent = '@import url(' + styleNode.href + ');\n' +
1192 '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1193 } else {
1194 // Not an external stylesheet, or no polling required; just copy the node over
1195 newNode = frameDoc.importNode( styleNode, true );
1196 }
1197 frameDoc.head.appendChild( newNode );
1198 }
1199
1200 // Poll every 100ms until all external stylesheets have loaded
1201 $pendingPollNodes = $pollNodes;
1202 timeoutID = setTimeout( function pollExternalStylesheets() {
1203 while (
1204 $pendingPollNodes.length > 0 &&
1205 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1206 ) {
1207 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1208 }
1209
1210 if ( $pendingPollNodes.length === 0 ) {
1211 // We're done!
1212 if ( timeoutID !== null ) {
1213 timeoutID = null;
1214 $pollNodes.remove();
1215 deferred.resolve();
1216 }
1217 } else {
1218 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1219 }
1220 }, 100 );
1221 // ...but give up after a while
1222 if ( timeout !== 0 ) {
1223 setTimeout( function () {
1224 if ( timeoutID ) {
1225 clearTimeout( timeoutID );
1226 timeoutID = null;
1227 $pollNodes.remove();
1228 deferred.reject();
1229 }
1230 }, timeout || 5000 );
1231 }
1232
1233 return deferred.promise();
1234 };
1235
1236 /* Methods */
1237
1238 /**
1239 * Load the frame contents.
1240 *
1241 * Once the iframe's stylesheets are loaded, the `load` event will be emitted and the returned
1242 * promise will be resolved. Calling while loading will return a promise but not trigger a new
1243 * loading cycle. Calling after loading is complete will return a promise that's already been
1244 * resolved.
1245 *
1246 * Sounds simple right? Read on...
1247 *
1248 * When you create a dynamic iframe using open/write/close, the window.load event for the
1249 * iframe is triggered when you call close, and there's no further load event to indicate that
1250 * everything is actually loaded.
1251 *
1252 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
1253 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
1254 * are added to document.styleSheets immediately, and the only way you can determine whether they've
1255 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
1256 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
1257 *
1258 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>` tags.
1259 * Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets until
1260 * the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the `@import`
1261 * has finished. And because the contents of the `<style>` tag are from the same origin, accessing
1262 * .cssRules is allowed.
1263 *
1264 * However, now that we control the styles we're injecting, we might as well do away with
1265 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
1266 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
1267 * and wait for its font-family to change to someValue. Because `@import` is blocking, the font-family
1268 * rule is not applied until after the `@import` finishes.
1269 *
1270 * All this stylesheet injection and polling magic is in #transplantStyles.
1271 *
1272 * @return {jQuery.Promise} Promise resolved when loading is complete
1273 * @fires load
1274 */
1275 OO.ui.Frame.prototype.load = function () {
1276 var win, doc,
1277 frame = this;
1278
1279 // Return existing promise if already loading or loaded
1280 if ( this.loading ) {
1281 return this.loading.promise();
1282 }
1283
1284 // Load the frame
1285 this.loading = $.Deferred();
1286
1287 win = this.$element.prop( 'contentWindow' );
1288 doc = win.document;
1289
1290 // Figure out directionality:
1291 this.dir = OO.ui.Element.getDir( this.$element ) || 'ltr';
1292
1293 // Initialize contents
1294 doc.open();
1295 doc.write(
1296 '<!doctype html>' +
1297 '<html>' +
1298 '<body class="oo-ui-frame-content oo-ui-' + this.dir + '" style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
1299 '</body>' +
1300 '</html>'
1301 );
1302 doc.close();
1303
1304 // Properties
1305 this.$ = OO.ui.Element.getJQuery( doc, this );
1306 this.$content = this.$( '.oo-ui-frame-content' ).attr( 'tabIndex', 0 );
1307 this.$document = this.$( doc );
1308
1309 // Initialization
1310 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[0] )
1311 .always( function () {
1312 frame.emit( 'load' );
1313 frame.loading.resolve();
1314 } );
1315
1316 return this.loading.promise();
1317 };
1318
1319 /**
1320 * Set the size of the frame.
1321 *
1322 * @param {number} width Frame width in pixels
1323 * @param {number} height Frame height in pixels
1324 * @chainable
1325 */
1326 OO.ui.Frame.prototype.setSize = function ( width, height ) {
1327 this.$element.css( { 'width': width, 'height': height } );
1328 return this;
1329 };
1330
1331 /**
1332 * Container for elements.
1333 *
1334 * @abstract
1335 * @class
1336 * @extends OO.ui.Element
1337 * @mixins OO.EventEmitter
1338 *
1339 * @constructor
1340 * @param {Object} [config] Configuration options
1341 */
1342 OO.ui.Layout = function OoUiLayout( config ) {
1343 // Initialize config
1344 config = config || {};
1345
1346 // Parent constructor
1347 OO.ui.Layout.super.call( this, config );
1348
1349 // Mixin constructors
1350 OO.EventEmitter.call( this );
1351
1352 // Initialization
1353 this.$element.addClass( 'oo-ui-layout' );
1354 };
1355
1356 /* Setup */
1357
1358 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1359 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1360
1361 /**
1362 * User interface control.
1363 *
1364 * @abstract
1365 * @class
1366 * @extends OO.ui.Element
1367 * @mixins OO.EventEmitter
1368 *
1369 * @constructor
1370 * @param {Object} [config] Configuration options
1371 * @cfg {boolean} [disabled=false] Disable
1372 */
1373 OO.ui.Widget = function OoUiWidget( config ) {
1374 // Initialize config
1375 config = $.extend( { 'disabled': false }, config );
1376
1377 // Parent constructor
1378 OO.ui.Widget.super.call( this, config );
1379
1380 // Mixin constructors
1381 OO.EventEmitter.call( this );
1382
1383 // Properties
1384 this.visible = true;
1385 this.disabled = null;
1386 this.wasDisabled = null;
1387
1388 // Initialization
1389 this.$element.addClass( 'oo-ui-widget' );
1390 this.setDisabled( !!config.disabled );
1391 };
1392
1393 /* Setup */
1394
1395 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1396 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1397
1398 /* Events */
1399
1400 /**
1401 * @event disable
1402 * @param {boolean} disabled Widget is disabled
1403 */
1404
1405 /**
1406 * @event toggle
1407 * @param {boolean} visible Widget is visible
1408 */
1409
1410 /* Methods */
1411
1412 /**
1413 * Check if the widget is disabled.
1414 *
1415 * @param {boolean} Button is disabled
1416 */
1417 OO.ui.Widget.prototype.isDisabled = function () {
1418 return this.disabled;
1419 };
1420
1421 /**
1422 * Check if widget is visible.
1423 *
1424 * @return {boolean} Widget is visible
1425 */
1426 OO.ui.Widget.prototype.isVisible = function () {
1427 return this.visible;
1428 };
1429
1430 /**
1431 * Set the disabled state of the widget.
1432 *
1433 * This should probably change the widgets' appearance and prevent it from being used.
1434 *
1435 * @param {boolean} disabled Disable widget
1436 * @chainable
1437 */
1438 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1439 var isDisabled;
1440
1441 this.disabled = !!disabled;
1442 isDisabled = this.isDisabled();
1443 if ( isDisabled !== this.wasDisabled ) {
1444 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1445 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1446 this.emit( 'disable', isDisabled );
1447 }
1448 this.wasDisabled = isDisabled;
1449
1450 return this;
1451 };
1452
1453 /**
1454 * Toggle visibility of widget.
1455 *
1456 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1457 * @fires visible
1458 * @chainable
1459 */
1460 OO.ui.Widget.prototype.toggle = function ( show ) {
1461 show = show === undefined ? !this.visible : !!show;
1462
1463 if ( show !== this.isVisible() ) {
1464 this.visible = show;
1465 this.$element.toggle( show );
1466 this.emit( 'toggle', show );
1467 }
1468
1469 return this;
1470 };
1471
1472 /**
1473 * Update the disabled state, in case of changes in parent widget.
1474 *
1475 * @chainable
1476 */
1477 OO.ui.Widget.prototype.updateDisabled = function () {
1478 this.setDisabled( this.disabled );
1479 return this;
1480 };
1481
1482 /**
1483 * Container for elements in a child frame.
1484 *
1485 * Use together with OO.ui.WindowManager.
1486 *
1487 * @abstract
1488 * @class
1489 * @extends OO.ui.Element
1490 * @mixins OO.EventEmitter
1491 *
1492 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1493 * teardown processes are executed when the window is closed.
1494 *
1495 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1496 * - Window manager begins opening window
1497 * - {@link #getSetupProcess} method is called and its result executed
1498 * - {@link #getReadyProcess} method is called and its result executed
1499 * - Window is now open
1500 *
1501 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1502 * - Window manager begins closing window
1503 * - {@link #getHoldProcess} method is called and its result executed
1504 * - {@link #getTeardownProcess} method is called and its result executed
1505 * - Window is now closed
1506 *
1507 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1508 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1509 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchonous
1510 * processing can complete. Always assume window processes are executed asychronously. See
1511 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1512 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1513 *
1514 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1515 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1516 *
1517 * @constructor
1518 * @param {OO.ui.WindowManager} manager Manager of window
1519 * @param {Object} [config] Configuration options
1520 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large` or `full`; omit to
1521 * use #static-size
1522 * @fires initialize
1523 */
1524 OO.ui.Window = function OoUiWindow( manager, config ) {
1525 var win = this;
1526
1527 // Configuration initialization
1528 config = config || {};
1529
1530 // Parent constructor
1531 OO.ui.Window.super.call( this, config );
1532
1533 // Mixin constructors
1534 OO.EventEmitter.call( this );
1535
1536 if ( !( manager instanceof OO.ui.WindowManager ) ) {
1537 throw new Error( 'Cannot construct window: window must have a manager' );
1538 }
1539
1540 // Properties
1541 this.manager = manager;
1542 this.initialized = false;
1543 this.visible = false;
1544 this.opening = null;
1545 this.closing = null;
1546 this.opened = null;
1547 this.timing = null;
1548 this.size = config.size || this.constructor.static.size;
1549 this.frame = new OO.ui.Frame( { '$': this.$ } );
1550 this.$frame = this.$( '<div>' );
1551 this.$ = function () {
1552 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1553 };
1554
1555 // Initialization
1556 this.$element
1557 .addClass( 'oo-ui-window' )
1558 // Hide the window using visibility: hidden; while the iframe is still loading
1559 // Can't use display: none; because that prevents the iframe from loading in Firefox
1560 .css( 'visibility', 'hidden' )
1561 .append( this.$frame );
1562 this.$frame
1563 .addClass( 'oo-ui-window-frame' )
1564 .append( this.frame.$element );
1565
1566 // Events
1567 this.frame.on( 'load', function () {
1568 win.initialize();
1569 win.initialized = true;
1570 // Undo the visibility: hidden; hack and apply display: none;
1571 // We can do this safely now that the iframe has initialized
1572 // (don't do this from within #initialize because it has to happen
1573 // after the all subclasses have been handled as well).
1574 win.$element.hide().css( 'visibility', '' );
1575 } );
1576 };
1577
1578 /* Setup */
1579
1580 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1581 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1582
1583 /* Events */
1584
1585 /**
1586 * @event resize
1587 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1588 */
1589
1590 /* Static Properties */
1591
1592 /**
1593 * Symbolic name of size.
1594 *
1595 * Size is used if no size is configured during construction.
1596 *
1597 * @static
1598 * @inheritable
1599 * @property {string}
1600 */
1601 OO.ui.Window.static.size = 'medium';
1602
1603 /* Methods */
1604
1605 /**
1606 * Check if window has been initialized.
1607 *
1608 * @return {boolean} Window has been initialized
1609 */
1610 OO.ui.Window.prototype.isInitialized = function () {
1611 return this.initialized;
1612 };
1613
1614 /**
1615 * Check if window is visible.
1616 *
1617 * @return {boolean} Window is visible
1618 */
1619 OO.ui.Window.prototype.isVisible = function () {
1620 return this.visible;
1621 };
1622
1623 /**
1624 * Check if window is opening.
1625 *
1626 * This is a wrapper around OO.ui.WindowManager#isOpening.
1627 *
1628 * @return {boolean} Window is opening
1629 */
1630 OO.ui.Window.prototype.isOpening = function () {
1631 return this.manager.isOpening( this );
1632 };
1633
1634 /**
1635 * Check if window is closing.
1636 *
1637 * This is a wrapper around OO.ui.WindowManager#isClosing.
1638 *
1639 * @return {boolean} Window is closing
1640 */
1641 OO.ui.Window.prototype.isClosing = function () {
1642 return this.manager.isClosing( this );
1643 };
1644
1645 /**
1646 * Check if window is opened.
1647 *
1648 * This is a wrapper around OO.ui.WindowManager#isOpened.
1649 *
1650 * @return {boolean} Window is opened
1651 */
1652 OO.ui.Window.prototype.isOpened = function () {
1653 return this.manager.isOpened( this );
1654 };
1655
1656 /**
1657 * Get the window manager.
1658 *
1659 * @return {OO.ui.WindowManager} Manager of window
1660 */
1661 OO.ui.Window.prototype.getManager = function () {
1662 return this.manager;
1663 };
1664
1665 /**
1666 * Get the window frame.
1667 *
1668 * @return {OO.ui.Frame} Frame of window
1669 */
1670 OO.ui.Window.prototype.getFrame = function () {
1671 return this.frame;
1672 };
1673
1674 /**
1675 * Get the window size.
1676 *
1677 * @return {string} Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1678 */
1679 OO.ui.Window.prototype.getSize = function () {
1680 return this.size;
1681 };
1682
1683 /**
1684 * Get the height of the dialog contents.
1685 *
1686 * @return {number} Content height
1687 */
1688 OO.ui.Window.prototype.getContentHeight = function () {
1689 return Math.round(
1690 // Add buffer for border
1691 ( ( this.$frame.outerHeight() - this.$frame.innerHeight() ) * 2 ) +
1692 // Height of contents
1693 ( this.$head.outerHeight( true ) + this.getBodyHeight() + this.$foot.outerHeight( true ) )
1694 );
1695 };
1696
1697 /**
1698 * Get the height of the dialog contents.
1699 *
1700 * @return {number} Height of content
1701 */
1702 OO.ui.Window.prototype.getBodyHeight = function () {
1703 return this.$body[0].scrollHeight;
1704 };
1705
1706 /**
1707 * Get a process for setting up a window for use.
1708 *
1709 * Each time the window is opened this process will set it up for use in a particular context, based
1710 * on the `data` argument.
1711 *
1712 * When you override this method, you can add additional setup steps to the process the parent
1713 * method provides using the 'first' and 'next' methods.
1714 *
1715 * @abstract
1716 * @param {Object} [data] Window opening data
1717 * @return {OO.ui.Process} Setup process
1718 */
1719 OO.ui.Window.prototype.getSetupProcess = function () {
1720 return new OO.ui.Process();
1721 };
1722
1723 /**
1724 * Get a process for readying a window for use.
1725 *
1726 * Each time the window is open and setup, this process will ready it up for use in a particular
1727 * context, based on the `data` argument.
1728 *
1729 * When you override this method, you can add additional setup steps to the process the parent
1730 * method provides using the 'first' and 'next' methods.
1731 *
1732 * @abstract
1733 * @param {Object} [data] Window opening data
1734 * @return {OO.ui.Process} Setup process
1735 */
1736 OO.ui.Window.prototype.getReadyProcess = function () {
1737 return new OO.ui.Process();
1738 };
1739
1740 /**
1741 * Get a process for holding a window from use.
1742 *
1743 * Each time the window is closed, this process will hold it from use in a particular context, based
1744 * on the `data` argument.
1745 *
1746 * When you override this method, you can add additional setup steps to the process the parent
1747 * method provides using the 'first' and 'next' methods.
1748 *
1749 * @abstract
1750 * @param {Object} [data] Window closing data
1751 * @return {OO.ui.Process} Hold process
1752 */
1753 OO.ui.Window.prototype.getHoldProcess = function () {
1754 return new OO.ui.Process();
1755 };
1756
1757 /**
1758 * Get a process for tearing down a window after use.
1759 *
1760 * Each time the window is closed this process will tear it down and do something with the user's
1761 * interactions within the window, based on the `data` argument.
1762 *
1763 * When you override this method, you can add additional teardown steps to the process the parent
1764 * method provides using the 'first' and 'next' methods.
1765 *
1766 * @abstract
1767 * @param {Object} [data] Window closing data
1768 * @return {OO.ui.Process} Teardown process
1769 */
1770 OO.ui.Window.prototype.getTeardownProcess = function () {
1771 return new OO.ui.Process();
1772 };
1773
1774 /**
1775 * Set the window size.
1776 *
1777 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1778 * @chainable
1779 */
1780 OO.ui.Window.prototype.setSize = function ( size ) {
1781 this.size = size;
1782 this.manager.updateWindowSize( this );
1783 return this;
1784 };
1785
1786 /**
1787 * Set window dimensions.
1788 *
1789 * Properties are applied to the frame container.
1790 *
1791 * @param {Object} dim CSS dimension properties
1792 * @param {string|number} [dim.width] Width
1793 * @param {string|number} [dim.minWidth] Minimum width
1794 * @param {string|number} [dim.maxWidth] Maximum width
1795 * @param {string|number} [dim.width] Height, omit to set based on height of contents
1796 * @param {string|number} [dim.minWidth] Minimum height
1797 * @param {string|number} [dim.maxWidth] Maximum height
1798 * @chainable
1799 */
1800 OO.ui.Window.prototype.setDimensions = function ( dim ) {
1801 // Apply width before height so height is not based on wrapping content using the wrong width
1802 this.$frame.css( {
1803 'width': dim.width || '',
1804 'min-width': dim.minWidth || '',
1805 'max-width': dim.maxWidth || ''
1806 } );
1807 this.$frame.css( {
1808 'height': ( dim.height !== undefined ? dim.height : this.getContentHeight() ) || '',
1809 'min-height': dim.minHeight || '',
1810 'max-height': dim.maxHeight || ''
1811 } );
1812 return this;
1813 };
1814
1815 /**
1816 * Initialize window contents.
1817 *
1818 * The first time the window is opened, #initialize is called when it's safe to begin populating
1819 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
1820 *
1821 * Once this method is called, this.$ can be used to create elements within the frame.
1822 *
1823 * @chainable
1824 */
1825 OO.ui.Window.prototype.initialize = function () {
1826 // Properties
1827 this.$ = this.frame.$;
1828 this.$head = this.$( '<div>' );
1829 this.$body = this.$( '<div>' );
1830 this.$foot = this.$( '<div>' );
1831 this.$overlay = this.$( '<div>' );
1832
1833 // Initialization
1834 this.$head.addClass( 'oo-ui-window-head' );
1835 this.$body.addClass( 'oo-ui-window-body' );
1836 this.$foot.addClass( 'oo-ui-window-foot' );
1837 this.$overlay.addClass( 'oo-ui-window-overlay' );
1838 this.frame.$content
1839 .addClass( 'oo-ui-window-content' )
1840 .append( this.$head, this.$body, this.$foot, this.$overlay );
1841
1842 return this;
1843 };
1844
1845 /**
1846 * Open window.
1847 *
1848 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
1849 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
1850 *
1851 * @param {Object} [data] Window opening data
1852 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
1853 * first argument will be a promise which will be resolved when the window begins closing
1854 */
1855 OO.ui.Window.prototype.open = function ( data ) {
1856 return this.manager.openWindow( this, data );
1857 };
1858
1859 /**
1860 * Close window.
1861 *
1862 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
1863 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
1864 *
1865 * @param {Object} [data] Window closing data
1866 * @return {jQuery.Promise} Promise resolved when window is closed
1867 */
1868 OO.ui.Window.prototype.close = function ( data ) {
1869 return this.manager.closeWindow( this, data );
1870 };
1871
1872 /**
1873 * Load window.
1874 *
1875 * This is called by OO.ui.WindowManager durring window adding, and should not be called directly
1876 * by other systems.
1877 *
1878 * @return {jQuery.Promise} Promise resolved when window is loaded
1879 */
1880 OO.ui.Window.prototype.load = function () {
1881 return this.frame.load();
1882 };
1883
1884 /**
1885 * Setup window.
1886 *
1887 * This is called by OO.ui.WindowManager durring window opening, and should not be called directly
1888 * by other systems.
1889 *
1890 * @param {Object} [data] Window opening data
1891 * @return {jQuery.Promise} Promise resolved when window is setup
1892 */
1893 OO.ui.Window.prototype.setup = function ( data ) {
1894 var win = this,
1895 deferred = $.Deferred();
1896
1897 this.$element.show();
1898 this.visible = true;
1899 this.getSetupProcess( data ).execute().done( function () {
1900 win.manager.updateWindowSize( win );
1901 // Force redraw by asking the browser to measure the elements' widths
1902 win.$element.addClass( 'oo-ui-window-setup' ).width();
1903 win.frame.$content.addClass( 'oo-ui-window-content-setup' ).width();
1904 deferred.resolve();
1905 } );
1906
1907 return deferred.promise();
1908 };
1909
1910 /**
1911 * Ready window.
1912 *
1913 * This is called by OO.ui.WindowManager durring window opening, and should not be called directly
1914 * by other systems.
1915 *
1916 * @param {Object} [data] Window opening data
1917 * @return {jQuery.Promise} Promise resolved when window is ready
1918 */
1919 OO.ui.Window.prototype.ready = function ( data ) {
1920 var win = this,
1921 deferred = $.Deferred();
1922
1923 this.frame.$content.focus();
1924 this.getReadyProcess( data ).execute().done( function () {
1925 // Force redraw by asking the browser to measure the elements' widths
1926 win.$element.addClass( 'oo-ui-window-ready' ).width();
1927 win.frame.$content.addClass( 'oo-ui-window-content-ready' ).width();
1928 deferred.resolve();
1929 } );
1930
1931 return deferred.promise();
1932 };
1933
1934 /**
1935 * Hold window.
1936 *
1937 * This is called by OO.ui.WindowManager durring window closing, and should not be called directly
1938 * by other systems.
1939 *
1940 * @param {Object} [data] Window closing data
1941 * @return {jQuery.Promise} Promise resolved when window is held
1942 */
1943 OO.ui.Window.prototype.hold = function ( data ) {
1944 var win = this,
1945 deferred = $.Deferred();
1946
1947 this.getHoldProcess( data ).execute().done( function () {
1948 win.frame.$content.find( ':focus' ).blur();
1949 // Force redraw by asking the browser to measure the elements' widths
1950 win.$element.removeClass( 'oo-ui-window-ready' ).width();
1951 win.frame.$content.removeClass( 'oo-ui-window-content-ready' ).width();
1952 deferred.resolve();
1953 } );
1954
1955 return deferred.promise();
1956 };
1957
1958 /**
1959 * Teardown window.
1960 *
1961 * This is called by OO.ui.WindowManager durring window closing, and should not be called directly
1962 * by other systems.
1963 *
1964 * @param {Object} [data] Window closing data
1965 * @return {jQuery.Promise} Promise resolved when window is torn down
1966 */
1967 OO.ui.Window.prototype.teardown = function ( data ) {
1968 var win = this,
1969 deferred = $.Deferred();
1970
1971 this.getTeardownProcess( data ).execute().done( function () {
1972 // Force redraw by asking the browser to measure the elements' widths
1973 win.$element.removeClass( 'oo-ui-window-setup' ).width();
1974 win.frame.$content.removeClass( 'oo-ui-window-content-setup' ).width();
1975 win.$element.hide();
1976 win.visible = false;
1977 deferred.resolve();
1978 } );
1979
1980 return deferred.promise();
1981 };
1982
1983 /**
1984 * Base class for all dialogs.
1985 *
1986 * Logic:
1987 * - Manage the window (open and close, etc.).
1988 * - Store the internal name and display title.
1989 * - A stack to track one or more pending actions.
1990 * - Manage a set of actions that can be performed.
1991 * - Configure and create action widgets.
1992 *
1993 * User interface:
1994 * - Close the dialog with Escape key.
1995 * - Visually lock the dialog while an action is in
1996 * progress (aka "pending").
1997 *
1998 * Subclass responsibilities:
1999 * - Display the title somewhere.
2000 * - Add content to the dialog.
2001 * - Provide a UI to close the dialog.
2002 * - Display the action widgets somewhere.
2003 *
2004 * @abstract
2005 * @class
2006 * @extends OO.ui.Window
2007 * @mixins OO.ui.LabeledElement
2008 *
2009 * @constructor
2010 * @param {Object} [config] Configuration options
2011 */
2012 OO.ui.Dialog = function OoUiDialog( manager, config ) {
2013 // Parent constructor
2014 OO.ui.Dialog.super.call( this, manager, config );
2015
2016 // Properties
2017 this.actions = new OO.ui.ActionSet();
2018 this.attachedActions = [];
2019 this.currentAction = null;
2020 this.pending = 0;
2021
2022 // Events
2023 this.actions.connect( this, {
2024 'click': 'onActionClick',
2025 'resize': 'onActionResize',
2026 'change': 'onActionsChange'
2027 } );
2028
2029 // Initialization
2030 this.$element
2031 .addClass( 'oo-ui-dialog' )
2032 .attr( 'role', 'dialog' );
2033 };
2034
2035 /* Setup */
2036
2037 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2038
2039 /* Static Properties */
2040
2041 /**
2042 * Symbolic name of dialog.
2043 *
2044 * @abstract
2045 * @static
2046 * @inheritable
2047 * @property {string}
2048 */
2049 OO.ui.Dialog.static.name = '';
2050
2051 /**
2052 * Dialog title.
2053 *
2054 * @abstract
2055 * @static
2056 * @inheritable
2057 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2058 */
2059 OO.ui.Dialog.static.title = '';
2060
2061 /**
2062 * List of OO.ui.ActionWidget configuration options.
2063 *
2064 * @static
2065 * inheritable
2066 * @property {Object[]}
2067 */
2068 OO.ui.Dialog.static.actions = [];
2069
2070 /**
2071 * Close dialog when the escape key is pressed.
2072 *
2073 * @static
2074 * @abstract
2075 * @inheritable
2076 * @property {boolean}
2077 */
2078 OO.ui.Dialog.static.escapable = true;
2079
2080 /* Methods */
2081
2082 /**
2083 * Handle frame document key down events.
2084 *
2085 * @param {jQuery.Event} e Key down event
2086 */
2087 OO.ui.Dialog.prototype.onFrameDocumentKeyDown = function ( e ) {
2088 if ( e.which === OO.ui.Keys.ESCAPE ) {
2089 this.close();
2090 return false;
2091 }
2092 };
2093
2094 /**
2095 * Handle action resized events.
2096 *
2097 * @param {OO.ui.ActionWidget} action Action that was resized
2098 */
2099 OO.ui.Dialog.prototype.onActionResize = function () {
2100 // Override in subclass
2101 };
2102
2103 /**
2104 * Handle action click events.
2105 *
2106 * @param {OO.ui.ActionWidget} action Action that was clicked
2107 */
2108 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2109 if ( !this.isPending() ) {
2110 this.currentAction = action;
2111 this.executeAction( action.getAction() );
2112 }
2113 };
2114
2115 /**
2116 * Handle actions change event.
2117 */
2118 OO.ui.Dialog.prototype.onActionsChange = function () {
2119 this.detachActions();
2120 if ( !this.isClosing() ) {
2121 this.attachActions();
2122 }
2123 };
2124
2125 /**
2126 * Check if input is pending.
2127 *
2128 * @return {boolean}
2129 */
2130 OO.ui.Dialog.prototype.isPending = function () {
2131 return !!this.pending;
2132 };
2133
2134 /**
2135 * Get set of actions.
2136 *
2137 * @return {OO.ui.ActionSet}
2138 */
2139 OO.ui.Dialog.prototype.getActions = function () {
2140 return this.actions;
2141 };
2142
2143 /**
2144 * Get a process for taking action.
2145 *
2146 * When you override this method, you can add additional accept steps to the process the parent
2147 * method provides using the 'first' and 'next' methods.
2148 *
2149 * @abstract
2150 * @param {string} [action] Symbolic name of action
2151 * @return {OO.ui.Process} Action process
2152 */
2153 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2154 return new OO.ui.Process()
2155 .next( function () {
2156 if ( !action ) {
2157 // An empty action always closes the dialog without data, which should always be
2158 // safe and make no changes
2159 this.close();
2160 }
2161 }, this );
2162 };
2163
2164 /**
2165 * @inheritdoc
2166 *
2167 * @param {Object} [data] Dialog opening data
2168 * @param {jQuery|string|Function|null} [data.label] Dialog label, omit to use #static-label
2169 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2170 * action item, omit to use #static-actions
2171 */
2172 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2173 data = data || {};
2174
2175 // Parent method
2176 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2177 .next( function () {
2178 var i, len,
2179 items = [],
2180 config = this.constructor.static,
2181 actions = data.actions !== undefined ? data.actions : config.actions;
2182
2183 this.title.setLabel(
2184 data.title !== undefined ? data.title : this.constructor.static.title
2185 );
2186 for ( i = 0, len = actions.length; i < len; i++ ) {
2187 items.push(
2188 new OO.ui.ActionWidget( $.extend( { '$': this.$ }, actions[i] ) )
2189 );
2190 }
2191 this.actions.add( items );
2192 }, this );
2193 };
2194
2195 /**
2196 * @inheritdoc
2197 */
2198 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2199 // Parent method
2200 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2201 .first( function () {
2202 this.actions.clear();
2203 this.currentAction = null;
2204 }, this );
2205 };
2206
2207 /**
2208 * @inheritdoc
2209 */
2210 OO.ui.Dialog.prototype.initialize = function () {
2211 // Parent method
2212 OO.ui.Dialog.super.prototype.initialize.call( this );
2213
2214 // Properties
2215 this.title = new OO.ui.LabelWidget( { '$': this.$ } );
2216
2217 // Events
2218 if ( this.constructor.static.escapable ) {
2219 this.frame.$document.on( 'keydown', OO.ui.bind( this.onFrameDocumentKeyDown, this ) );
2220 }
2221
2222 // Initialization
2223 this.frame.$content.addClass( 'oo-ui-dialog-content' );
2224 };
2225
2226 /**
2227 * Attach action actions.
2228 */
2229 OO.ui.Dialog.prototype.attachActions = function () {
2230 // Remember the list of potentially attached actions
2231 this.attachedActions = this.actions.get();
2232 };
2233
2234 /**
2235 * Detach action actions.
2236 *
2237 * @chainable
2238 */
2239 OO.ui.Dialog.prototype.detachActions = function () {
2240 var i, len;
2241
2242 // Detach all actions that may have been previously attached
2243 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2244 this.attachedActions[i].$element.detach();
2245 }
2246 this.attachedActions = [];
2247 };
2248
2249 /**
2250 * Execute an action.
2251 *
2252 * @param {string} action Symbolic name of action to execute
2253 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2254 */
2255 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2256 this.pushPending();
2257 return this.getActionProcess( action ).execute()
2258 .always( OO.ui.bind( this.popPending, this ) );
2259 };
2260
2261 /**
2262 * Increase the pending stack.
2263 *
2264 * @chainable
2265 */
2266 OO.ui.Dialog.prototype.pushPending = function () {
2267 if ( this.pending === 0 ) {
2268 this.frame.$content.addClass( 'oo-ui-actionDialog-content-pending' );
2269 this.$head.addClass( 'oo-ui-texture-pending' );
2270 }
2271 this.pending++;
2272
2273 return this;
2274 };
2275
2276 /**
2277 * Reduce the pending stack.
2278 *
2279 * Clamped at zero.
2280 *
2281 * @chainable
2282 */
2283 OO.ui.Dialog.prototype.popPending = function () {
2284 if ( this.pending === 1 ) {
2285 this.frame.$content.removeClass( 'oo-ui-actionDialog-content-pending' );
2286 this.$head.removeClass( 'oo-ui-texture-pending' );
2287 }
2288 this.pending = Math.max( 0, this.pending - 1 );
2289
2290 return this;
2291 };
2292
2293 /**
2294 * Collection of windows.
2295 *
2296 * @class
2297 * @extends OO.ui.Element
2298 * @mixins OO.EventEmitter
2299 *
2300 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2301 * already opening or opened, the current window will be closed without data. Empty closing data
2302 * should always result in the window being closed without causing constructive or destructive
2303 * action.
2304 *
2305 * As a window is opened and closed, it passes through several stages and the manager emits several
2306 * corresponding events.
2307 *
2308 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2309 * - {@link #event-opening} is emitted with `opening` promise
2310 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2311 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2312 * - `setup` progress notification is emitted from opening promise
2313 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2314 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2315 * - `ready` progress notification is emitted from opening promise
2316 * - `opening` promise is resolved with `opened` promise
2317 * - Window is now open
2318 *
2319 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2320 * - `opened` promise is resolved with `closing` promise
2321 * - {@link #event-opening} is emitted with `closing` promise
2322 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2323 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2324 * - `hold` progress notification is emitted from opening promise
2325 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2326 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2327 * - `teardown` progress notification is emitted from opening promise
2328 * - Closing promise is resolved
2329 * - Window is now closed
2330 *
2331 * @constructor
2332 * @param {Object} [config] Configuration options
2333 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2334 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2335 */
2336 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2337 // Configuration initialization
2338 config = config || {};
2339
2340 // Parent constructor
2341 OO.ui.WindowManager.super.call( this, config );
2342
2343 // Mixin constructors
2344 OO.EventEmitter.call( this );
2345
2346 // Properties
2347 this.factory = config.factory;
2348 this.modal = config.modal === undefined || !!config.modal;
2349 this.windows = {};
2350 this.opening = null;
2351 this.opened = null;
2352 this.closing = null;
2353 this.size = null;
2354 this.currentWindow = null;
2355 this.$ariaHidden = null;
2356 this.requestedSize = null;
2357 this.onWindowResizeTimeout = null;
2358 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
2359 this.afterWindowResizeHandler = OO.ui.bind( this.afterWindowResize, this );
2360 this.onWindowMouseWheelHandler = OO.ui.bind( this.onWindowMouseWheel, this );
2361 this.onDocumentKeyDownHandler = OO.ui.bind( this.onDocumentKeyDown, this );
2362
2363 // Events
2364 this.$element.on( 'mousedown', false );
2365
2366 // Initialization
2367 this.$element
2368 .addClass( 'oo-ui-windowManager' )
2369 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2370 };
2371
2372 /* Setup */
2373
2374 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2375 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2376
2377 /* Events */
2378
2379 /**
2380 * Window is opening.
2381 *
2382 * Fired when the window begins to be opened.
2383 *
2384 * @event opening
2385 * @param {OO.ui.Window} win Window that's being opened
2386 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2387 * resolved the first argument will be a promise which will be resolved when the window begins
2388 * closing, the second argument will be the opening data; progress notifications will be fired on
2389 * the promise for `setup` and `ready` when those processes are completed respectively.
2390 * @param {Object} data Window opening data
2391 */
2392
2393 /**
2394 * Window is closing.
2395 *
2396 * Fired when the window begins to be closed.
2397 *
2398 * @event closing
2399 * @param {OO.ui.Window} win Window that's being closed
2400 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2401 * is resolved the first argument will be a the closing data; progress notifications will be fired
2402 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2403 * @param {Object} data Window closing data
2404 */
2405
2406 /* Static Properties */
2407
2408 /**
2409 * Map of symbolic size names and CSS properties.
2410 *
2411 * @static
2412 * @inheritable
2413 * @property {Object}
2414 */
2415 OO.ui.WindowManager.static.sizes = {
2416 'small': {
2417 'width': 300
2418 },
2419 'medium': {
2420 'width': 500
2421 },
2422 'large': {
2423 'width': 700
2424 },
2425 'full': {
2426 // These can be non-numeric because they are never used in calculations
2427 'width': '100%',
2428 'height': '100%'
2429 }
2430 };
2431
2432 /**
2433 * Symbolic name of default size.
2434 *
2435 * Default size is used if the window's requested size is not recognized.
2436 *
2437 * @static
2438 * @inheritable
2439 * @property {string}
2440 */
2441 OO.ui.WindowManager.static.defaultSize = 'medium';
2442
2443 /* Methods */
2444
2445 /**
2446 * Handle window resize events.
2447 *
2448 * @param {jQuery.Event} e Window resize event
2449 */
2450 OO.ui.WindowManager.prototype.onWindowResize = function () {
2451 clearTimeout( this.onWindowResizeTimeout );
2452 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2453 };
2454
2455 /**
2456 * Handle window resize events.
2457 *
2458 * @param {jQuery.Event} e Window resize event
2459 */
2460 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2461 if ( this.currentWindow ) {
2462 this.updateWindowSize( this.currentWindow );
2463 }
2464 };
2465
2466 /**
2467 * Handle window mouse wheel events.
2468 *
2469 * @param {jQuery.Event} e Mouse wheel event
2470 */
2471 OO.ui.WindowManager.prototype.onWindowMouseWheel = function () {
2472 return false;
2473 };
2474
2475 /**
2476 * Handle document key down events.
2477 *
2478 * @param {jQuery.Event} e Key down event
2479 */
2480 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2481 switch ( e.which ) {
2482 case OO.ui.Keys.PAGEUP:
2483 case OO.ui.Keys.PAGEDOWN:
2484 case OO.ui.Keys.END:
2485 case OO.ui.Keys.HOME:
2486 case OO.ui.Keys.LEFT:
2487 case OO.ui.Keys.UP:
2488 case OO.ui.Keys.RIGHT:
2489 case OO.ui.Keys.DOWN:
2490 // Prevent any key events that might cause scrolling
2491 return false;
2492 }
2493 };
2494
2495 /**
2496 * Check if window is opening.
2497 *
2498 * @return {boolean} Window is opening
2499 */
2500 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2501 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2502 };
2503
2504 /**
2505 * Check if window is closing.
2506 *
2507 * @return {boolean} Window is closing
2508 */
2509 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2510 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2511 };
2512
2513 /**
2514 * Check if window is opened.
2515 *
2516 * @return {boolean} Window is opened
2517 */
2518 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2519 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2520 };
2521
2522 /**
2523 * Check if a window is being managed.
2524 *
2525 * @param {OO.ui.Window} win Window to check
2526 * @return {boolean} Window is being managed
2527 */
2528 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2529 var name;
2530
2531 for ( name in this.windows ) {
2532 if ( this.windows[name] === win ) {
2533 return true;
2534 }
2535 }
2536
2537 return false;
2538 };
2539
2540 /**
2541 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2542 *
2543 * @param {OO.ui.Window} win Window being opened
2544 * @param {Object} [data] Window opening data
2545 * @return {number} Milliseconds to wait
2546 */
2547 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2548 return 0;
2549 };
2550
2551 /**
2552 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2553 *
2554 * @param {OO.ui.Window} win Window being opened
2555 * @param {Object} [data] Window opening data
2556 * @return {number} Milliseconds to wait
2557 */
2558 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2559 return 0;
2560 };
2561
2562 /**
2563 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2564 *
2565 * @param {OO.ui.Window} win Window being closed
2566 * @param {Object} [data] Window closing data
2567 * @return {number} Milliseconds to wait
2568 */
2569 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2570 return 0;
2571 };
2572
2573 /**
2574 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2575 *
2576 * @param {OO.ui.Window} win Window being closed
2577 * @param {Object} [data] Window closing data
2578 * @return {number} Milliseconds to wait
2579 */
2580 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2581 return this.modal ? 250 : 0;
2582 };
2583
2584 /**
2585 * Get managed window by symbolic name.
2586 *
2587 * If window is not yet instantiated, it will be instantiated and added automatically.
2588 *
2589 * @param {string} name Symbolic window name
2590 * @return {jQuery.Promise} Promise resolved when window is ready to be accessed; when resolved the
2591 * first argument is an OO.ui.Window; when rejected the first argument is an OO.ui.Error
2592 * @throws {Error} If the symbolic name is unrecognized by the factory
2593 * @throws {Error} If the symbolic name unrecognized as a managed window
2594 */
2595 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2596 var deferred = $.Deferred(),
2597 win = this.windows[name];
2598
2599 if ( !( win instanceof OO.ui.Window ) ) {
2600 if ( this.factory ) {
2601 if ( !this.factory.lookup( name ) ) {
2602 deferred.reject( new OO.ui.Error(
2603 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2604 ) );
2605 } else {
2606 win = this.factory.create( name, this, { '$': this.$ } );
2607 this.addWindows( [ win ] ).then(
2608 OO.ui.bind( deferred.resolve, deferred, win ),
2609 deferred.reject
2610 );
2611 }
2612 } else {
2613 deferred.reject( new OO.ui.Error(
2614 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2615 ) );
2616 }
2617 } else {
2618 deferred.resolve( win );
2619 }
2620
2621 return deferred.promise();
2622 };
2623
2624 /**
2625 * Get current window.
2626 *
2627 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2628 */
2629 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2630 return this.currentWindow;
2631 };
2632
2633 /**
2634 * Open a window.
2635 *
2636 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2637 * @param {Object} [data] Window opening data
2638 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2639 * for more details about the `opening` promise
2640 * @fires opening
2641 */
2642 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2643 var manager = this,
2644 preparing = [],
2645 opening = $.Deferred();
2646
2647 // Argument handling
2648 if ( typeof win === 'string' ) {
2649 return this.getWindow( win ).then( function ( win ) {
2650 return manager.openWindow( win, data );
2651 } );
2652 }
2653
2654 // Error handling
2655 if ( !this.hasWindow( win ) ) {
2656 opening.reject( new OO.ui.Error(
2657 'Cannot open window: window is not attached to manager'
2658 ) );
2659 }
2660
2661 // Window opening
2662 if ( opening.state() !== 'rejected' ) {
2663 // Begin loading the window if it's not loaded already - may take noticable time and we want
2664 // too do this in paralell with any preparatory actions
2665 preparing.push( win.load() );
2666
2667 if ( this.opening || this.opened ) {
2668 // If a window is currently opening or opened, close it first
2669 preparing.push( this.closeWindow( this.currentWindow ) );
2670 } else if ( this.closing ) {
2671 // If a window is currently closing, wait for it to complete
2672 preparing.push( this.closing );
2673 }
2674
2675 $.when.apply( $, preparing ).done( function () {
2676 if ( manager.modal ) {
2677 manager.$( manager.getElementDocument() ).on( {
2678 // Prevent scrolling by keys in top-level window
2679 'keydown': manager.onDocumentKeyDownHandler
2680 } );
2681 manager.$( manager.getElementWindow() ).on( {
2682 // Prevent scrolling by wheel in top-level window
2683 'mousewheel': manager.onWindowMouseWheelHandler,
2684 // Start listening for top-level window dimension changes
2685 'orientationchange resize': manager.onWindowResizeHandler
2686 } );
2687 // Hide other content from screen readers
2688 manager.$ariaHidden = $( 'body' )
2689 .children()
2690 .not( manager.$element.parentsUntil( 'body' ).last() )
2691 .attr( 'aria-hidden', '' );
2692 }
2693 manager.currentWindow = win;
2694 manager.opening = opening;
2695 manager.emit( 'opening', win, opening, data );
2696 manager.updateWindowSize( win );
2697 setTimeout( function () {
2698 win.setup( data ).then( function () {
2699 manager.opening.notify( { 'state': 'setup' } );
2700 setTimeout( function () {
2701 win.ready( data ).then( function () {
2702 manager.opening.notify( { 'state': 'ready' } );
2703 manager.opening = null;
2704 manager.opened = $.Deferred();
2705 opening.resolve( manager.opened.promise(), data );
2706 } );
2707 }, manager.getReadyDelay() );
2708 } );
2709 }, manager.getSetupDelay() );
2710 } );
2711 }
2712
2713 return opening;
2714 };
2715
2716 /**
2717 * Close a window.
2718 *
2719 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
2720 * @param {Object} [data] Window closing data
2721 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-closing}
2722 * for more details about the `closing` promise
2723 * @throws {Error} If no window by that name is being managed
2724 * @fires closing
2725 */
2726 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
2727 var manager = this,
2728 preparing = [],
2729 closing = $.Deferred(),
2730 opened = this.opened;
2731
2732 // Argument handling
2733 if ( typeof win === 'string' ) {
2734 win = this.windows[win];
2735 } else if ( !this.hasWindow( win ) ) {
2736 win = null;
2737 }
2738
2739 // Error handling
2740 if ( !win ) {
2741 closing.reject( new OO.ui.Error(
2742 'Cannot close window: window is not attached to manager'
2743 ) );
2744 } else if ( win !== this.currentWindow ) {
2745 closing.reject( new OO.ui.Error(
2746 'Cannot close window: window already closed with different data'
2747 ) );
2748 } else if ( this.closing ) {
2749 closing.reject( new OO.ui.Error(
2750 'Cannot close window: window already closing with different data'
2751 ) );
2752 }
2753
2754 // Window closing
2755 if ( closing.state() !== 'rejected' ) {
2756 if ( this.opening ) {
2757 // If the window is currently opening, close it when it's done
2758 preparing.push( this.opening );
2759 }
2760
2761 // Close the window
2762 $.when.apply( $, preparing ).done( function () {
2763 manager.closing = closing;
2764 manager.emit( 'closing', win, closing, data );
2765 manager.opened = null;
2766 opened.resolve( closing.promise(), data );
2767 setTimeout( function () {
2768 win.hold( data ).then( function () {
2769 closing.notify( { 'state': 'hold' } );
2770 setTimeout( function () {
2771 win.teardown( data ).then( function () {
2772 closing.notify( { 'state': 'teardown' } );
2773 if ( manager.modal ) {
2774 manager.$( manager.getElementDocument() ).off( {
2775 // Allow scrolling by keys in top-level window
2776 'keydown': manager.onDocumentKeyDownHandler
2777 } );
2778 manager.$( manager.getElementWindow() ).off( {
2779 // Allow scrolling by wheel in top-level window
2780 'mousewheel': manager.onWindowMouseWheelHandler,
2781 // Stop listening for top-level window dimension changes
2782 'orientationchange resize': manager.onWindowResizeHandler
2783 } );
2784 }
2785 // Restore screen reader visiblity
2786 if ( manager.$ariaHidden ) {
2787 manager.$ariaHidden.removeAttr( 'aria-hidden' );
2788 manager.$ariaHidden = null;
2789 }
2790 manager.closing = null;
2791 manager.currentWindow = null;
2792 closing.resolve( data );
2793 } );
2794 }, manager.getTeardownDelay() );
2795 } );
2796 }, manager.getHoldDelay() );
2797 } );
2798 }
2799
2800 return closing;
2801 };
2802
2803 /**
2804 * Add windows.
2805 *
2806 * If the window manager is attached to the DOM then windows will be automatically loaded as they
2807 * are added.
2808 *
2809 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
2810 * @return {jQuery.Promise} Promise resolved when all windows are added
2811 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
2812 * a statically configured symbolic name
2813 */
2814 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
2815 var i, len, win, name, list,
2816 promises = [];
2817
2818 if ( $.isArray( windows ) ) {
2819 // Convert to map of windows by looking up symbolic names from static configuration
2820 list = {};
2821 for ( i = 0, len = windows.length; i < len; i++ ) {
2822 name = windows[i].constructor.static.name;
2823 if ( typeof name !== 'string' ) {
2824 throw new Error( 'Cannot add window' );
2825 }
2826 list[name] = windows[i];
2827 }
2828 } else if ( $.isPlainObject( windows ) ) {
2829 list = windows;
2830 }
2831
2832 // Add windows
2833 for ( name in list ) {
2834 win = list[name];
2835 this.windows[name] = win;
2836 this.$element.append( win.$element );
2837
2838 if ( this.isElementAttached() ) {
2839 promises.push( win.load() );
2840 }
2841 }
2842
2843 return $.when.apply( $, promises );
2844 };
2845
2846 /**
2847 * Remove windows.
2848 *
2849 * Windows will be closed before they are removed.
2850 *
2851 * @param {string} name Symbolic name of window to remove
2852 * @return {jQuery.Promise} Promise resolved when window is closed and removed
2853 * @throws {Error} If windows being removed are not being managed
2854 */
2855 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
2856 var i, len, win, name,
2857 manager = this,
2858 promises = [],
2859 cleanup = function ( name, win ) {
2860 delete manager.windows[name];
2861 win.$element.detach();
2862 };
2863
2864 for ( i = 0, len = names.length; i < len; i++ ) {
2865 name = names[i];
2866 win = this.windows[name];
2867 if ( !win ) {
2868 throw new Error( 'Cannot remove window' );
2869 }
2870 promises.push( this.closeWindow( name ).then( OO.ui.bind( cleanup, null, name, win ) ) );
2871 }
2872
2873 return $.when.apply( $, promises );
2874 };
2875
2876 /**
2877 * Remove all windows.
2878 *
2879 * Windows will be closed before they are removed.
2880 *
2881 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
2882 */
2883 OO.ui.WindowManager.prototype.clearWindows = function () {
2884 return this.removeWindows( Object.keys( this.windows ) );
2885 };
2886
2887 /**
2888 * Set dialog size.
2889 *
2890 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
2891 *
2892 * @chainable
2893 */
2894 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
2895 // Bypass for non-current, and thus invisible, windows
2896 if ( win !== this.currentWindow ) {
2897 return;
2898 }
2899
2900 var viewport = OO.ui.Element.getDimensions( win.getElementWindow() ),
2901 sizes = this.constructor.static.sizes,
2902 size = win.getSize();
2903
2904 if ( !sizes[size] ) {
2905 size = this.constructor.static.defaultSize;
2906 }
2907 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[size].width ) {
2908 size = 'full';
2909 }
2910
2911 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
2912 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
2913 win.setDimensions( sizes[size] );
2914
2915 return this;
2916 };
2917
2918 /**
2919 * @abstract
2920 * @class
2921 *
2922 * @constructor
2923 * @param {string|jQuery} message Description of error
2924 * @param {Object} [config] Configuration options
2925 * @cfg {boolean} [recoverable=true] Error is recoverable
2926 */
2927 OO.ui.Error = function OoUiElement( message, config ) {
2928 // Configuration initialization
2929 config = config || {};
2930
2931 // Properties
2932 this.message = message instanceof jQuery ? message : String( message );
2933 this.recoverable = config.recoverable === undefined || !!config.recoverable;
2934 };
2935
2936 /* Setup */
2937
2938 OO.initClass( OO.ui.Error );
2939
2940 /* Methods */
2941
2942 /**
2943 * Check if error can be recovered from.
2944 *
2945 * @return {boolean} Error is recoverable
2946 */
2947 OO.ui.Error.prototype.isRecoverable = function () {
2948 return this.recoverable;
2949 };
2950
2951 /**
2952 * Get error message as DOM nodes.
2953 *
2954 * @return {jQuery} Error message in DOM nodes
2955 */
2956 OO.ui.Error.prototype.getMessage = function () {
2957 return this.message instanceof jQuery ?
2958 this.message.clone() :
2959 $( '<div>' ).text( this.message ).contents();
2960 };
2961
2962 /**
2963 * Get error message as text.
2964 *
2965 * @return {string} Error message
2966 */
2967 OO.ui.Error.prototype.getMessageText = function () {
2968 return this.message instanceof jQuery ? this.message.text() : this.message;
2969 };
2970
2971 /**
2972 * A list of functions, called in sequence.
2973 *
2974 * If a function added to a process returns boolean false the process will stop; if it returns an
2975 * object with a `promise` method the process will use the promise to either continue to the next
2976 * step when the promise is resolved or stop when the promise is rejected.
2977 *
2978 * @class
2979 *
2980 * @constructor
2981 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
2982 * call, see #createStep for more information
2983 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
2984 * or a promise
2985 * @return {Object} Step object, with `callback` and `context` properties
2986 */
2987 OO.ui.Process = function ( step, context ) {
2988 // Properties
2989 this.steps = [];
2990
2991 // Initialization
2992 if ( step !== undefined ) {
2993 this.next( step, context );
2994 }
2995 };
2996
2997 /* Setup */
2998
2999 OO.initClass( OO.ui.Process );
3000
3001 /* Methods */
3002
3003 /**
3004 * Start the process.
3005 *
3006 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3007 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3008 * process, the remaining steps will not be taken
3009 */
3010 OO.ui.Process.prototype.execute = function () {
3011 var i, len, promise;
3012
3013 /**
3014 * Continue execution.
3015 *
3016 * @ignore
3017 * @param {Array} step A function and the context it should be called in
3018 * @return {Function} Function that continues the process
3019 */
3020 function proceed( step ) {
3021 return function () {
3022 // Execute step in the correct context
3023 var deferred,
3024 result = step.callback.call( step.context );
3025
3026 if ( result === false ) {
3027 // Use rejected promise for boolean false results
3028 return $.Deferred().reject( [] ).promise();
3029 }
3030 if ( typeof result === 'number' ) {
3031 if ( result < 0 ) {
3032 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3033 }
3034 // Use a delayed promise for numbers, expecting them to be in milliseconds
3035 deferred = $.Deferred();
3036 setTimeout( deferred.resolve, result );
3037 return deferred.promise();
3038 }
3039 if ( result instanceof OO.ui.Error ) {
3040 // Use rejected promise for error
3041 return $.Deferred().reject( [ result ] ).promise();
3042 }
3043 if ( $.isArray( result ) && result.length && result[0] instanceof OO.ui.Error ) {
3044 // Use rejected promise for list of errors
3045 return $.Deferred().reject( result ).promise();
3046 }
3047 // Duck-type the object to see if it can produce a promise
3048 if ( result && $.isFunction( result.promise ) ) {
3049 // Use a promise generated from the result
3050 return result.promise();
3051 }
3052 // Use resolved promise for other results
3053 return $.Deferred().resolve().promise();
3054 };
3055 }
3056
3057 if ( this.steps.length ) {
3058 // Generate a chain reaction of promises
3059 promise = proceed( this.steps[0] )();
3060 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3061 promise = promise.then( proceed( this.steps[i] ) );
3062 }
3063 } else {
3064 promise = $.Deferred().resolve().promise();
3065 }
3066
3067 return promise;
3068 };
3069
3070 /**
3071 * Create a process step.
3072 *
3073 * @private
3074 * @param {number|jQuery.Promise|Function} step
3075 *
3076 * - Number of milliseconds to wait; or
3077 * - Promise to wait to be resolved; or
3078 * - Function to execute
3079 * - If it returns boolean false the process will stop
3080 * - If it returns an object with a `promise` method the process will use the promise to either
3081 * continue to the next step when the promise is resolved or stop when the promise is rejected
3082 * - If it returns a number, the process will wait for that number of milliseconds before
3083 * proceeding
3084 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3085 * or a promise
3086 * @return {Object} Step object, with `callback` and `context` properties
3087 */
3088 OO.ui.Process.prototype.createStep = function ( step, context ) {
3089 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3090 return {
3091 'callback': function () {
3092 return step;
3093 },
3094 'context': null
3095 };
3096 }
3097 if ( $.isFunction( step ) ) {
3098 return {
3099 'callback': step,
3100 'context': context
3101 };
3102 }
3103 throw new Error( 'Cannot create process step: number, promise or function expected' );
3104 };
3105
3106 /**
3107 * Add step to the beginning of the process.
3108 *
3109 * @inheritdoc #createStep
3110 * @return {OO.ui.Process} this
3111 * @chainable
3112 */
3113 OO.ui.Process.prototype.first = function ( step, context ) {
3114 this.steps.unshift( this.createStep( step, context ) );
3115 return this;
3116 };
3117
3118 /**
3119 * Add step to the end of the process.
3120 *
3121 * @inheritdoc #createStep
3122 * @return {OO.ui.Process} this
3123 * @chainable
3124 */
3125 OO.ui.Process.prototype.next = function ( step, context ) {
3126 this.steps.push( this.createStep( step, context ) );
3127 return this;
3128 };
3129
3130 /**
3131 * Factory for tools.
3132 *
3133 * @class
3134 * @extends OO.Factory
3135 * @constructor
3136 */
3137 OO.ui.ToolFactory = function OoUiToolFactory() {
3138 // Parent constructor
3139 OO.ui.ToolFactory.super.call( this );
3140 };
3141
3142 /* Setup */
3143
3144 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3145
3146 /* Methods */
3147
3148 /** */
3149 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3150 var i, len, included, promoted, demoted,
3151 auto = [],
3152 used = {};
3153
3154 // Collect included and not excluded tools
3155 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3156
3157 // Promotion
3158 promoted = this.extract( promote, used );
3159 demoted = this.extract( demote, used );
3160
3161 // Auto
3162 for ( i = 0, len = included.length; i < len; i++ ) {
3163 if ( !used[included[i]] ) {
3164 auto.push( included[i] );
3165 }
3166 }
3167
3168 return promoted.concat( auto ).concat( demoted );
3169 };
3170
3171 /**
3172 * Get a flat list of names from a list of names or groups.
3173 *
3174 * Tools can be specified in the following ways:
3175 *
3176 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
3177 * - All tools in a group: `{ 'group': 'group-name' }`
3178 * - All tools: `'*'`
3179 *
3180 * @private
3181 * @param {Array|string} collection List of tools
3182 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3183 * names will be added as properties
3184 * @return {string[]} List of extracted names
3185 */
3186 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3187 var i, len, item, name, tool,
3188 names = [];
3189
3190 if ( collection === '*' ) {
3191 for ( name in this.registry ) {
3192 tool = this.registry[name];
3193 if (
3194 // Only add tools by group name when auto-add is enabled
3195 tool.static.autoAddToCatchall &&
3196 // Exclude already used tools
3197 ( !used || !used[name] )
3198 ) {
3199 names.push( name );
3200 if ( used ) {
3201 used[name] = true;
3202 }
3203 }
3204 }
3205 } else if ( $.isArray( collection ) ) {
3206 for ( i = 0, len = collection.length; i < len; i++ ) {
3207 item = collection[i];
3208 // Allow plain strings as shorthand for named tools
3209 if ( typeof item === 'string' ) {
3210 item = { 'name': item };
3211 }
3212 if ( OO.isPlainObject( item ) ) {
3213 if ( item.group ) {
3214 for ( name in this.registry ) {
3215 tool = this.registry[name];
3216 if (
3217 // Include tools with matching group
3218 tool.static.group === item.group &&
3219 // Only add tools by group name when auto-add is enabled
3220 tool.static.autoAddToGroup &&
3221 // Exclude already used tools
3222 ( !used || !used[name] )
3223 ) {
3224 names.push( name );
3225 if ( used ) {
3226 used[name] = true;
3227 }
3228 }
3229 }
3230 // Include tools with matching name and exclude already used tools
3231 } else if ( item.name && ( !used || !used[item.name] ) ) {
3232 names.push( item.name );
3233 if ( used ) {
3234 used[item.name] = true;
3235 }
3236 }
3237 }
3238 }
3239 }
3240 return names;
3241 };
3242
3243 /**
3244 * Factory for tool groups.
3245 *
3246 * @class
3247 * @extends OO.Factory
3248 * @constructor
3249 */
3250 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3251 // Parent constructor
3252 OO.Factory.call( this );
3253
3254 var i, l,
3255 defaultClasses = this.constructor.static.getDefaultClasses();
3256
3257 // Register default toolgroups
3258 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3259 this.register( defaultClasses[i] );
3260 }
3261 };
3262
3263 /* Setup */
3264
3265 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3266
3267 /* Static Methods */
3268
3269 /**
3270 * Get a default set of classes to be registered on construction
3271 *
3272 * @return {Function[]} Default classes
3273 */
3274 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3275 return [
3276 OO.ui.BarToolGroup,
3277 OO.ui.ListToolGroup,
3278 OO.ui.MenuToolGroup
3279 ];
3280 };
3281
3282 /**
3283 * Element with a button.
3284 *
3285 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3286 * and access keys for accessibility purposes.
3287 *
3288 * @abstract
3289 * @class
3290 *
3291 * @constructor
3292 * @param {jQuery} $button Button node, assigned to #$button
3293 * @param {Object} [config] Configuration options
3294 * @cfg {boolean} [framed=true] Render button with a frame
3295 * @cfg {number} [tabIndex=0] Button's tab index, use null to have no tabIndex
3296 * @cfg {string} [accessKey] Button's access key
3297 */
3298 OO.ui.ButtonedElement = function OoUiButtonedElement( $button, config ) {
3299 // Configuration initialization
3300 config = config || {};
3301
3302 // Properties
3303 this.$button = $button;
3304 this.tabIndex = null;
3305 this.framed = null;
3306 this.active = false;
3307 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
3308
3309 // Events
3310 this.$button.on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
3311
3312 // Initialization
3313 this.$element.addClass( 'oo-ui-buttonedElement' );
3314 this.$button
3315 .addClass( 'oo-ui-buttonedElement-button' )
3316 .attr( 'role', 'button' );
3317 this.setTabIndex( config.tabIndex || 0 );
3318 this.setAccessKey( config.accessKey );
3319 this.toggleFramed( config.framed === undefined || config.framed );
3320 };
3321
3322 /* Setup */
3323
3324 OO.initClass( OO.ui.ButtonedElement );
3325
3326 /* Static Properties */
3327
3328 /**
3329 * Cancel mouse down events.
3330 *
3331 * @static
3332 * @inheritable
3333 * @property {boolean}
3334 */
3335 OO.ui.ButtonedElement.static.cancelButtonMouseDownEvents = true;
3336
3337 /* Methods */
3338
3339 /**
3340 * Handles mouse down events.
3341 *
3342 * @param {jQuery.Event} e Mouse down event
3343 */
3344 OO.ui.ButtonedElement.prototype.onMouseDown = function ( e ) {
3345 if ( this.isDisabled() || e.which !== 1 ) {
3346 return false;
3347 }
3348 // tabIndex should generally be interacted with via the property, but it's not possible to
3349 // reliably unset a tabIndex via a property so we use the (lowercase) "tabindex" attribute
3350 this.tabIndex = this.$button.attr( 'tabindex' );
3351 this.$button
3352 // Remove the tab-index while the button is down to prevent the button from stealing focus
3353 .removeAttr( 'tabindex' )
3354 .addClass( 'oo-ui-buttonedElement-pressed' );
3355 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3356 // reliably reapply the tabindex and remove the pressed class
3357 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3358 // Prevent change of focus unless specifically configured otherwise
3359 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3360 return false;
3361 }
3362 };
3363
3364 /**
3365 * Handles mouse up events.
3366 *
3367 * @param {jQuery.Event} e Mouse up event
3368 */
3369 OO.ui.ButtonedElement.prototype.onMouseUp = function ( e ) {
3370 if ( this.isDisabled() || e.which !== 1 ) {
3371 return false;
3372 }
3373 this.$button
3374 // Restore the tab-index after the button is up to restore the button's accesssibility
3375 .attr( 'tabindex', this.tabIndex )
3376 .removeClass( 'oo-ui-buttonedElement-pressed' );
3377 // Stop listening for mouseup, since we only needed this once
3378 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3379 };
3380
3381 /**
3382 * Toggle frame.
3383 *
3384 * @param {boolean} [framed] Make button framed, omit to toggle
3385 * @chainable
3386 */
3387 OO.ui.ButtonedElement.prototype.toggleFramed = function ( framed ) {
3388 framed = framed === undefined ? !this.framed : !!framed;
3389 if ( framed !== this.framed ) {
3390 this.framed = framed;
3391 this.$element
3392 .toggleClass( 'oo-ui-buttonedElement-frameless', !framed )
3393 .toggleClass( 'oo-ui-buttonedElement-framed', framed );
3394 }
3395
3396 return this;
3397 };
3398
3399 /**
3400 * Set tab index.
3401 *
3402 * @param {number|null} tabIndex Button's tab index, use null to remove
3403 * @chainable
3404 */
3405 OO.ui.ButtonedElement.prototype.setTabIndex = function ( tabIndex ) {
3406 if ( typeof tabIndex === 'number' && tabIndex >= 0 ) {
3407 this.$button.attr( 'tabindex', tabIndex );
3408 } else {
3409 this.$button.removeAttr( 'tabindex' );
3410 }
3411 return this;
3412 };
3413
3414 /**
3415 * Set access key
3416 *
3417 * @param {string} accessKey Button's access key, use empty string to remove
3418 * @chainable
3419 */
3420 OO.ui.ButtonedElement.prototype.setAccessKey = function ( accessKey ) {
3421 if ( typeof accessKey === 'string' && accessKey.length ) {
3422 this.$button.attr( 'accesskey', accessKey );
3423 } else {
3424 this.$button.removeAttr( 'accesskey' );
3425 }
3426 return this;
3427 };
3428
3429 /**
3430 * Set active state.
3431 *
3432 * @param {boolean} [value] Make button active
3433 * @chainable
3434 */
3435 OO.ui.ButtonedElement.prototype.setActive = function ( value ) {
3436 this.$button.toggleClass( 'oo-ui-buttonedElement-active', !!value );
3437 return this;
3438 };
3439
3440 /**
3441 * Element that can be automatically clipped to visible boundaies.
3442 *
3443 * @abstract
3444 * @class
3445 *
3446 * @constructor
3447 * @param {jQuery} $clippable Nodes to clip, assigned to #$clippable
3448 * @param {Object} [config] Configuration options
3449 */
3450 OO.ui.ClippableElement = function OoUiClippableElement( $clippable, config ) {
3451 // Configuration initialization
3452 config = config || {};
3453
3454 // Properties
3455 this.$clippable = $clippable;
3456 this.clipping = false;
3457 this.clipped = false;
3458 this.$clippableContainer = null;
3459 this.$clippableScroller = null;
3460 this.$clippableWindow = null;
3461 this.idealWidth = null;
3462 this.idealHeight = null;
3463 this.onClippableContainerScrollHandler = OO.ui.bind( this.clip, this );
3464 this.onClippableWindowResizeHandler = OO.ui.bind( this.clip, this );
3465
3466 // Initialization
3467 this.$clippable.addClass( 'oo-ui-clippableElement-clippable' );
3468 };
3469
3470 /* Methods */
3471
3472 /**
3473 * Set clipping.
3474 *
3475 * @param {boolean} value Enable clipping
3476 * @chainable
3477 */
3478 OO.ui.ClippableElement.prototype.setClipping = function ( value ) {
3479 value = !!value;
3480
3481 if ( this.clipping !== value ) {
3482 this.clipping = value;
3483 if ( this.clipping ) {
3484 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
3485 // If the clippable container is the body, we have to listen to scroll events and check
3486 // jQuery.scrollTop on the window because of browser inconsistencies
3487 this.$clippableScroller = this.$clippableContainer.is( 'body' ) ?
3488 this.$( OO.ui.Element.getWindow( this.$clippableContainer ) ) :
3489 this.$clippableContainer;
3490 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
3491 this.$clippableWindow = this.$( this.getElementWindow() )
3492 .on( 'resize', this.onClippableWindowResizeHandler );
3493 // Initial clip after visible
3494 setTimeout( OO.ui.bind( this.clip, this ) );
3495 } else {
3496 this.$clippableContainer = null;
3497 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
3498 this.$clippableScroller = null;
3499 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
3500 this.$clippableWindow = null;
3501 }
3502 }
3503
3504 return this;
3505 };
3506
3507 /**
3508 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
3509 *
3510 * @return {boolean} Element will be clipped to the visible area
3511 */
3512 OO.ui.ClippableElement.prototype.isClipping = function () {
3513 return this.clipping;
3514 };
3515
3516 /**
3517 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
3518 *
3519 * @return {boolean} Part of the element is being clipped
3520 */
3521 OO.ui.ClippableElement.prototype.isClipped = function () {
3522 return this.clipped;
3523 };
3524
3525 /**
3526 * Set the ideal size.
3527 *
3528 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
3529 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
3530 */
3531 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
3532 this.idealWidth = width;
3533 this.idealHeight = height;
3534 };
3535
3536 /**
3537 * Clip element to visible boundaries and allow scrolling when needed.
3538 *
3539 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
3540 * overlapped by, the visible area of the nearest scrollable container.
3541 *
3542 * @chainable
3543 */
3544 OO.ui.ClippableElement.prototype.clip = function () {
3545 if ( !this.clipping ) {
3546 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
3547 return this;
3548 }
3549
3550 var buffer = 10,
3551 cOffset = this.$clippable.offset(),
3552 ccOffset = this.$clippableContainer.offset() || { 'top': 0, 'left': 0 },
3553 ccHeight = this.$clippableContainer.innerHeight() - buffer,
3554 ccWidth = this.$clippableContainer.innerWidth() - buffer,
3555 scrollTop = this.$clippableScroller.scrollTop(),
3556 scrollLeft = this.$clippableScroller.scrollLeft(),
3557 desiredWidth = ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
3558 desiredHeight = ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
3559 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
3560 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
3561 clipWidth = desiredWidth < naturalWidth,
3562 clipHeight = desiredHeight < naturalHeight;
3563
3564 if ( clipWidth ) {
3565 this.$clippable.css( { 'overflow-x': 'auto', 'width': desiredWidth } );
3566 } else {
3567 this.$clippable.css( 'width', this.idealWidth || '' );
3568 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
3569 this.$clippable.css( 'overflow-x', '' );
3570 }
3571 if ( clipHeight ) {
3572 this.$clippable.css( { 'overflow-y': 'auto', 'height': desiredHeight } );
3573 } else {
3574 this.$clippable.css( 'height', this.idealHeight || '' );
3575 this.$clippable.height(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
3576 this.$clippable.css( 'overflow-y', '' );
3577 }
3578
3579 this.clipped = clipWidth || clipHeight;
3580
3581 return this;
3582 };
3583
3584 /**
3585 * Element with named flags that can be added, removed, listed and checked.
3586 *
3587 * A flag, when set, adds a CSS class on the `$element` by combing `oo-ui-flaggableElement-` with
3588 * the flag name. Flags are primarily useful for styling.
3589 *
3590 * @abstract
3591 * @class
3592 *
3593 * @constructor
3594 * @param {Object} [config] Configuration options
3595 * @cfg {string[]} [flags=[]] Styling flags, e.g. 'primary', 'destructive' or 'constructive'
3596 */
3597 OO.ui.FlaggableElement = function OoUiFlaggableElement( config ) {
3598 // Config initialization
3599 config = config || {};
3600
3601 // Properties
3602 this.flags = {};
3603
3604 // Initialization
3605 this.setFlags( config.flags );
3606 };
3607
3608 /* Events */
3609
3610 /**
3611 * @event flag
3612 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
3613 * added/removed properties
3614 */
3615
3616 /* Methods */
3617
3618 /**
3619 * Check if a flag is set.
3620 *
3621 * @param {string} flag Name of flag
3622 * @return {boolean} Has flag
3623 */
3624 OO.ui.FlaggableElement.prototype.hasFlag = function ( flag ) {
3625 return flag in this.flags;
3626 };
3627
3628 /**
3629 * Get the names of all flags set.
3630 *
3631 * @return {string[]} flags Flag names
3632 */
3633 OO.ui.FlaggableElement.prototype.getFlags = function () {
3634 return Object.keys( this.flags );
3635 };
3636
3637 /**
3638 * Clear all flags.
3639 *
3640 * @chainable
3641 * @fires flag
3642 */
3643 OO.ui.FlaggableElement.prototype.clearFlags = function () {
3644 var flag,
3645 changes = {},
3646 classPrefix = 'oo-ui-flaggableElement-';
3647
3648 for ( flag in this.flags ) {
3649 changes[flag] = false;
3650 delete this.flags[flag];
3651 this.$element.removeClass( classPrefix + flag );
3652 }
3653
3654 this.emit( 'flag', changes );
3655
3656 return this;
3657 };
3658
3659 /**
3660 * Add one or more flags.
3661 *
3662 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
3663 * keyed by flag name containing boolean set/remove instructions.
3664 * @chainable
3665 * @fires flag
3666 */
3667 OO.ui.FlaggableElement.prototype.setFlags = function ( flags ) {
3668 var i, len, flag,
3669 changes = {},
3670 classPrefix = 'oo-ui-flaggableElement-';
3671
3672 if ( typeof flags === 'string' ) {
3673 // Set
3674 this.flags[flags] = true;
3675 this.$element.addClass( classPrefix + flags );
3676 } else if ( $.isArray( flags ) ) {
3677 for ( i = 0, len = flags.length; i < len; i++ ) {
3678 flag = flags[i];
3679 // Set
3680 changes[flag] = true;
3681 this.flags[flag] = true;
3682 this.$element.addClass( classPrefix + flag );
3683 }
3684 } else if ( OO.isPlainObject( flags ) ) {
3685 for ( flag in flags ) {
3686 if ( flags[flag] ) {
3687 // Set
3688 changes[flag] = true;
3689 this.flags[flag] = true;
3690 this.$element.addClass( classPrefix + flag );
3691 } else {
3692 // Remove
3693 changes[flag] = false;
3694 delete this.flags[flag];
3695 this.$element.removeClass( classPrefix + flag );
3696 }
3697 }
3698 }
3699
3700 this.emit( 'flag', changes );
3701
3702 return this;
3703 };
3704
3705 /**
3706 * Element containing a sequence of child elements.
3707 *
3708 * @abstract
3709 * @class
3710 *
3711 * @constructor
3712 * @param {jQuery} $group Container node, assigned to #$group
3713 * @param {Object} [config] Configuration options
3714 */
3715 OO.ui.GroupElement = function OoUiGroupElement( $group, config ) {
3716 // Configuration
3717 config = config || {};
3718
3719 // Properties
3720 this.$group = $group;
3721 this.items = [];
3722 this.aggregateItemEvents = {};
3723 };
3724
3725 /* Methods */
3726
3727 /**
3728 * Get items.
3729 *
3730 * @return {OO.ui.Element[]} Items
3731 */
3732 OO.ui.GroupElement.prototype.getItems = function () {
3733 return this.items.slice( 0 );
3734 };
3735
3736 /**
3737 * Add an aggregate item event.
3738 *
3739 * Aggregated events are listened to on each item and then emitted by the group under a new name,
3740 * and with an additional leading parameter containing the item that emitted the original event.
3741 * Other arguments that were emitted from the original event are passed through.
3742 *
3743 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
3744 * event, use null value to remove aggregation
3745 * @throws {Error} If aggregation already exists
3746 */
3747 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
3748 var i, len, item, add, remove, itemEvent, groupEvent;
3749
3750 for ( itemEvent in events ) {
3751 groupEvent = events[itemEvent];
3752
3753 // Remove existing aggregated event
3754 if ( itemEvent in this.aggregateItemEvents ) {
3755 // Don't allow duplicate aggregations
3756 if ( groupEvent ) {
3757 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
3758 }
3759 // Remove event aggregation from existing items
3760 for ( i = 0, len = this.items.length; i < len; i++ ) {
3761 item = this.items[i];
3762 if ( item.connect && item.disconnect ) {
3763 remove = {};
3764 remove[itemEvent] = [ 'emit', groupEvent, item ];
3765 item.disconnect( this, remove );
3766 }
3767 }
3768 // Prevent future items from aggregating event
3769 delete this.aggregateItemEvents[itemEvent];
3770 }
3771
3772 // Add new aggregate event
3773 if ( groupEvent ) {
3774 // Make future items aggregate event
3775 this.aggregateItemEvents[itemEvent] = groupEvent;
3776 // Add event aggregation to existing items
3777 for ( i = 0, len = this.items.length; i < len; i++ ) {
3778 item = this.items[i];
3779 if ( item.connect && item.disconnect ) {
3780 add = {};
3781 add[itemEvent] = [ 'emit', groupEvent, item ];
3782 item.connect( this, add );
3783 }
3784 }
3785 }
3786 }
3787 };
3788
3789 /**
3790 * Add items.
3791 *
3792 * @param {OO.ui.Element[]} items Item
3793 * @param {number} [index] Index to insert items at
3794 * @chainable
3795 */
3796 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
3797 var i, len, item, event, events, currentIndex,
3798 itemElements = [];
3799
3800 for ( i = 0, len = items.length; i < len; i++ ) {
3801 item = items[i];
3802
3803 // Check if item exists then remove it first, effectively "moving" it
3804 currentIndex = $.inArray( item, this.items );
3805 if ( currentIndex >= 0 ) {
3806 this.removeItems( [ item ] );
3807 // Adjust index to compensate for removal
3808 if ( currentIndex < index ) {
3809 index--;
3810 }
3811 }
3812 // Add the item
3813 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
3814 events = {};
3815 for ( event in this.aggregateItemEvents ) {
3816 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
3817 }
3818 item.connect( this, events );
3819 }
3820 item.setElementGroup( this );
3821 itemElements.push( item.$element.get( 0 ) );
3822 }
3823
3824 if ( index === undefined || index < 0 || index >= this.items.length ) {
3825 this.$group.append( itemElements );
3826 this.items.push.apply( this.items, items );
3827 } else if ( index === 0 ) {
3828 this.$group.prepend( itemElements );
3829 this.items.unshift.apply( this.items, items );
3830 } else {
3831 this.items[index].$element.before( itemElements );
3832 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
3833 }
3834
3835 return this;
3836 };
3837
3838 /**
3839 * Remove items.
3840 *
3841 * Items will be detached, not removed, so they can be used later.
3842 *
3843 * @param {OO.ui.Element[]} items Items to remove
3844 * @chainable
3845 */
3846 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
3847 var i, len, item, index, remove, itemEvent;
3848
3849 // Remove specific items
3850 for ( i = 0, len = items.length; i < len; i++ ) {
3851 item = items[i];
3852 index = $.inArray( item, this.items );
3853 if ( index !== -1 ) {
3854 if (
3855 item.connect && item.disconnect &&
3856 !$.isEmptyObject( this.aggregateItemEvents )
3857 ) {
3858 remove = {};
3859 if ( itemEvent in this.aggregateItemEvents ) {
3860 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
3861 }
3862 item.disconnect( this, remove );
3863 }
3864 item.setElementGroup( null );
3865 this.items.splice( index, 1 );
3866 item.$element.detach();
3867 }
3868 }
3869
3870 return this;
3871 };
3872
3873 /**
3874 * Clear all items.
3875 *
3876 * Items will be detached, not removed, so they can be used later.
3877 *
3878 * @chainable
3879 */
3880 OO.ui.GroupElement.prototype.clearItems = function () {
3881 var i, len, item, remove, itemEvent;
3882
3883 // Remove all items
3884 for ( i = 0, len = this.items.length; i < len; i++ ) {
3885 item = this.items[i];
3886 if (
3887 item.connect && item.disconnect &&
3888 !$.isEmptyObject( this.aggregateItemEvents )
3889 ) {
3890 remove = {};
3891 if ( itemEvent in this.aggregateItemEvents ) {
3892 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
3893 }
3894 item.disconnect( this, remove );
3895 }
3896 item.setElementGroup( null );
3897 item.$element.detach();
3898 }
3899
3900 this.items = [];
3901 return this;
3902 };
3903
3904 /**
3905 * Element containing an icon.
3906 *
3907 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
3908 * a control or convey information in a more space efficient way. Icons should rarely be used
3909 * without labels; such as in a toolbar where space is at a premium or within a context where the
3910 * meaning is very clear to the user.
3911 *
3912 * @abstract
3913 * @class
3914 *
3915 * @constructor
3916 * @param {jQuery} $icon Icon node, assigned to #$icon
3917 * @param {Object} [config] Configuration options
3918 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
3919 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3920 * language
3921 */
3922 OO.ui.IconedElement = function OoUiIconedElement( $icon, config ) {
3923 // Config intialization
3924 config = config || {};
3925
3926 // Properties
3927 this.$icon = $icon;
3928 this.icon = null;
3929
3930 // Initialization
3931 this.$icon.addClass( 'oo-ui-iconedElement-icon' );
3932 this.setIcon( config.icon || this.constructor.static.icon );
3933 };
3934
3935 /* Setup */
3936
3937 OO.initClass( OO.ui.IconedElement );
3938
3939 /* Static Properties */
3940
3941 /**
3942 * Icon.
3943 *
3944 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
3945 *
3946 * For i18n purposes, this property can be an object containing a `default` icon name property and
3947 * additional icon names keyed by language code.
3948 *
3949 * Example of i18n icon definition:
3950 * { 'default': 'bold-a', 'en': 'bold-b', 'de': 'bold-f' }
3951 *
3952 * @static
3953 * @inheritable
3954 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
3955 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3956 * language
3957 */
3958 OO.ui.IconedElement.static.icon = null;
3959
3960 /* Methods */
3961
3962 /**
3963 * Set icon.
3964 *
3965 * @param {Object|string} icon Symbolic icon name, or map of icon names keyed by language ID;
3966 * use the 'default' key to specify the icon to be used when there is no icon in the user's
3967 * language
3968 * @chainable
3969 */
3970 OO.ui.IconedElement.prototype.setIcon = function ( icon ) {
3971 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
3972
3973 if ( this.icon ) {
3974 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
3975 }
3976 if ( typeof icon === 'string' ) {
3977 icon = icon.trim();
3978 if ( icon.length ) {
3979 this.$icon.addClass( 'oo-ui-icon-' + icon );
3980 this.icon = icon;
3981 }
3982 }
3983 this.$element.toggleClass( 'oo-ui-iconedElement', !!this.icon );
3984
3985 return this;
3986 };
3987
3988 /**
3989 * Get icon.
3990 *
3991 * @return {string} Icon
3992 */
3993 OO.ui.IconedElement.prototype.getIcon = function () {
3994 return this.icon;
3995 };
3996
3997 /**
3998 * Element containing an indicator.
3999 *
4000 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4001 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4002 * instead of performing an action directly, or an item in a list which has errors that need to be
4003 * resolved.
4004 *
4005 * @abstract
4006 * @class
4007 *
4008 * @constructor
4009 * @param {jQuery} $indicator Indicator node, assigned to #$indicator
4010 * @param {Object} [config] Configuration options
4011 * @cfg {string} [indicator] Symbolic indicator name
4012 * @cfg {string} [indicatorTitle] Indicator title text or a function that return text
4013 */
4014 OO.ui.IndicatedElement = function OoUiIndicatedElement( $indicator, config ) {
4015 // Config intialization
4016 config = config || {};
4017
4018 // Properties
4019 this.$indicator = $indicator;
4020 this.indicator = null;
4021 this.indicatorLabel = null;
4022
4023 // Initialization
4024 this.$indicator.addClass( 'oo-ui-indicatedElement-indicator' );
4025 this.setIndicator( config.indicator || this.constructor.static.indicator );
4026 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4027 };
4028
4029 /* Setup */
4030
4031 OO.initClass( OO.ui.IndicatedElement );
4032
4033 /* Static Properties */
4034
4035 /**
4036 * indicator.
4037 *
4038 * @static
4039 * @inheritable
4040 * @property {string|null} Symbolic indicator name or null for no indicator
4041 */
4042 OO.ui.IndicatedElement.static.indicator = null;
4043
4044 /**
4045 * Indicator title.
4046 *
4047 * @static
4048 * @inheritable
4049 * @property {string|Function|null} Indicator title text, a function that return text or null for no
4050 * indicator title
4051 */
4052 OO.ui.IndicatedElement.static.indicatorTitle = null;
4053
4054 /* Methods */
4055
4056 /**
4057 * Set indicator.
4058 *
4059 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4060 * @chainable
4061 */
4062 OO.ui.IndicatedElement.prototype.setIndicator = function ( indicator ) {
4063 if ( this.indicator ) {
4064 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4065 this.indicator = null;
4066 }
4067 if ( typeof indicator === 'string' ) {
4068 indicator = indicator.trim();
4069 if ( indicator.length ) {
4070 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4071 this.indicator = indicator;
4072 }
4073 }
4074 this.$element.toggleClass( 'oo-ui-indicatedElement', !!this.indicator );
4075
4076 return this;
4077 };
4078
4079 /**
4080 * Set indicator label.
4081 *
4082 * @param {string|Function|null} indicator Indicator title text, a function that return text or null
4083 * for no indicator title
4084 * @chainable
4085 */
4086 OO.ui.IndicatedElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4087 this.indicatorTitle = indicatorTitle = OO.ui.resolveMsg( indicatorTitle );
4088
4089 if ( typeof indicatorTitle === 'string' && indicatorTitle.length ) {
4090 this.$indicator.attr( 'title', indicatorTitle );
4091 } else {
4092 this.$indicator.removeAttr( 'title' );
4093 }
4094
4095 return this;
4096 };
4097
4098 /**
4099 * Get indicator.
4100 *
4101 * @return {string} title Symbolic name of indicator
4102 */
4103 OO.ui.IndicatedElement.prototype.getIndicator = function () {
4104 return this.indicator;
4105 };
4106
4107 /**
4108 * Get indicator title.
4109 *
4110 * @return {string} Indicator title text
4111 */
4112 OO.ui.IndicatedElement.prototype.getIndicatorTitle = function () {
4113 return this.indicatorTitle;
4114 };
4115
4116 /**
4117 * Element containing a label.
4118 *
4119 * @abstract
4120 * @class
4121 *
4122 * @constructor
4123 * @param {jQuery} $label Label node, assigned to #$label
4124 * @param {Object} [config] Configuration options
4125 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4126 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4127 */
4128 OO.ui.LabeledElement = function OoUiLabeledElement( $label, config ) {
4129 // Config intialization
4130 config = config || {};
4131
4132 // Properties
4133 this.$label = $label;
4134 this.label = null;
4135
4136 // Initialization
4137 this.$label.addClass( 'oo-ui-labeledElement-label' );
4138 this.setLabel( config.label || this.constructor.static.label );
4139 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4140 };
4141
4142 /* Setup */
4143
4144 OO.initClass( OO.ui.LabeledElement );
4145
4146 /* Static Properties */
4147
4148 /**
4149 * Label.
4150 *
4151 * @static
4152 * @inheritable
4153 * @property {string|Function|null} Label text; a function that returns a nodes or text; or null for
4154 * no label
4155 */
4156 OO.ui.LabeledElement.static.label = null;
4157
4158 /* Methods */
4159
4160 /**
4161 * Set the label.
4162 *
4163 * An empty string will result in the label being hidden. A string containing only whitespace will
4164 * be converted to a single &nbsp;
4165 *
4166 * @param {jQuery|string|Function|null} label Label nodes; text; a function that retuns nodes or
4167 * text; or null for no label
4168 * @chainable
4169 */
4170 OO.ui.LabeledElement.prototype.setLabel = function ( label ) {
4171 var empty = false;
4172
4173 this.label = label = OO.ui.resolveMsg( label ) || null;
4174 if ( typeof label === 'string' && label.length ) {
4175 if ( label.match( /^\s*$/ ) ) {
4176 // Convert whitespace only string to a single non-breaking space
4177 this.$label.html( '&nbsp;' );
4178 } else {
4179 this.$label.text( label );
4180 }
4181 } else if ( label instanceof jQuery ) {
4182 this.$label.empty().append( label );
4183 } else {
4184 this.$label.empty();
4185 empty = true;
4186 }
4187 this.$element.toggleClass( 'oo-ui-labeledElement', !empty );
4188 this.$label.css( 'display', empty ? 'none' : '' );
4189
4190 return this;
4191 };
4192
4193 /**
4194 * Get the label.
4195 *
4196 * @return {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4197 * text; or null for no label
4198 */
4199 OO.ui.LabeledElement.prototype.getLabel = function () {
4200 return this.label;
4201 };
4202
4203 /**
4204 * Fit the label.
4205 *
4206 * @chainable
4207 */
4208 OO.ui.LabeledElement.prototype.fitLabel = function () {
4209 if ( this.$label.autoEllipsis && this.autoFitLabel ) {
4210 this.$label.autoEllipsis( { 'hasSpan': false, 'tooltip': true } );
4211 }
4212 return this;
4213 };
4214
4215 /**
4216 * Element containing an OO.ui.PopupWidget object.
4217 *
4218 * @abstract
4219 * @class
4220 *
4221 * @constructor
4222 * @param {Object} [config] Configuration options
4223 * @cfg {Object} [popup] Configuration to pass to popup
4224 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
4225 */
4226 OO.ui.PopuppableElement = function OoUiPopuppableElement( config ) {
4227 // Configuration initialization
4228 config = config || {};
4229
4230 // Properties
4231 this.popup = new OO.ui.PopupWidget( $.extend(
4232 { 'autoClose': true },
4233 config.popup,
4234 { '$': this.$, '$autoCloseIgnore': this.$element }
4235 ) );
4236 };
4237
4238 /* Methods */
4239
4240 /**
4241 * Get popup.
4242 *
4243 * @return {OO.ui.PopupWidget} Popup widget
4244 */
4245 OO.ui.PopuppableElement.prototype.getPopup = function () {
4246 return this.popup;
4247 };
4248
4249 /**
4250 * Element with a title.
4251 *
4252 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
4253 * not visible on touch devices.
4254 *
4255 * @abstract
4256 * @class
4257 *
4258 * @constructor
4259 * @param {jQuery} $label Titled node, assigned to #$titled
4260 * @param {Object} [config] Configuration options
4261 * @cfg {string|Function} [title] Title text or a function that returns text
4262 */
4263 OO.ui.TitledElement = function OoUiTitledElement( $titled, config ) {
4264 // Config intialization
4265 config = config || {};
4266
4267 // Properties
4268 this.$titled = $titled;
4269 this.title = null;
4270
4271 // Initialization
4272 this.setTitle( config.title || this.constructor.static.title );
4273 };
4274
4275 /* Setup */
4276
4277 OO.initClass( OO.ui.TitledElement );
4278
4279 /* Static Properties */
4280
4281 /**
4282 * Title.
4283 *
4284 * @static
4285 * @inheritable
4286 * @property {string|Function} Title text or a function that returns text
4287 */
4288 OO.ui.TitledElement.static.title = null;
4289
4290 /* Methods */
4291
4292 /**
4293 * Set title.
4294 *
4295 * @param {string|Function|null} title Title text, a function that returns text or null for no title
4296 * @chainable
4297 */
4298 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
4299 this.title = title = OO.ui.resolveMsg( title ) || null;
4300
4301 if ( typeof title === 'string' && title.length ) {
4302 this.$titled.attr( 'title', title );
4303 } else {
4304 this.$titled.removeAttr( 'title' );
4305 }
4306
4307 return this;
4308 };
4309
4310 /**
4311 * Get title.
4312 *
4313 * @return {string} Title string
4314 */
4315 OO.ui.TitledElement.prototype.getTitle = function () {
4316 return this.title;
4317 };
4318
4319 /**
4320 * Generic toolbar tool.
4321 *
4322 * @abstract
4323 * @class
4324 * @extends OO.ui.Widget
4325 * @mixins OO.ui.IconedElement
4326 *
4327 * @constructor
4328 * @param {OO.ui.ToolGroup} toolGroup
4329 * @param {Object} [config] Configuration options
4330 * @cfg {string|Function} [title] Title text or a function that returns text
4331 */
4332 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
4333 // Config intialization
4334 config = config || {};
4335
4336 // Parent constructor
4337 OO.ui.Tool.super.call( this, config );
4338
4339 // Mixin constructors
4340 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
4341
4342 // Properties
4343 this.toolGroup = toolGroup;
4344 this.toolbar = this.toolGroup.getToolbar();
4345 this.active = false;
4346 this.$title = this.$( '<span>' );
4347 this.$link = this.$( '<a>' );
4348 this.title = null;
4349
4350 // Events
4351 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
4352
4353 // Initialization
4354 this.$title.addClass( 'oo-ui-tool-title' );
4355 this.$link
4356 .addClass( 'oo-ui-tool-link' )
4357 .append( this.$icon, this.$title )
4358 .prop( 'tabIndex', 0 )
4359 .attr( 'role', 'button' );
4360 this.$element
4361 .data( 'oo-ui-tool', this )
4362 .addClass(
4363 'oo-ui-tool ' + 'oo-ui-tool-name-' +
4364 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
4365 )
4366 .append( this.$link );
4367 this.setTitle( config.title || this.constructor.static.title );
4368 };
4369
4370 /* Setup */
4371
4372 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
4373 OO.mixinClass( OO.ui.Tool, OO.ui.IconedElement );
4374
4375 /* Events */
4376
4377 /**
4378 * @event select
4379 */
4380
4381 /* Static Properties */
4382
4383 /**
4384 * @static
4385 * @inheritdoc
4386 */
4387 OO.ui.Tool.static.tagName = 'span';
4388
4389 /**
4390 * Symbolic name of tool.
4391 *
4392 * @abstract
4393 * @static
4394 * @inheritable
4395 * @property {string}
4396 */
4397 OO.ui.Tool.static.name = '';
4398
4399 /**
4400 * Tool group.
4401 *
4402 * @abstract
4403 * @static
4404 * @inheritable
4405 * @property {string}
4406 */
4407 OO.ui.Tool.static.group = '';
4408
4409 /**
4410 * Tool title.
4411 *
4412 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
4413 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
4414 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
4415 * appended to the title if the tool is part of a bar tool group.
4416 *
4417 * @abstract
4418 * @static
4419 * @inheritable
4420 * @property {string|Function} Title text or a function that returns text
4421 */
4422 OO.ui.Tool.static.title = '';
4423
4424 /**
4425 * Tool can be automatically added to catch-all groups.
4426 *
4427 * @static
4428 * @inheritable
4429 * @property {boolean}
4430 */
4431 OO.ui.Tool.static.autoAddToCatchall = true;
4432
4433 /**
4434 * Tool can be automatically added to named groups.
4435 *
4436 * @static
4437 * @property {boolean}
4438 * @inheritable
4439 */
4440 OO.ui.Tool.static.autoAddToGroup = true;
4441
4442 /**
4443 * Check if this tool is compatible with given data.
4444 *
4445 * @static
4446 * @inheritable
4447 * @param {Mixed} data Data to check
4448 * @return {boolean} Tool can be used with data
4449 */
4450 OO.ui.Tool.static.isCompatibleWith = function () {
4451 return false;
4452 };
4453
4454 /* Methods */
4455
4456 /**
4457 * Handle the toolbar state being updated.
4458 *
4459 * This is an abstract method that must be overridden in a concrete subclass.
4460 *
4461 * @abstract
4462 */
4463 OO.ui.Tool.prototype.onUpdateState = function () {
4464 throw new Error(
4465 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
4466 );
4467 };
4468
4469 /**
4470 * Handle the tool being selected.
4471 *
4472 * This is an abstract method that must be overridden in a concrete subclass.
4473 *
4474 * @abstract
4475 */
4476 OO.ui.Tool.prototype.onSelect = function () {
4477 throw new Error(
4478 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
4479 );
4480 };
4481
4482 /**
4483 * Check if the button is active.
4484 *
4485 * @param {boolean} Button is active
4486 */
4487 OO.ui.Tool.prototype.isActive = function () {
4488 return this.active;
4489 };
4490
4491 /**
4492 * Make the button appear active or inactive.
4493 *
4494 * @param {boolean} state Make button appear active
4495 */
4496 OO.ui.Tool.prototype.setActive = function ( state ) {
4497 this.active = !!state;
4498 if ( this.active ) {
4499 this.$element.addClass( 'oo-ui-tool-active' );
4500 } else {
4501 this.$element.removeClass( 'oo-ui-tool-active' );
4502 }
4503 };
4504
4505 /**
4506 * Get the tool title.
4507 *
4508 * @param {string|Function} title Title text or a function that returns text
4509 * @chainable
4510 */
4511 OO.ui.Tool.prototype.setTitle = function ( title ) {
4512 this.title = OO.ui.resolveMsg( title );
4513 this.updateTitle();
4514 return this;
4515 };
4516
4517 /**
4518 * Get the tool title.
4519 *
4520 * @return {string} Title text
4521 */
4522 OO.ui.Tool.prototype.getTitle = function () {
4523 return this.title;
4524 };
4525
4526 /**
4527 * Get the tool's symbolic name.
4528 *
4529 * @return {string} Symbolic name of tool
4530 */
4531 OO.ui.Tool.prototype.getName = function () {
4532 return this.constructor.static.name;
4533 };
4534
4535 /**
4536 * Update the title.
4537 */
4538 OO.ui.Tool.prototype.updateTitle = function () {
4539 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
4540 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
4541 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
4542 tooltipParts = [];
4543
4544 this.$title.empty()
4545 .text( this.title )
4546 .append(
4547 this.$( '<span>' )
4548 .addClass( 'oo-ui-tool-accel' )
4549 .text( accel )
4550 );
4551
4552 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
4553 tooltipParts.push( this.title );
4554 }
4555 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
4556 tooltipParts.push( accel );
4557 }
4558 if ( tooltipParts.length ) {
4559 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
4560 } else {
4561 this.$link.removeAttr( 'title' );
4562 }
4563 };
4564
4565 /**
4566 * Destroy tool.
4567 */
4568 OO.ui.Tool.prototype.destroy = function () {
4569 this.toolbar.disconnect( this );
4570 this.$element.remove();
4571 };
4572
4573 /**
4574 * Collection of tool groups.
4575 *
4576 * @class
4577 * @extends OO.ui.Element
4578 * @mixins OO.EventEmitter
4579 * @mixins OO.ui.GroupElement
4580 *
4581 * @constructor
4582 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
4583 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
4584 * @param {Object} [config] Configuration options
4585 * @cfg {boolean} [actions] Add an actions section opposite to the tools
4586 * @cfg {boolean} [shadow] Add a shadow below the toolbar
4587 */
4588 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
4589 // Configuration initialization
4590 config = config || {};
4591
4592 // Parent constructor
4593 OO.ui.Toolbar.super.call( this, config );
4594
4595 // Mixin constructors
4596 OO.EventEmitter.call( this );
4597 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
4598
4599 // Properties
4600 this.toolFactory = toolFactory;
4601 this.toolGroupFactory = toolGroupFactory;
4602 this.groups = [];
4603 this.tools = {};
4604 this.$bar = this.$( '<div>' );
4605 this.$actions = this.$( '<div>' );
4606 this.initialized = false;
4607
4608 // Events
4609 this.$element
4610 .add( this.$bar ).add( this.$group ).add( this.$actions )
4611 .on( 'mousedown', OO.ui.bind( this.onMouseDown, this ) );
4612
4613 // Initialization
4614 this.$group.addClass( 'oo-ui-toolbar-tools' );
4615 this.$bar.addClass( 'oo-ui-toolbar-bar' ).append( this.$group );
4616 if ( config.actions ) {
4617 this.$actions.addClass( 'oo-ui-toolbar-actions' );
4618 this.$bar.append( this.$actions );
4619 }
4620 this.$bar.append( '<div style="clear:both"></div>' );
4621 if ( config.shadow ) {
4622 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
4623 }
4624 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
4625 };
4626
4627 /* Setup */
4628
4629 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
4630 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
4631 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
4632
4633 /* Methods */
4634
4635 /**
4636 * Get the tool factory.
4637 *
4638 * @return {OO.ui.ToolFactory} Tool factory
4639 */
4640 OO.ui.Toolbar.prototype.getToolFactory = function () {
4641 return this.toolFactory;
4642 };
4643
4644 /**
4645 * Get the tool group factory.
4646 *
4647 * @return {OO.Factory} Tool group factory
4648 */
4649 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
4650 return this.toolGroupFactory;
4651 };
4652
4653 /**
4654 * Handles mouse down events.
4655 *
4656 * @param {jQuery.Event} e Mouse down event
4657 */
4658 OO.ui.Toolbar.prototype.onMouseDown = function ( e ) {
4659 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
4660 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
4661 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
4662 return false;
4663 }
4664 };
4665
4666 /**
4667 * Sets up handles and preloads required information for the toolbar to work.
4668 * This must be called immediately after it is attached to a visible document.
4669 */
4670 OO.ui.Toolbar.prototype.initialize = function () {
4671 this.initialized = true;
4672 };
4673
4674 /**
4675 * Setup toolbar.
4676 *
4677 * Tools can be specified in the following ways:
4678 *
4679 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
4680 * - All tools in a group: `{ 'group': 'group-name' }`
4681 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
4682 *
4683 * @param {Object.<string,Array>} groups List of tool group configurations
4684 * @param {Array|string} [groups.include] Tools to include
4685 * @param {Array|string} [groups.exclude] Tools to exclude
4686 * @param {Array|string} [groups.promote] Tools to promote to the beginning
4687 * @param {Array|string} [groups.demote] Tools to demote to the end
4688 */
4689 OO.ui.Toolbar.prototype.setup = function ( groups ) {
4690 var i, len, type, group,
4691 items = [],
4692 defaultType = 'bar';
4693
4694 // Cleanup previous groups
4695 this.reset();
4696
4697 // Build out new groups
4698 for ( i = 0, len = groups.length; i < len; i++ ) {
4699 group = groups[i];
4700 if ( group.include === '*' ) {
4701 // Apply defaults to catch-all groups
4702 if ( group.type === undefined ) {
4703 group.type = 'list';
4704 }
4705 if ( group.label === undefined ) {
4706 group.label = 'ooui-toolbar-more';
4707 }
4708 }
4709 // Check type has been registered
4710 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
4711 items.push(
4712 this.getToolGroupFactory().create( type, this, $.extend( { '$': this.$ }, group ) )
4713 );
4714 }
4715 this.addItems( items );
4716 };
4717
4718 /**
4719 * Remove all tools and groups from the toolbar.
4720 */
4721 OO.ui.Toolbar.prototype.reset = function () {
4722 var i, len;
4723
4724 this.groups = [];
4725 this.tools = {};
4726 for ( i = 0, len = this.items.length; i < len; i++ ) {
4727 this.items[i].destroy();
4728 }
4729 this.clearItems();
4730 };
4731
4732 /**
4733 * Destroys toolbar, removing event handlers and DOM elements.
4734 *
4735 * Call this whenever you are done using a toolbar.
4736 */
4737 OO.ui.Toolbar.prototype.destroy = function () {
4738 this.reset();
4739 this.$element.remove();
4740 };
4741
4742 /**
4743 * Check if tool has not been used yet.
4744 *
4745 * @param {string} name Symbolic name of tool
4746 * @return {boolean} Tool is available
4747 */
4748 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
4749 return !this.tools[name];
4750 };
4751
4752 /**
4753 * Prevent tool from being used again.
4754 *
4755 * @param {OO.ui.Tool} tool Tool to reserve
4756 */
4757 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
4758 this.tools[tool.getName()] = tool;
4759 };
4760
4761 /**
4762 * Allow tool to be used again.
4763 *
4764 * @param {OO.ui.Tool} tool Tool to release
4765 */
4766 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
4767 delete this.tools[tool.getName()];
4768 };
4769
4770 /**
4771 * Get accelerator label for tool.
4772 *
4773 * This is a stub that should be overridden to provide access to accelerator information.
4774 *
4775 * @param {string} name Symbolic name of tool
4776 * @return {string|undefined} Tool accelerator label if available
4777 */
4778 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
4779 return undefined;
4780 };
4781
4782 /**
4783 * Collection of tools.
4784 *
4785 * Tools can be specified in the following ways:
4786 *
4787 * - A specific tool: `{ 'name': 'tool-name' }` or `'tool-name'`
4788 * - All tools in a group: `{ 'group': 'group-name' }`
4789 * - All tools: `'*'`
4790 *
4791 * @abstract
4792 * @class
4793 * @extends OO.ui.Widget
4794 * @mixins OO.ui.GroupElement
4795 *
4796 * @constructor
4797 * @param {OO.ui.Toolbar} toolbar
4798 * @param {Object} [config] Configuration options
4799 * @cfg {Array|string} [include=[]] List of tools to include
4800 * @cfg {Array|string} [exclude=[]] List of tools to exclude
4801 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
4802 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
4803 */
4804 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
4805 // Configuration initialization
4806 config = config || {};
4807
4808 // Parent constructor
4809 OO.ui.ToolGroup.super.call( this, config );
4810
4811 // Mixin constructors
4812 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
4813
4814 // Properties
4815 this.toolbar = toolbar;
4816 this.tools = {};
4817 this.pressed = null;
4818 this.autoDisabled = false;
4819 this.include = config.include || [];
4820 this.exclude = config.exclude || [];
4821 this.promote = config.promote || [];
4822 this.demote = config.demote || [];
4823 this.onCapturedMouseUpHandler = OO.ui.bind( this.onCapturedMouseUp, this );
4824
4825 // Events
4826 this.$element.on( {
4827 'mousedown': OO.ui.bind( this.onMouseDown, this ),
4828 'mouseup': OO.ui.bind( this.onMouseUp, this ),
4829 'mouseover': OO.ui.bind( this.onMouseOver, this ),
4830 'mouseout': OO.ui.bind( this.onMouseOut, this )
4831 } );
4832 this.toolbar.getToolFactory().connect( this, { 'register': 'onToolFactoryRegister' } );
4833 this.aggregate( { 'disable': 'itemDisable' } );
4834 this.connect( this, { 'itemDisable': 'updateDisabled' } );
4835
4836 // Initialization
4837 this.$group.addClass( 'oo-ui-toolGroup-tools' );
4838 this.$element
4839 .addClass( 'oo-ui-toolGroup' )
4840 .append( this.$group );
4841 this.populate();
4842 };
4843
4844 /* Setup */
4845
4846 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
4847 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
4848
4849 /* Events */
4850
4851 /**
4852 * @event update
4853 */
4854
4855 /* Static Properties */
4856
4857 /**
4858 * Show labels in tooltips.
4859 *
4860 * @static
4861 * @inheritable
4862 * @property {boolean}
4863 */
4864 OO.ui.ToolGroup.static.titleTooltips = false;
4865
4866 /**
4867 * Show acceleration labels in tooltips.
4868 *
4869 * @static
4870 * @inheritable
4871 * @property {boolean}
4872 */
4873 OO.ui.ToolGroup.static.accelTooltips = false;
4874
4875 /**
4876 * Automatically disable the toolgroup when all tools are disabled
4877 *
4878 * @static
4879 * @inheritable
4880 * @property {boolean}
4881 */
4882 OO.ui.ToolGroup.static.autoDisable = true;
4883
4884 /* Methods */
4885
4886 /**
4887 * @inheritdoc
4888 */
4889 OO.ui.ToolGroup.prototype.isDisabled = function () {
4890 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
4891 };
4892
4893 /**
4894 * @inheritdoc
4895 */
4896 OO.ui.ToolGroup.prototype.updateDisabled = function () {
4897 var i, item, allDisabled = true;
4898
4899 if ( this.constructor.static.autoDisable ) {
4900 for ( i = this.items.length - 1; i >= 0; i-- ) {
4901 item = this.items[i];
4902 if ( !item.isDisabled() ) {
4903 allDisabled = false;
4904 break;
4905 }
4906 }
4907 this.autoDisabled = allDisabled;
4908 }
4909 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
4910 };
4911
4912 /**
4913 * Handle mouse down events.
4914 *
4915 * @param {jQuery.Event} e Mouse down event
4916 */
4917 OO.ui.ToolGroup.prototype.onMouseDown = function ( e ) {
4918 if ( !this.isDisabled() && e.which === 1 ) {
4919 this.pressed = this.getTargetTool( e );
4920 if ( this.pressed ) {
4921 this.pressed.setActive( true );
4922 this.getElementDocument().addEventListener(
4923 'mouseup', this.onCapturedMouseUpHandler, true
4924 );
4925 }
4926 }
4927 return false;
4928 };
4929
4930 /**
4931 * Handle captured mouse up events.
4932 *
4933 * @param {Event} e Mouse up event
4934 */
4935 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
4936 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
4937 // onMouseUp may be called a second time, depending on where the mouse is when the button is
4938 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
4939 this.onMouseUp( e );
4940 };
4941
4942 /**
4943 * Handle mouse up events.
4944 *
4945 * @param {jQuery.Event} e Mouse up event
4946 */
4947 OO.ui.ToolGroup.prototype.onMouseUp = function ( e ) {
4948 var tool = this.getTargetTool( e );
4949
4950 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
4951 this.pressed.onSelect();
4952 }
4953
4954 this.pressed = null;
4955 return false;
4956 };
4957
4958 /**
4959 * Handle mouse over events.
4960 *
4961 * @param {jQuery.Event} e Mouse over event
4962 */
4963 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
4964 var tool = this.getTargetTool( e );
4965
4966 if ( this.pressed && this.pressed === tool ) {
4967 this.pressed.setActive( true );
4968 }
4969 };
4970
4971 /**
4972 * Handle mouse out events.
4973 *
4974 * @param {jQuery.Event} e Mouse out event
4975 */
4976 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
4977 var tool = this.getTargetTool( e );
4978
4979 if ( this.pressed && this.pressed === tool ) {
4980 this.pressed.setActive( false );
4981 }
4982 };
4983
4984 /**
4985 * Get the closest tool to a jQuery.Event.
4986 *
4987 * Only tool links are considered, which prevents other elements in the tool such as popups from
4988 * triggering tool group interactions.
4989 *
4990 * @private
4991 * @param {jQuery.Event} e
4992 * @return {OO.ui.Tool|null} Tool, `null` if none was found
4993 */
4994 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
4995 var tool,
4996 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
4997
4998 if ( $item.length ) {
4999 tool = $item.parent().data( 'oo-ui-tool' );
5000 }
5001
5002 return tool && !tool.isDisabled() ? tool : null;
5003 };
5004
5005 /**
5006 * Handle tool registry register events.
5007 *
5008 * If a tool is registered after the group is created, we must repopulate the list to account for:
5009 *
5010 * - a tool being added that may be included
5011 * - a tool already included being overridden
5012 *
5013 * @param {string} name Symbolic name of tool
5014 */
5015 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
5016 this.populate();
5017 };
5018
5019 /**
5020 * Get the toolbar this group is in.
5021 *
5022 * @return {OO.ui.Toolbar} Toolbar of group
5023 */
5024 OO.ui.ToolGroup.prototype.getToolbar = function () {
5025 return this.toolbar;
5026 };
5027
5028 /**
5029 * Add and remove tools based on configuration.
5030 */
5031 OO.ui.ToolGroup.prototype.populate = function () {
5032 var i, len, name, tool,
5033 toolFactory = this.toolbar.getToolFactory(),
5034 names = {},
5035 add = [],
5036 remove = [],
5037 list = this.toolbar.getToolFactory().getTools(
5038 this.include, this.exclude, this.promote, this.demote
5039 );
5040
5041 // Build a list of needed tools
5042 for ( i = 0, len = list.length; i < len; i++ ) {
5043 name = list[i];
5044 if (
5045 // Tool exists
5046 toolFactory.lookup( name ) &&
5047 // Tool is available or is already in this group
5048 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
5049 ) {
5050 tool = this.tools[name];
5051 if ( !tool ) {
5052 // Auto-initialize tools on first use
5053 this.tools[name] = tool = toolFactory.create( name, this );
5054 tool.updateTitle();
5055 }
5056 this.toolbar.reserveTool( tool );
5057 add.push( tool );
5058 names[name] = true;
5059 }
5060 }
5061 // Remove tools that are no longer needed
5062 for ( name in this.tools ) {
5063 if ( !names[name] ) {
5064 this.tools[name].destroy();
5065 this.toolbar.releaseTool( this.tools[name] );
5066 remove.push( this.tools[name] );
5067 delete this.tools[name];
5068 }
5069 }
5070 if ( remove.length ) {
5071 this.removeItems( remove );
5072 }
5073 // Update emptiness state
5074 if ( add.length ) {
5075 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
5076 } else {
5077 this.$element.addClass( 'oo-ui-toolGroup-empty' );
5078 }
5079 // Re-add tools (moving existing ones to new locations)
5080 this.addItems( add );
5081 // Disabled state may depend on items
5082 this.updateDisabled();
5083 };
5084
5085 /**
5086 * Destroy tool group.
5087 */
5088 OO.ui.ToolGroup.prototype.destroy = function () {
5089 var name;
5090
5091 this.clearItems();
5092 this.toolbar.getToolFactory().disconnect( this );
5093 for ( name in this.tools ) {
5094 this.toolbar.releaseTool( this.tools[name] );
5095 this.tools[name].disconnect( this ).destroy();
5096 delete this.tools[name];
5097 }
5098 this.$element.remove();
5099 };
5100
5101 /**
5102 * Dialog for showing a message.
5103 *
5104 * User interface:
5105 * - Registers two actions by default (safe and primary).
5106 * - Renders action widgets in the footer.
5107 *
5108 * @class
5109 * @extends OO.ui.Dialog
5110 *
5111 * @constructor
5112 * @param {Object} [config] Configuration options
5113 */
5114 OO.ui.MessageDialog = function OoUiMessageDialog( manager, config ) {
5115 // Parent constructor
5116 OO.ui.MessageDialog.super.call( this, manager, config );
5117
5118 // Properties
5119 this.verticalActionLayout = null;
5120
5121 // Initialization
5122 this.$element.addClass( 'oo-ui-messageDialog' );
5123 };
5124
5125 /* Inheritance */
5126
5127 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
5128
5129 /* Static Properties */
5130
5131 OO.ui.MessageDialog.static.name = 'message';
5132
5133 OO.ui.MessageDialog.static.size = 'small';
5134
5135 OO.ui.MessageDialog.static.verbose = false;
5136
5137 /**
5138 * Dialog title.
5139 *
5140 * A confirmation dialog's title should describe what the progressive action will do. An alert
5141 * dialog's title should describe what event occured.
5142 *
5143 * @static
5144 * inheritable
5145 * @property {jQuery|string|Function|null}
5146 */
5147 OO.ui.MessageDialog.static.title = null;
5148
5149 /**
5150 * A confirmation dialog's message should describe the consequences of the progressive action. An
5151 * alert dialog's message should describe why the event occured.
5152 *
5153 * @static
5154 * inheritable
5155 * @property {jQuery|string|Function|null}
5156 */
5157 OO.ui.MessageDialog.static.message = null;
5158
5159 OO.ui.MessageDialog.static.actions = [
5160 { 'label': OO.ui.deferMsg( 'ooui-dialog-message-accept' ), 'flags': 'primary' },
5161 { 'label': OO.ui.deferMsg( 'ooui-dialog-message-reject' ), 'flags': 'safe' }
5162 ];
5163
5164 /* Methods */
5165
5166 /**
5167 * @inheritdoc
5168 */
5169 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
5170 this.fitActions();
5171 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
5172 };
5173
5174 /**
5175 * Toggle action layout between vertical and horizontal.
5176 *
5177 * @param {boolean} [value] Layout actions vertically, omit to toggle
5178 * @chainable
5179 */
5180 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
5181 value = value === undefined ? !this.verticalActionLayout : !!value;
5182
5183 if ( value !== this.verticalActionLayout ) {
5184 this.verticalActionLayout = value;
5185 this.$actions
5186 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
5187 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
5188 }
5189
5190 return this;
5191 };
5192
5193 /**
5194 * @inheritdoc
5195 */
5196 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
5197 if ( action ) {
5198 return new OO.ui.Process( function () {
5199 this.close( { 'action': action } );
5200 }, this );
5201 }
5202 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
5203 };
5204
5205 /**
5206 * @inheritdoc
5207 *
5208 * @param {Object} [data] Dialog opening data
5209 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
5210 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
5211 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
5212 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
5213 * action item
5214 */
5215 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
5216 data = data || {};
5217
5218 // Parent method
5219 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
5220 .next( function () {
5221 this.title.setLabel(
5222 data.title !== undefined ? data.title : this.constructor.static.title
5223 );
5224 this.message.setLabel(
5225 data.message !== undefined ? data.message : this.constructor.static.message
5226 );
5227 this.message.$element.toggleClass(
5228 'oo-ui-messageDialog-message-verbose',
5229 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
5230 );
5231 }, this );
5232 };
5233
5234 /**
5235 * @inheritdoc
5236 */
5237 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
5238 return Math.round( this.text.$element.outerHeight( true ) );
5239 };
5240
5241 /**
5242 * @inheritdoc
5243 */
5244 OO.ui.MessageDialog.prototype.initialize = function () {
5245 // Parent method
5246 OO.ui.MessageDialog.super.prototype.initialize.call( this );
5247
5248 // Properties
5249 this.$actions = this.$( '<div>' );
5250 this.container = new OO.ui.PanelLayout( {
5251 '$': this.$, 'scrollable': true, 'classes': [ 'oo-ui-messageDialog-container' ]
5252 } );
5253 this.text = new OO.ui.PanelLayout( {
5254 '$': this.$, 'padded': true, 'expanded': false, 'classes': [ 'oo-ui-messageDialog-text' ]
5255 } );
5256 this.message = new OO.ui.LabelWidget( {
5257 '$': this.$, 'classes': [ 'oo-ui-messageDialog-message' ]
5258 } );
5259
5260 // Initialization
5261 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
5262 this.frame.$content.addClass( 'oo-ui-messageDialog-content' );
5263 this.container.$element.append( this.text.$element );
5264 this.text.$element.append( this.title.$element, this.message.$element );
5265 this.$body.append( this.container.$element );
5266 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
5267 this.$foot.append( this.$actions );
5268 };
5269
5270 /**
5271 * @inheritdoc
5272 */
5273 OO.ui.MessageDialog.prototype.attachActions = function () {
5274 var i, len, other, special, others;
5275
5276 // Parent method
5277 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
5278
5279 special = this.actions.getSpecial();
5280 others = this.actions.getOthers();
5281 if ( special.safe ) {
5282 this.$actions.append( special.safe.$element );
5283 special.safe.toggleFramed( false );
5284 }
5285 if ( others.length ) {
5286 for ( i = 0, len = others.length; i < len; i++ ) {
5287 other = others[i];
5288 this.$actions.append( other.$element );
5289 other.toggleFramed( false );
5290 }
5291 }
5292 if ( special.primary ) {
5293 this.$actions.append( special.primary.$element );
5294 special.primary.toggleFramed( false );
5295 }
5296
5297 this.fitActions();
5298 if ( !this.isOpening() ) {
5299 this.manager.updateWindowSize( this );
5300 }
5301 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
5302 };
5303
5304 /**
5305 * Fit action actions into columns or rows.
5306 *
5307 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
5308 */
5309 OO.ui.MessageDialog.prototype.fitActions = function () {
5310 var i, len, action,
5311 actions = this.actions.get();
5312
5313 // Detect clipping
5314 this.toggleVerticalActionLayout( false );
5315 for ( i = 0, len = actions.length; i < len; i++ ) {
5316 action = actions[i];
5317 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
5318 this.toggleVerticalActionLayout( true );
5319 break;
5320 }
5321 }
5322 };
5323
5324 /**
5325 * Navigation dialog window.
5326 *
5327 * Logic:
5328 * - Show and hide errors.
5329 * - Retry an action.
5330 *
5331 * User interface:
5332 * - Renders header with dialog title and one action widget on either side
5333 * (a 'safe' button on the left, and a 'primary' button on the right, both of
5334 * which close the dialog).
5335 * - Displays any action widgets in the footer (none by default).
5336 * - Ability to dismiss errors.
5337 *
5338 * Subclass responsibilities:
5339 * - Register a 'safe' action.
5340 * - Register a 'primary' action.
5341 * - Add content to the dialog.
5342 *
5343 * @abstract
5344 * @class
5345 * @extends OO.ui.Dialog
5346 *
5347 * @constructor
5348 * @param {Object} [config] Configuration options
5349 */
5350 OO.ui.ProcessDialog = function OoUiProcessDialog( manager, config ) {
5351 // Parent constructor
5352 OO.ui.ProcessDialog.super.call( this, manager, config );
5353
5354 // Initialization
5355 this.$element.addClass( 'oo-ui-processDialog' );
5356 };
5357
5358 /* Setup */
5359
5360 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
5361
5362 /* Methods */
5363
5364 /**
5365 * Handle dismiss button click events.
5366 *
5367 * Hides errors.
5368 */
5369 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
5370 this.hideErrors();
5371 };
5372
5373 /**
5374 * Handle retry button click events.
5375 *
5376 * Hides errors and then tries again.
5377 */
5378 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
5379 this.hideErrors();
5380 this.executeAction( this.currentAction.getAction() );
5381 };
5382
5383 /**
5384 * @inheritdoc
5385 */
5386 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
5387 if ( this.actions.isSpecial( action ) ) {
5388 this.fitLabel();
5389 }
5390 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
5391 };
5392
5393 /**
5394 * @inheritdoc
5395 */
5396 OO.ui.ProcessDialog.prototype.initialize = function () {
5397 // Parent method
5398 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
5399
5400 // Properties
5401 this.$navigation = this.$( '<div>' );
5402 this.$location = this.$( '<div>' );
5403 this.$safeActions = this.$( '<div>' );
5404 this.$primaryActions = this.$( '<div>' );
5405 this.$otherActions = this.$( '<div>' );
5406 this.dismissButton = new OO.ui.ButtonWidget( {
5407 '$': this.$,
5408 'label': OO.ui.msg( 'ooui-dialog-process-dismiss' )
5409 } );
5410 this.retryButton = new OO.ui.ButtonWidget( {
5411 '$': this.$,
5412 'label': OO.ui.msg( 'ooui-dialog-process-retry' )
5413 } );
5414 this.$errors = this.$( '<div>' );
5415 this.$errorsTitle = this.$( '<div>' );
5416
5417 // Events
5418 this.dismissButton.connect( this, { 'click': 'onDismissErrorButtonClick' } );
5419 this.retryButton.connect( this, { 'click': 'onRetryButtonClick' } );
5420
5421 // Initialization
5422 this.title.$element.addClass( 'oo-ui-processDialog-title' );
5423 this.$location
5424 .append( this.title.$element )
5425 .addClass( 'oo-ui-processDialog-location' );
5426 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
5427 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
5428 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
5429 this.$errorsTitle
5430 .addClass( 'oo-ui-processDialog-errors-title' )
5431 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
5432 this.$errors
5433 .addClass( 'oo-ui-processDialog-errors' )
5434 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
5435 this.frame.$content
5436 .addClass( 'oo-ui-processDialog-content' )
5437 .append( this.$errors );
5438 this.$navigation
5439 .addClass( 'oo-ui-processDialog-navigation' )
5440 .append( this.$safeActions, this.$location, this.$primaryActions );
5441 this.$head.append( this.$navigation );
5442 this.$foot.append( this.$otherActions );
5443 };
5444
5445 /**
5446 * @inheritdoc
5447 */
5448 OO.ui.ProcessDialog.prototype.attachActions = function () {
5449 var i, len, other, special, others;
5450
5451 // Parent method
5452 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
5453
5454 special = this.actions.getSpecial();
5455 others = this.actions.getOthers();
5456 if ( special.primary ) {
5457 this.$primaryActions.append( special.primary.$element );
5458 special.primary.toggleFramed( false );
5459 }
5460 if ( others.length ) {
5461 for ( i = 0, len = others.length; i < len; i++ ) {
5462 other = others[i];
5463 this.$otherActions.append( other.$element );
5464 other.toggleFramed( true );
5465 }
5466 }
5467 if ( special.safe ) {
5468 this.$safeActions.append( special.safe.$element );
5469 special.safe.toggleFramed( false );
5470 }
5471
5472 this.fitLabel();
5473 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
5474 };
5475
5476 /**
5477 * @inheritdoc
5478 */
5479 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
5480 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
5481 .fail( OO.ui.bind( this.showErrors, this ) );
5482 };
5483
5484 /**
5485 * Fit label between actions.
5486 *
5487 * @chainable
5488 */
5489 OO.ui.ProcessDialog.prototype.fitLabel = function () {
5490 var width = Math.max(
5491 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
5492 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
5493 );
5494 this.$location.css( { 'padding-left': width, 'padding-right': width } );
5495
5496 return this;
5497 };
5498
5499 /**
5500 * Handle errors that occured durring accept or reject processes.
5501 *
5502 * @param {OO.ui.Error[]} errors Errors to be handled
5503 */
5504 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
5505 var i, len, $item,
5506 items = [],
5507 recoverable = true;
5508
5509 for ( i = 0, len = errors.length; i < len; i++ ) {
5510 if ( !errors[i].isRecoverable() ) {
5511 recoverable = false;
5512 }
5513 $item = this.$( '<div>' )
5514 .addClass( 'oo-ui-processDialog-error' )
5515 .append( errors[i].getMessage() );
5516 items.push( $item[0] );
5517 }
5518 this.$errorItems = this.$( items );
5519 if ( recoverable ) {
5520 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
5521 } else {
5522 this.currentAction.setDisabled( true );
5523 }
5524 this.retryButton.toggle( recoverable );
5525 this.$errorsTitle.after( this.$errorItems );
5526 this.$errors.show().scrollTop( 0 );
5527 };
5528
5529 /**
5530 * Hide errors.
5531 */
5532 OO.ui.ProcessDialog.prototype.hideErrors = function () {
5533 this.$errors.hide();
5534 this.$errorItems.remove();
5535 this.$errorItems = null;
5536 };
5537
5538 /**
5539 * Layout containing a series of pages.
5540 *
5541 * @class
5542 * @extends OO.ui.Layout
5543 *
5544 * @constructor
5545 * @param {Object} [config] Configuration options
5546 * @cfg {boolean} [continuous=false] Show all pages, one after another
5547 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
5548 * @cfg {boolean} [outlined=false] Show an outline
5549 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
5550 */
5551 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
5552 // Initialize configuration
5553 config = config || {};
5554
5555 // Parent constructor
5556 OO.ui.BookletLayout.super.call( this, config );
5557
5558 // Properties
5559 this.currentPageName = null;
5560 this.pages = {};
5561 this.ignoreFocus = false;
5562 this.stackLayout = new OO.ui.StackLayout( { '$': this.$, 'continuous': !!config.continuous } );
5563 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
5564 this.outlineVisible = false;
5565 this.outlined = !!config.outlined;
5566 if ( this.outlined ) {
5567 this.editable = !!config.editable;
5568 this.outlineControlsWidget = null;
5569 this.outlineWidget = new OO.ui.OutlineWidget( { '$': this.$ } );
5570 this.outlinePanel = new OO.ui.PanelLayout( { '$': this.$, 'scrollable': true } );
5571 this.gridLayout = new OO.ui.GridLayout(
5572 [ this.outlinePanel, this.stackLayout ],
5573 { '$': this.$, 'widths': [ 1, 2 ] }
5574 );
5575 this.outlineVisible = true;
5576 if ( this.editable ) {
5577 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
5578 this.outlineWidget, { '$': this.$ }
5579 );
5580 }
5581 }
5582
5583 // Events
5584 this.stackLayout.connect( this, { 'set': 'onStackLayoutSet' } );
5585 if ( this.outlined ) {
5586 this.outlineWidget.connect( this, { 'select': 'onOutlineWidgetSelect' } );
5587 }
5588 if ( this.autoFocus ) {
5589 // Event 'focus' does not bubble, but 'focusin' does
5590 this.stackLayout.onDOMEvent( 'focusin', OO.ui.bind( this.onStackLayoutFocus, this ) );
5591 }
5592
5593 // Initialization
5594 this.$element.addClass( 'oo-ui-bookletLayout' );
5595 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
5596 if ( this.outlined ) {
5597 this.outlinePanel.$element
5598 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
5599 .append( this.outlineWidget.$element );
5600 if ( this.editable ) {
5601 this.outlinePanel.$element
5602 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
5603 .append( this.outlineControlsWidget.$element );
5604 }
5605 this.$element.append( this.gridLayout.$element );
5606 } else {
5607 this.$element.append( this.stackLayout.$element );
5608 }
5609 };
5610
5611 /* Setup */
5612
5613 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
5614
5615 /* Events */
5616
5617 /**
5618 * @event set
5619 * @param {OO.ui.PageLayout} page Current page
5620 */
5621
5622 /**
5623 * @event add
5624 * @param {OO.ui.PageLayout[]} page Added pages
5625 * @param {number} index Index pages were added at
5626 */
5627
5628 /**
5629 * @event remove
5630 * @param {OO.ui.PageLayout[]} pages Removed pages
5631 */
5632
5633 /* Methods */
5634
5635 /**
5636 * Handle stack layout focus.
5637 *
5638 * @param {jQuery.Event} e Focusin event
5639 */
5640 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
5641 var name, $target;
5642
5643 // Find the page that an element was focused within
5644 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
5645 for ( name in this.pages ) {
5646 // Check for page match, exclude current page to find only page changes
5647 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
5648 this.setPage( name );
5649 break;
5650 }
5651 }
5652 };
5653
5654 /**
5655 * Handle stack layout set events.
5656 *
5657 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
5658 */
5659 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
5660 var layout = this;
5661 if ( page ) {
5662 page.scrollElementIntoView( { 'complete': function () {
5663 if ( layout.autoFocus ) {
5664 // Set focus to the first input if nothing on the page is focused yet
5665 if ( !page.$element.find( ':focus' ).length ) {
5666 page.$element.find( ':input:first' ).focus();
5667 }
5668 }
5669 } } );
5670 }
5671 };
5672
5673 /**
5674 * Handle outline widget select events.
5675 *
5676 * @param {OO.ui.OptionWidget|null} item Selected item
5677 */
5678 OO.ui.BookletLayout.prototype.onOutlineWidgetSelect = function ( item ) {
5679 if ( item ) {
5680 this.setPage( item.getData() );
5681 }
5682 };
5683
5684 /**
5685 * Check if booklet has an outline.
5686 *
5687 * @return {boolean}
5688 */
5689 OO.ui.BookletLayout.prototype.isOutlined = function () {
5690 return this.outlined;
5691 };
5692
5693 /**
5694 * Check if booklet has editing controls.
5695 *
5696 * @return {boolean}
5697 */
5698 OO.ui.BookletLayout.prototype.isEditable = function () {
5699 return this.editable;
5700 };
5701
5702 /**
5703 * Check if booklet has a visible outline.
5704 *
5705 * @return {boolean}
5706 */
5707 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
5708 return this.outlined && this.outlineVisible;
5709 };
5710
5711 /**
5712 * Hide or show the outline.
5713 *
5714 * @param {boolean} [show] Show outline, omit to invert current state
5715 * @chainable
5716 */
5717 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
5718 if ( this.outlined ) {
5719 show = show === undefined ? !this.outlineVisible : !!show;
5720 this.outlineVisible = show;
5721 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
5722 }
5723
5724 return this;
5725 };
5726
5727 /**
5728 * Get the outline widget.
5729 *
5730 * @param {OO.ui.PageLayout} page Page to be selected
5731 * @return {OO.ui.PageLayout|null} Closest page to another
5732 */
5733 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
5734 var next, prev, level,
5735 pages = this.stackLayout.getItems(),
5736 index = $.inArray( page, pages );
5737
5738 if ( index !== -1 ) {
5739 next = pages[index + 1];
5740 prev = pages[index - 1];
5741 // Prefer adjacent pages at the same level
5742 if ( this.outlined ) {
5743 level = this.outlineWidget.getItemFromData( page.getName() ).getLevel();
5744 if (
5745 prev &&
5746 level === this.outlineWidget.getItemFromData( prev.getName() ).getLevel()
5747 ) {
5748 return prev;
5749 }
5750 if (
5751 next &&
5752 level === this.outlineWidget.getItemFromData( next.getName() ).getLevel()
5753 ) {
5754 return next;
5755 }
5756 }
5757 }
5758 return prev || next || null;
5759 };
5760
5761 /**
5762 * Get the outline widget.
5763 *
5764 * @return {OO.ui.OutlineWidget|null} Outline widget, or null if boolet has no outline
5765 */
5766 OO.ui.BookletLayout.prototype.getOutline = function () {
5767 return this.outlineWidget;
5768 };
5769
5770 /**
5771 * Get the outline controls widget. If the outline is not editable, null is returned.
5772 *
5773 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
5774 */
5775 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
5776 return this.outlineControlsWidget;
5777 };
5778
5779 /**
5780 * Get a page by name.
5781 *
5782 * @param {string} name Symbolic name of page
5783 * @return {OO.ui.PageLayout|undefined} Page, if found
5784 */
5785 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
5786 return this.pages[name];
5787 };
5788
5789 /**
5790 * Get the current page name.
5791 *
5792 * @return {string|null} Current page name
5793 */
5794 OO.ui.BookletLayout.prototype.getPageName = function () {
5795 return this.currentPageName;
5796 };
5797
5798 /**
5799 * Add a page to the layout.
5800 *
5801 * When pages are added with the same names as existing pages, the existing pages will be
5802 * automatically removed before the new pages are added.
5803 *
5804 * @param {OO.ui.PageLayout[]} pages Pages to add
5805 * @param {number} index Index to insert pages after
5806 * @fires add
5807 * @chainable
5808 */
5809 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
5810 var i, len, name, page, item, currentIndex,
5811 stackLayoutPages = this.stackLayout.getItems(),
5812 remove = [],
5813 items = [];
5814
5815 // Remove pages with same names
5816 for ( i = 0, len = pages.length; i < len; i++ ) {
5817 page = pages[i];
5818 name = page.getName();
5819
5820 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
5821 // Correct the insertion index
5822 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
5823 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
5824 index--;
5825 }
5826 remove.push( this.pages[name] );
5827 }
5828 }
5829 if ( remove.length ) {
5830 this.removePages( remove );
5831 }
5832
5833 // Add new pages
5834 for ( i = 0, len = pages.length; i < len; i++ ) {
5835 page = pages[i];
5836 name = page.getName();
5837 this.pages[page.getName()] = page;
5838 if ( this.outlined ) {
5839 item = new OO.ui.OutlineItemWidget( name, page, { '$': this.$ } );
5840 page.setOutlineItem( item );
5841 items.push( item );
5842 }
5843 }
5844
5845 if ( this.outlined && items.length ) {
5846 this.outlineWidget.addItems( items, index );
5847 this.updateOutlineWidget();
5848 }
5849 this.stackLayout.addItems( pages, index );
5850 this.emit( 'add', pages, index );
5851
5852 return this;
5853 };
5854
5855 /**
5856 * Remove a page from the layout.
5857 *
5858 * @fires remove
5859 * @chainable
5860 */
5861 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
5862 var i, len, name, page,
5863 items = [];
5864
5865 for ( i = 0, len = pages.length; i < len; i++ ) {
5866 page = pages[i];
5867 name = page.getName();
5868 delete this.pages[name];
5869 if ( this.outlined ) {
5870 items.push( this.outlineWidget.getItemFromData( name ) );
5871 page.setOutlineItem( null );
5872 }
5873 }
5874 if ( this.outlined && items.length ) {
5875 this.outlineWidget.removeItems( items );
5876 this.updateOutlineWidget();
5877 }
5878 this.stackLayout.removeItems( pages );
5879 this.emit( 'remove', pages );
5880
5881 return this;
5882 };
5883
5884 /**
5885 * Clear all pages from the layout.
5886 *
5887 * @fires remove
5888 * @chainable
5889 */
5890 OO.ui.BookletLayout.prototype.clearPages = function () {
5891 var i, len,
5892 pages = this.stackLayout.getItems();
5893
5894 this.pages = {};
5895 this.currentPageName = null;
5896 if ( this.outlined ) {
5897 this.outlineWidget.clearItems();
5898 for ( i = 0, len = pages.length; i < len; i++ ) {
5899 pages[i].setOutlineItem( null );
5900 }
5901 }
5902 this.stackLayout.clearItems();
5903
5904 this.emit( 'remove', pages );
5905
5906 return this;
5907 };
5908
5909 /**
5910 * Set the current page by name.
5911 *
5912 * @fires set
5913 * @param {string} name Symbolic name of page
5914 */
5915 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
5916 var selectedItem,
5917 page = this.pages[name];
5918
5919 if ( name !== this.currentPageName ) {
5920 if ( this.outlined ) {
5921 selectedItem = this.outlineWidget.getSelectedItem();
5922 if ( selectedItem && selectedItem.getData() !== name ) {
5923 this.outlineWidget.selectItem( this.outlineWidget.getItemFromData( name ) );
5924 }
5925 }
5926 if ( page ) {
5927 if ( this.currentPageName && this.pages[this.currentPageName] ) {
5928 this.pages[this.currentPageName].setActive( false );
5929 // Blur anything focused if the next page doesn't have anything focusable - this
5930 // is not needed if the next page has something focusable because once it is focused
5931 // this blur happens automatically
5932 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
5933 this.pages[this.currentPageName].$element.find( ':focus' ).blur();
5934 }
5935 }
5936 this.currentPageName = name;
5937 this.stackLayout.setItem( page );
5938 page.setActive( true );
5939 this.emit( 'set', page );
5940 }
5941 }
5942 };
5943
5944 /**
5945 * Call this after adding or removing items from the OutlineWidget.
5946 *
5947 * @chainable
5948 */
5949 OO.ui.BookletLayout.prototype.updateOutlineWidget = function () {
5950 // Auto-select first item when nothing is selected anymore
5951 if ( !this.outlineWidget.getSelectedItem() ) {
5952 this.outlineWidget.selectItem( this.outlineWidget.getFirstSelectableItem() );
5953 }
5954
5955 return this;
5956 };
5957
5958 /**
5959 * Layout made of a field and optional label.
5960 *
5961 * @class
5962 * @extends OO.ui.Layout
5963 * @mixins OO.ui.LabeledElement
5964 *
5965 * Available label alignment modes include:
5966 * - 'left': Label is before the field and aligned away from it, best for when the user will be
5967 * scanning for a specific label in a form with many fields
5968 * - 'right': Label is before the field and aligned toward it, best for forms the user is very
5969 * familiar with and will tab through field checking quickly to verify which field they are in
5970 * - 'top': Label is before the field and above it, best for when the use will need to fill out all
5971 * fields from top to bottom in a form with few fields
5972 * - 'inline': Label is after the field and aligned toward it, best for small boolean fields like
5973 * checkboxes or radio buttons
5974 *
5975 * @constructor
5976 * @param {OO.ui.Widget} field Field widget
5977 * @param {Object} [config] Configuration options
5978 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
5979 * @cfg {string} [help] Explanatory text shown as a '?' icon.
5980 */
5981 OO.ui.FieldLayout = function OoUiFieldLayout( field, config ) {
5982 var popupButtonWidget;
5983 // Config initialization
5984 config = $.extend( { 'align': 'left' }, config );
5985
5986 // Parent constructor
5987 OO.ui.FieldLayout.super.call( this, config );
5988
5989 // Mixin constructors
5990 this.$help = this.$( '<div>' );
5991 OO.ui.LabeledElement.call( this, this.$( '<label>' ), config );
5992 if ( config.help ) {
5993 popupButtonWidget = new OO.ui.PopupButtonWidget( $.extend(
5994 {
5995 '$': this.$,
5996 'frameless': true,
5997 'icon': 'info',
5998 'title': config.help
5999 },
6000 config,
6001 { label: null }
6002 ) );
6003 popupButtonWidget.getPopup().$body.append( this.getElementDocument().createTextNode( config.help ) );
6004 this.$help = popupButtonWidget.$element;
6005 }
6006
6007 // Properties
6008 this.$field = this.$( '<div>' );
6009 this.field = field;
6010 this.align = null;
6011
6012 // Events
6013 if ( this.field instanceof OO.ui.InputWidget ) {
6014 this.$label.on( 'click', OO.ui.bind( this.onLabelClick, this ) );
6015 }
6016 this.field.connect( this, { 'disable': 'onFieldDisable' } );
6017
6018 // Initialization
6019 this.$element.addClass( 'oo-ui-fieldLayout' );
6020 this.$field
6021 .addClass( 'oo-ui-fieldLayout-field' )
6022 .toggleClass( 'oo-ui-fieldLayout-disable', this.field.isDisabled() )
6023 .append( this.field.$element );
6024 this.setAlignment( config.align );
6025 };
6026
6027 /* Setup */
6028
6029 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
6030 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabeledElement );
6031
6032 /* Methods */
6033
6034 /**
6035 * Handle field disable events.
6036 *
6037 * @param {boolean} value Field is disabled
6038 */
6039 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
6040 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
6041 };
6042
6043 /**
6044 * Handle label mouse click events.
6045 *
6046 * @param {jQuery.Event} e Mouse click event
6047 */
6048 OO.ui.FieldLayout.prototype.onLabelClick = function () {
6049 this.field.simulateLabelClick();
6050 return false;
6051 };
6052
6053 /**
6054 * Get the field.
6055 *
6056 * @return {OO.ui.Widget} Field widget
6057 */
6058 OO.ui.FieldLayout.prototype.getField = function () {
6059 return this.field;
6060 };
6061
6062 /**
6063 * Set the field alignment mode.
6064 *
6065 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
6066 * @chainable
6067 */
6068 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
6069 if ( value !== this.align ) {
6070 // Default to 'left'
6071 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
6072 value = 'left';
6073 }
6074 // Reorder elements
6075 if ( value === 'inline' ) {
6076 this.$element.append( this.$field, this.$label, this.$help );
6077 } else {
6078 this.$element.append( this.$help, this.$label, this.$field );
6079 }
6080 // Set classes
6081 if ( this.align ) {
6082 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
6083 }
6084 this.align = value;
6085 this.$element.addClass( 'oo-ui-fieldLayout-align-' + this.align );
6086 }
6087
6088 return this;
6089 };
6090
6091 /**
6092 * Layout made of a fieldset and optional legend.
6093 *
6094 * Just add OO.ui.FieldLayout items.
6095 *
6096 * @class
6097 * @extends OO.ui.Layout
6098 * @mixins OO.ui.LabeledElement
6099 * @mixins OO.ui.IconedElement
6100 * @mixins OO.ui.GroupElement
6101 *
6102 * @constructor
6103 * @param {Object} [config] Configuration options
6104 * @cfg {string} [icon] Symbolic icon name
6105 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
6106 */
6107 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
6108 // Config initialization
6109 config = config || {};
6110
6111 // Parent constructor
6112 OO.ui.FieldsetLayout.super.call( this, config );
6113
6114 // Mixin constructors
6115 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
6116 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
6117 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
6118
6119 // Initialization
6120 this.$element
6121 .addClass( 'oo-ui-fieldsetLayout' )
6122 .prepend( this.$icon, this.$label, this.$group );
6123 if ( $.isArray( config.items ) ) {
6124 this.addItems( config.items );
6125 }
6126 };
6127
6128 /* Setup */
6129
6130 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
6131 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconedElement );
6132 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabeledElement );
6133 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
6134
6135 /* Static Properties */
6136
6137 OO.ui.FieldsetLayout.static.tagName = 'div';
6138
6139 /**
6140 * Layout with an HTML form.
6141 *
6142 * @class
6143 * @extends OO.ui.Layout
6144 *
6145 * @constructor
6146 * @param {Object} [config] Configuration options
6147 */
6148 OO.ui.FormLayout = function OoUiFormLayout( config ) {
6149 // Configuration initialization
6150 config = config || {};
6151
6152 // Parent constructor
6153 OO.ui.FormLayout.super.call( this, config );
6154
6155 // Events
6156 this.$element.on( 'submit', OO.ui.bind( this.onFormSubmit, this ) );
6157
6158 // Initialization
6159 this.$element.addClass( 'oo-ui-formLayout' );
6160 };
6161
6162 /* Setup */
6163
6164 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
6165
6166 /* Events */
6167
6168 /**
6169 * @event submit
6170 */
6171
6172 /* Static Properties */
6173
6174 OO.ui.FormLayout.static.tagName = 'form';
6175
6176 /* Methods */
6177
6178 /**
6179 * Handle form submit events.
6180 *
6181 * @param {jQuery.Event} e Submit event
6182 * @fires submit
6183 */
6184 OO.ui.FormLayout.prototype.onFormSubmit = function () {
6185 this.emit( 'submit' );
6186 return false;
6187 };
6188
6189 /**
6190 * Layout made of proportionally sized columns and rows.
6191 *
6192 * @class
6193 * @extends OO.ui.Layout
6194 *
6195 * @constructor
6196 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
6197 * @param {Object} [config] Configuration options
6198 * @cfg {number[]} [widths] Widths of columns as ratios
6199 * @cfg {number[]} [heights] Heights of columns as ratios
6200 */
6201 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
6202 var i, len, widths;
6203
6204 // Config initialization
6205 config = config || {};
6206
6207 // Parent constructor
6208 OO.ui.GridLayout.super.call( this, config );
6209
6210 // Properties
6211 this.panels = [];
6212 this.widths = [];
6213 this.heights = [];
6214
6215 // Initialization
6216 this.$element.addClass( 'oo-ui-gridLayout' );
6217 for ( i = 0, len = panels.length; i < len; i++ ) {
6218 this.panels.push( panels[i] );
6219 this.$element.append( panels[i].$element );
6220 }
6221 if ( config.widths || config.heights ) {
6222 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
6223 } else {
6224 // Arrange in columns by default
6225 widths = [];
6226 for ( i = 0, len = this.panels.length; i < len; i++ ) {
6227 widths[i] = 1;
6228 }
6229 this.layout( widths, [ 1 ] );
6230 }
6231 };
6232
6233 /* Setup */
6234
6235 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
6236
6237 /* Events */
6238
6239 /**
6240 * @event layout
6241 */
6242
6243 /**
6244 * @event update
6245 */
6246
6247 /* Static Properties */
6248
6249 OO.ui.GridLayout.static.tagName = 'div';
6250
6251 /* Methods */
6252
6253 /**
6254 * Set grid dimensions.
6255 *
6256 * @param {number[]} widths Widths of columns as ratios
6257 * @param {number[]} heights Heights of rows as ratios
6258 * @fires layout
6259 * @throws {Error} If grid is not large enough to fit all panels
6260 */
6261 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
6262 var x, y,
6263 xd = 0,
6264 yd = 0,
6265 cols = widths.length,
6266 rows = heights.length;
6267
6268 // Verify grid is big enough to fit panels
6269 if ( cols * rows < this.panels.length ) {
6270 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
6271 }
6272
6273 // Sum up denominators
6274 for ( x = 0; x < cols; x++ ) {
6275 xd += widths[x];
6276 }
6277 for ( y = 0; y < rows; y++ ) {
6278 yd += heights[y];
6279 }
6280 // Store factors
6281 this.widths = [];
6282 this.heights = [];
6283 for ( x = 0; x < cols; x++ ) {
6284 this.widths[x] = widths[x] / xd;
6285 }
6286 for ( y = 0; y < rows; y++ ) {
6287 this.heights[y] = heights[y] / yd;
6288 }
6289 // Synchronize view
6290 this.update();
6291 this.emit( 'layout' );
6292 };
6293
6294 /**
6295 * Update panel positions and sizes.
6296 *
6297 * @fires update
6298 */
6299 OO.ui.GridLayout.prototype.update = function () {
6300 var x, y, panel,
6301 i = 0,
6302 left = 0,
6303 top = 0,
6304 dimensions,
6305 width = 0,
6306 height = 0,
6307 cols = this.widths.length,
6308 rows = this.heights.length;
6309
6310 for ( y = 0; y < rows; y++ ) {
6311 height = this.heights[y];
6312 for ( x = 0; x < cols; x++ ) {
6313 panel = this.panels[i];
6314 width = this.widths[x];
6315 dimensions = {
6316 'width': Math.round( width * 100 ) + '%',
6317 'height': Math.round( height * 100 ) + '%',
6318 'top': Math.round( top * 100 ) + '%',
6319 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
6320 'visibility': width === 0 || height === 0 ? 'hidden' : ''
6321 };
6322 // If RTL, reverse:
6323 if ( OO.ui.Element.getDir( this.$.context ) === 'rtl' ) {
6324 dimensions.right = Math.round( left * 100 ) + '%';
6325 } else {
6326 dimensions.left = Math.round( left * 100 ) + '%';
6327 }
6328 panel.$element.css( dimensions );
6329 i++;
6330 left += width;
6331 }
6332 top += height;
6333 left = 0;
6334 }
6335
6336 this.emit( 'update' );
6337 };
6338
6339 /**
6340 * Get a panel at a given position.
6341 *
6342 * The x and y position is affected by the current grid layout.
6343 *
6344 * @param {number} x Horizontal position
6345 * @param {number} y Vertical position
6346 * @return {OO.ui.PanelLayout} The panel at the given postion
6347 */
6348 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
6349 return this.panels[( x * this.widths.length ) + y];
6350 };
6351
6352 /**
6353 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
6354 *
6355 * @class
6356 * @extends OO.ui.Layout
6357 *
6358 * @constructor
6359 * @param {Object} [config] Configuration options
6360 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
6361 * @cfg {boolean} [padded=false] Pad the content from the edges
6362 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
6363 */
6364 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
6365 // Config initialization
6366 config = config || {};
6367
6368 // Parent constructor
6369 OO.ui.PanelLayout.super.call( this, config );
6370
6371 // Initialization
6372 this.$element.addClass( 'oo-ui-panelLayout' );
6373 if ( config.scrollable ) {
6374 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
6375 }
6376
6377 if ( config.padded ) {
6378 this.$element.addClass( 'oo-ui-panelLayout-padded' );
6379 }
6380
6381 if ( config.expanded === undefined || config.expanded ) {
6382 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
6383 }
6384 };
6385
6386 /* Setup */
6387
6388 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
6389
6390 /**
6391 * Page within an booklet layout.
6392 *
6393 * @class
6394 * @extends OO.ui.PanelLayout
6395 *
6396 * @constructor
6397 * @param {string} name Unique symbolic name of page
6398 * @param {Object} [config] Configuration options
6399 * @param {string} [outlineItem] Outline item widget
6400 */
6401 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
6402 // Configuration initialization
6403 config = $.extend( { 'scrollable': true }, config );
6404
6405 // Parent constructor
6406 OO.ui.PageLayout.super.call( this, config );
6407
6408 // Properties
6409 this.name = name;
6410 this.outlineItem = config.outlineItem || null;
6411 this.active = false;
6412
6413 // Initialization
6414 this.$element.addClass( 'oo-ui-pageLayout' );
6415 };
6416
6417 /* Setup */
6418
6419 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
6420
6421 /* Events */
6422
6423 /**
6424 * @event active
6425 * @param {boolean} active Page is active
6426 */
6427
6428 /* Methods */
6429
6430 /**
6431 * Get page name.
6432 *
6433 * @return {string} Symbolic name of page
6434 */
6435 OO.ui.PageLayout.prototype.getName = function () {
6436 return this.name;
6437 };
6438
6439 /**
6440 * Check if page is active.
6441 *
6442 * @return {boolean} Page is active
6443 */
6444 OO.ui.PageLayout.prototype.isActive = function () {
6445 return this.active;
6446 };
6447
6448 /**
6449 * Get outline item.
6450 *
6451 * @return {OO.ui.OutlineItemWidget|null} Outline item widget
6452 */
6453 OO.ui.PageLayout.prototype.getOutlineItem = function () {
6454 return this.outlineItem;
6455 };
6456
6457 /**
6458 * Set outline item.
6459 *
6460 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
6461 * outline item as desired; this method is called for setting (with an object) and unsetting
6462 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
6463 * operating on null instead of an OO.ui.OutlineItemWidget object.
6464 *
6465 * @param {OO.ui.OutlineItemWidget|null} outlineItem Outline item widget, null to clear
6466 * @chainable
6467 */
6468 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
6469 this.outlineItem = outlineItem || null;
6470 if ( outlineItem ) {
6471 this.setupOutlineItem();
6472 }
6473 return this;
6474 };
6475
6476 /**
6477 * Setup outline item.
6478 *
6479 * @localdoc Subclasses should override this method to adjust the outline item as desired.
6480 *
6481 * @param {OO.ui.OutlineItemWidget} outlineItem Outline item widget to setup
6482 * @chainable
6483 */
6484 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
6485 return this;
6486 };
6487
6488 /**
6489 * Set page active state.
6490 *
6491 * @param {boolean} Page is active
6492 * @fires active
6493 */
6494 OO.ui.PageLayout.prototype.setActive = function ( active ) {
6495 active = !!active;
6496
6497 if ( active !== this.active ) {
6498 this.active = active;
6499 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
6500 this.emit( 'active', this.active );
6501 }
6502 };
6503
6504 /**
6505 * Layout containing a series of mutually exclusive pages.
6506 *
6507 * @class
6508 * @extends OO.ui.PanelLayout
6509 * @mixins OO.ui.GroupElement
6510 *
6511 * @constructor
6512 * @param {Object} [config] Configuration options
6513 * @cfg {boolean} [continuous=false] Show all pages, one after another
6514 * @cfg {string} [icon=''] Symbolic icon name
6515 * @cfg {OO.ui.Layout[]} [items] Layouts to add
6516 */
6517 OO.ui.StackLayout = function OoUiStackLayout( config ) {
6518 // Config initialization
6519 config = $.extend( { 'scrollable': true }, config );
6520
6521 // Parent constructor
6522 OO.ui.StackLayout.super.call( this, config );
6523
6524 // Mixin constructors
6525 OO.ui.GroupElement.call( this, this.$element, config );
6526
6527 // Properties
6528 this.currentItem = null;
6529 this.continuous = !!config.continuous;
6530
6531 // Initialization
6532 this.$element.addClass( 'oo-ui-stackLayout' );
6533 if ( this.continuous ) {
6534 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
6535 }
6536 if ( $.isArray( config.items ) ) {
6537 this.addItems( config.items );
6538 }
6539 };
6540
6541 /* Setup */
6542
6543 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
6544 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
6545
6546 /* Events */
6547
6548 /**
6549 * @event set
6550 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
6551 */
6552
6553 /* Methods */
6554
6555 /**
6556 * Get the current item.
6557 *
6558 * @return {OO.ui.Layout|null}
6559 */
6560 OO.ui.StackLayout.prototype.getCurrentItem = function () {
6561 return this.currentItem;
6562 };
6563
6564 /**
6565 * Unset the current item.
6566 *
6567 * @private
6568 * @param {OO.ui.StackLayout} layout
6569 * @fires set
6570 */
6571 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
6572 var prevItem = this.currentItem;
6573 if ( prevItem === null ) {
6574 return;
6575 }
6576
6577 this.currentItem = null;
6578 this.emit( 'set', null );
6579 };
6580
6581 /**
6582 * Add items.
6583 *
6584 * Adding an existing item (by value) will move it.
6585 *
6586 * @param {OO.ui.Layout[]} items Items to add
6587 * @param {number} [index] Index to insert items after
6588 * @chainable
6589 */
6590 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
6591 // Mixin method
6592 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
6593
6594 if ( !this.currentItem && items.length ) {
6595 this.setItem( items[0] );
6596 }
6597
6598 return this;
6599 };
6600
6601 /**
6602 * Remove items.
6603 *
6604 * Items will be detached, not removed, so they can be used later.
6605 *
6606 * @param {OO.ui.Layout[]} items Items to remove
6607 * @chainable
6608 * @fires set
6609 */
6610 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
6611 // Mixin method
6612 OO.ui.GroupElement.prototype.removeItems.call( this, items );
6613
6614 if ( $.inArray( this.currentItem, items ) !== -1 ) {
6615 if ( this.items.length ) {
6616 this.setItem( this.items[0] );
6617 } else {
6618 this.unsetCurrentItem();
6619 }
6620 }
6621
6622 return this;
6623 };
6624
6625 /**
6626 * Clear all items.
6627 *
6628 * Items will be detached, not removed, so they can be used later.
6629 *
6630 * @chainable
6631 * @fires set
6632 */
6633 OO.ui.StackLayout.prototype.clearItems = function () {
6634 this.unsetCurrentItem();
6635 OO.ui.GroupElement.prototype.clearItems.call( this );
6636
6637 return this;
6638 };
6639
6640 /**
6641 * Show item.
6642 *
6643 * Any currently shown item will be hidden.
6644 *
6645 * FIXME: If the passed item to show has not been added in the items list, then
6646 * this method drops it and unsets the current item.
6647 *
6648 * @param {OO.ui.Layout} item Item to show
6649 * @chainable
6650 * @fires set
6651 */
6652 OO.ui.StackLayout.prototype.setItem = function ( item ) {
6653 var i, len;
6654
6655 if ( item !== this.currentItem ) {
6656 if ( !this.continuous ) {
6657 for ( i = 0, len = this.items.length; i < len; i++ ) {
6658 this.items[i].$element.css( 'display', '' );
6659 }
6660 }
6661 if ( $.inArray( item, this.items ) !== -1 ) {
6662 if ( !this.continuous ) {
6663 item.$element.css( 'display', 'block' );
6664 }
6665 this.currentItem = item;
6666 this.emit( 'set', item );
6667 } else {
6668 this.unsetCurrentItem();
6669 }
6670 }
6671
6672 return this;
6673 };
6674
6675 /**
6676 * Horizontal bar layout of tools as icon buttons.
6677 *
6678 * @class
6679 * @extends OO.ui.ToolGroup
6680 *
6681 * @constructor
6682 * @param {OO.ui.Toolbar} toolbar
6683 * @param {Object} [config] Configuration options
6684 */
6685 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
6686 // Parent constructor
6687 OO.ui.BarToolGroup.super.call( this, toolbar, config );
6688
6689 // Initialization
6690 this.$element.addClass( 'oo-ui-barToolGroup' );
6691 };
6692
6693 /* Setup */
6694
6695 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
6696
6697 /* Static Properties */
6698
6699 OO.ui.BarToolGroup.static.titleTooltips = true;
6700
6701 OO.ui.BarToolGroup.static.accelTooltips = true;
6702
6703 OO.ui.BarToolGroup.static.name = 'bar';
6704
6705 /**
6706 * Popup list of tools with an icon and optional label.
6707 *
6708 * @abstract
6709 * @class
6710 * @extends OO.ui.ToolGroup
6711 * @mixins OO.ui.IconedElement
6712 * @mixins OO.ui.IndicatedElement
6713 * @mixins OO.ui.LabeledElement
6714 * @mixins OO.ui.TitledElement
6715 * @mixins OO.ui.ClippableElement
6716 *
6717 * @constructor
6718 * @param {OO.ui.Toolbar} toolbar
6719 * @param {Object} [config] Configuration options
6720 * @cfg {string} [header] Text to display at the top of the pop-up
6721 */
6722 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
6723 // Configuration initialization
6724 config = config || {};
6725
6726 // Parent constructor
6727 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
6728
6729 // Mixin constructors
6730 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
6731 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
6732 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
6733 OO.ui.TitledElement.call( this, this.$element, config );
6734 OO.ui.ClippableElement.call( this, this.$group, config );
6735
6736 // Properties
6737 this.active = false;
6738 this.dragging = false;
6739 this.onBlurHandler = OO.ui.bind( this.onBlur, this );
6740 this.$handle = this.$( '<span>' );
6741
6742 // Events
6743 this.$handle.on( {
6744 'mousedown': OO.ui.bind( this.onHandleMouseDown, this ),
6745 'mouseup': OO.ui.bind( this.onHandleMouseUp, this )
6746 } );
6747
6748 // Initialization
6749 this.$handle
6750 .addClass( 'oo-ui-popupToolGroup-handle' )
6751 .append( this.$icon, this.$label, this.$indicator );
6752 // If the pop-up should have a header, add it to the top of the toolGroup.
6753 // Note: If this feature is useful for other widgets, we could abstract it into an
6754 // OO.ui.HeaderedElement mixin constructor.
6755 if ( config.header !== undefined ) {
6756 this.$group
6757 .prepend( this.$( '<span>' )
6758 .addClass( 'oo-ui-popupToolGroup-header' )
6759 .text( config.header )
6760 );
6761 }
6762 this.$element
6763 .addClass( 'oo-ui-popupToolGroup' )
6764 .prepend( this.$handle );
6765 };
6766
6767 /* Setup */
6768
6769 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
6770 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconedElement );
6771 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatedElement );
6772 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabeledElement );
6773 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
6774 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
6775
6776 /* Static Properties */
6777
6778 /* Methods */
6779
6780 /**
6781 * @inheritdoc
6782 */
6783 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
6784 // Parent method
6785 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
6786
6787 if ( this.isDisabled() && this.isElementAttached() ) {
6788 this.setActive( false );
6789 }
6790 };
6791
6792 /**
6793 * Handle focus being lost.
6794 *
6795 * The event is actually generated from a mouseup, so it is not a normal blur event object.
6796 *
6797 * @param {jQuery.Event} e Mouse up event
6798 */
6799 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
6800 // Only deactivate when clicking outside the dropdown element
6801 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
6802 this.setActive( false );
6803 }
6804 };
6805
6806 /**
6807 * @inheritdoc
6808 */
6809 OO.ui.PopupToolGroup.prototype.onMouseUp = function ( e ) {
6810 if ( !this.isDisabled() && e.which === 1 ) {
6811 this.setActive( false );
6812 }
6813 return OO.ui.PopupToolGroup.super.prototype.onMouseUp.call( this, e );
6814 };
6815
6816 /**
6817 * Handle mouse up events.
6818 *
6819 * @param {jQuery.Event} e Mouse up event
6820 */
6821 OO.ui.PopupToolGroup.prototype.onHandleMouseUp = function () {
6822 return false;
6823 };
6824
6825 /**
6826 * Handle mouse down events.
6827 *
6828 * @param {jQuery.Event} e Mouse down event
6829 */
6830 OO.ui.PopupToolGroup.prototype.onHandleMouseDown = function ( e ) {
6831 if ( !this.isDisabled() && e.which === 1 ) {
6832 this.setActive( !this.active );
6833 }
6834 return false;
6835 };
6836
6837 /**
6838 * Switch into active mode.
6839 *
6840 * When active, mouseup events anywhere in the document will trigger deactivation.
6841 */
6842 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
6843 value = !!value;
6844 if ( this.active !== value ) {
6845 this.active = value;
6846 if ( value ) {
6847 this.setClipping( true );
6848 this.$element.addClass( 'oo-ui-popupToolGroup-active' );
6849 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
6850 } else {
6851 this.setClipping( false );
6852 this.$element.removeClass( 'oo-ui-popupToolGroup-active' );
6853 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
6854 }
6855 }
6856 };
6857
6858 /**
6859 * Drop down list layout of tools as labeled icon buttons.
6860 *
6861 * @class
6862 * @extends OO.ui.PopupToolGroup
6863 *
6864 * @constructor
6865 * @param {OO.ui.Toolbar} toolbar
6866 * @param {Object} [config] Configuration options
6867 */
6868 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
6869 // Parent constructor
6870 OO.ui.ListToolGroup.super.call( this, toolbar, config );
6871
6872 // Initialization
6873 this.$element.addClass( 'oo-ui-listToolGroup' );
6874 };
6875
6876 /* Setup */
6877
6878 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
6879
6880 /* Static Properties */
6881
6882 OO.ui.ListToolGroup.static.accelTooltips = true;
6883
6884 OO.ui.ListToolGroup.static.name = 'list';
6885
6886 /**
6887 * Drop down menu layout of tools as selectable menu items.
6888 *
6889 * @class
6890 * @extends OO.ui.PopupToolGroup
6891 *
6892 * @constructor
6893 * @param {OO.ui.Toolbar} toolbar
6894 * @param {Object} [config] Configuration options
6895 */
6896 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
6897 // Configuration initialization
6898 config = config || {};
6899
6900 // Parent constructor
6901 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
6902
6903 // Events
6904 this.toolbar.connect( this, { 'updateState': 'onUpdateState' } );
6905
6906 // Initialization
6907 this.$element.addClass( 'oo-ui-menuToolGroup' );
6908 };
6909
6910 /* Setup */
6911
6912 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
6913
6914 /* Static Properties */
6915
6916 OO.ui.MenuToolGroup.static.accelTooltips = true;
6917
6918 OO.ui.MenuToolGroup.static.name = 'menu';
6919
6920 /* Methods */
6921
6922 /**
6923 * Handle the toolbar state being updated.
6924 *
6925 * When the state changes, the title of each active item in the menu will be joined together and
6926 * used as a label for the group. The label will be empty if none of the items are active.
6927 */
6928 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
6929 var name,
6930 labelTexts = [];
6931
6932 for ( name in this.tools ) {
6933 if ( this.tools[name].isActive() ) {
6934 labelTexts.push( this.tools[name].getTitle() );
6935 }
6936 }
6937
6938 this.setLabel( labelTexts.join( ', ' ) || ' ' );
6939 };
6940
6941 /**
6942 * Tool that shows a popup when selected.
6943 *
6944 * @abstract
6945 * @class
6946 * @extends OO.ui.Tool
6947 * @mixins OO.ui.PopuppableElement
6948 *
6949 * @constructor
6950 * @param {OO.ui.Toolbar} toolbar
6951 * @param {Object} [config] Configuration options
6952 */
6953 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
6954 // Parent constructor
6955 OO.ui.PopupTool.super.call( this, toolbar, config );
6956
6957 // Mixin constructors
6958 OO.ui.PopuppableElement.call( this, config );
6959
6960 // Initialization
6961 this.$element
6962 .addClass( 'oo-ui-popupTool' )
6963 .append( this.popup.$element );
6964 };
6965
6966 /* Setup */
6967
6968 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
6969 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopuppableElement );
6970
6971 /* Methods */
6972
6973 /**
6974 * Handle the tool being selected.
6975 *
6976 * @inheritdoc
6977 */
6978 OO.ui.PopupTool.prototype.onSelect = function () {
6979 if ( !this.isDisabled() ) {
6980 this.popup.toggle();
6981 }
6982 this.setActive( false );
6983 return false;
6984 };
6985
6986 /**
6987 * Handle the toolbar state being updated.
6988 *
6989 * @inheritdoc
6990 */
6991 OO.ui.PopupTool.prototype.onUpdateState = function () {
6992 this.setActive( false );
6993 };
6994
6995 /**
6996 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
6997 *
6998 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
6999 *
7000 * @abstract
7001 * @class
7002 * @extends OO.ui.GroupElement
7003 *
7004 * @constructor
7005 * @param {jQuery} $group Container node, assigned to #$group
7006 * @param {Object} [config] Configuration options
7007 */
7008 OO.ui.GroupWidget = function OoUiGroupWidget( $element, config ) {
7009 // Parent constructor
7010 OO.ui.GroupWidget.super.call( this, $element, config );
7011 };
7012
7013 /* Setup */
7014
7015 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
7016
7017 /* Methods */
7018
7019 /**
7020 * Set the disabled state of the widget.
7021 *
7022 * This will also update the disabled state of child widgets.
7023 *
7024 * @param {boolean} disabled Disable widget
7025 * @chainable
7026 */
7027 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
7028 var i, len;
7029
7030 // Parent method
7031 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
7032 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
7033
7034 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
7035 if ( this.items ) {
7036 for ( i = 0, len = this.items.length; i < len; i++ ) {
7037 this.items[i].updateDisabled();
7038 }
7039 }
7040
7041 return this;
7042 };
7043
7044 /**
7045 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
7046 *
7047 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
7048 * allows bidrectional communication.
7049 *
7050 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
7051 *
7052 * @abstract
7053 * @class
7054 *
7055 * @constructor
7056 */
7057 OO.ui.ItemWidget = function OoUiItemWidget() {
7058 //
7059 };
7060
7061 /* Methods */
7062
7063 /**
7064 * Check if widget is disabled.
7065 *
7066 * Checks parent if present, making disabled state inheritable.
7067 *
7068 * @return {boolean} Widget is disabled
7069 */
7070 OO.ui.ItemWidget.prototype.isDisabled = function () {
7071 return this.disabled ||
7072 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
7073 };
7074
7075 /**
7076 * Set group element is in.
7077 *
7078 * @param {OO.ui.GroupElement|null} group Group element, null if none
7079 * @chainable
7080 */
7081 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
7082 // Parent method
7083 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
7084 OO.ui.Element.prototype.setElementGroup.call( this, group );
7085
7086 // Initialize item disabled states
7087 this.updateDisabled();
7088
7089 return this;
7090 };
7091
7092 /**
7093 * Mixin that adds a menu showing suggested values for a text input.
7094 *
7095 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
7096 *
7097 * @class
7098 * @abstract
7099 *
7100 * @constructor
7101 * @param {OO.ui.TextInputWidget} input Input widget
7102 * @param {Object} [config] Configuration options
7103 * @cfg {jQuery} [$overlay=this.$( 'body' )] Overlay layer
7104 */
7105 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
7106 // Config intialization
7107 config = config || {};
7108
7109 // Properties
7110 this.lookupInput = input;
7111 this.$overlay = config.$overlay || this.$( 'body,.oo-ui-window-overlay' ).last();
7112 this.lookupMenu = new OO.ui.TextInputMenuWidget( this, {
7113 '$': OO.ui.Element.getJQuery( this.$overlay ),
7114 'input': this.lookupInput,
7115 '$container': config.$container
7116 } );
7117 this.lookupCache = {};
7118 this.lookupQuery = null;
7119 this.lookupRequest = null;
7120 this.populating = false;
7121
7122 // Events
7123 this.$overlay.append( this.lookupMenu.$element );
7124
7125 this.lookupInput.$input.on( {
7126 'focus': OO.ui.bind( this.onLookupInputFocus, this ),
7127 'blur': OO.ui.bind( this.onLookupInputBlur, this ),
7128 'mousedown': OO.ui.bind( this.onLookupInputMouseDown, this )
7129 } );
7130 this.lookupInput.connect( this, { 'change': 'onLookupInputChange' } );
7131
7132 // Initialization
7133 this.$element.addClass( 'oo-ui-lookupWidget' );
7134 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
7135 };
7136
7137 /* Methods */
7138
7139 /**
7140 * Handle input focus event.
7141 *
7142 * @param {jQuery.Event} e Input focus event
7143 */
7144 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
7145 this.openLookupMenu();
7146 };
7147
7148 /**
7149 * Handle input blur event.
7150 *
7151 * @param {jQuery.Event} e Input blur event
7152 */
7153 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
7154 this.lookupMenu.toggle( false );
7155 };
7156
7157 /**
7158 * Handle input mouse down event.
7159 *
7160 * @param {jQuery.Event} e Input mouse down event
7161 */
7162 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
7163 this.openLookupMenu();
7164 };
7165
7166 /**
7167 * Handle input change event.
7168 *
7169 * @param {string} value New input value
7170 */
7171 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
7172 this.openLookupMenu();
7173 };
7174
7175 /**
7176 * Get lookup menu.
7177 *
7178 * @return {OO.ui.TextInputMenuWidget}
7179 */
7180 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
7181 return this.lookupMenu;
7182 };
7183
7184 /**
7185 * Open the menu.
7186 *
7187 * @chainable
7188 */
7189 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
7190 var value = this.lookupInput.getValue();
7191
7192 if ( this.lookupMenu.$input.is( ':focus' ) && $.trim( value ) !== '' ) {
7193 this.populateLookupMenu();
7194 this.lookupMenu.toggle( true );
7195 } else {
7196 this.lookupMenu
7197 .clearItems()
7198 .toggle( false );
7199 }
7200
7201 return this;
7202 };
7203
7204 /**
7205 * Populate lookup menu with current information.
7206 *
7207 * @chainable
7208 */
7209 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
7210 var widget = this;
7211
7212 if ( !this.populating ) {
7213 this.populating = true;
7214 this.getLookupMenuItems()
7215 .done( function ( items ) {
7216 widget.lookupMenu.clearItems();
7217 if ( items.length ) {
7218 widget.lookupMenu
7219 .addItems( items )
7220 .toggle( true );
7221 widget.initializeLookupMenuSelection();
7222 widget.openLookupMenu();
7223 } else {
7224 widget.lookupMenu.toggle( true );
7225 }
7226 widget.populating = false;
7227 } )
7228 .fail( function () {
7229 widget.lookupMenu.clearItems();
7230 widget.populating = false;
7231 } );
7232 }
7233
7234 return this;
7235 };
7236
7237 /**
7238 * Set selection in the lookup menu with current information.
7239 *
7240 * @chainable
7241 */
7242 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
7243 if ( !this.lookupMenu.getSelectedItem() ) {
7244 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
7245 }
7246 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
7247 };
7248
7249 /**
7250 * Get lookup menu items for the current query.
7251 *
7252 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
7253 * of the done event
7254 */
7255 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
7256 var widget = this,
7257 value = this.lookupInput.getValue(),
7258 deferred = $.Deferred();
7259
7260 if ( value && value !== this.lookupQuery ) {
7261 // Abort current request if query has changed
7262 if ( this.lookupRequest ) {
7263 this.lookupRequest.abort();
7264 this.lookupQuery = null;
7265 this.lookupRequest = null;
7266 }
7267 if ( value in this.lookupCache ) {
7268 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
7269 } else {
7270 this.lookupQuery = value;
7271 this.lookupRequest = this.getLookupRequest()
7272 .always( function () {
7273 widget.lookupQuery = null;
7274 widget.lookupRequest = null;
7275 } )
7276 .done( function ( data ) {
7277 widget.lookupCache[value] = widget.getLookupCacheItemFromData( data );
7278 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[value] ) );
7279 } )
7280 .fail( function () {
7281 deferred.reject();
7282 } );
7283 this.pushPending();
7284 this.lookupRequest.always( function () {
7285 widget.popPending();
7286 } );
7287 }
7288 }
7289 return deferred.promise();
7290 };
7291
7292 /**
7293 * Get a new request object of the current lookup query value.
7294 *
7295 * @abstract
7296 * @return {jqXHR} jQuery AJAX object, or promise object with an .abort() method
7297 */
7298 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
7299 // Stub, implemented in subclass
7300 return null;
7301 };
7302
7303 /**
7304 * Handle successful lookup request.
7305 *
7306 * Overriding methods should call #populateLookupMenu when results are available and cache results
7307 * for future lookups in #lookupCache as an array of #OO.ui.MenuItemWidget objects.
7308 *
7309 * @abstract
7310 * @param {Mixed} data Response from server
7311 */
7312 OO.ui.LookupInputWidget.prototype.onLookupRequestDone = function () {
7313 // Stub, implemented in subclass
7314 };
7315
7316 /**
7317 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
7318 *
7319 * @abstract
7320 * @param {Mixed} data Cached result data, usually an array
7321 * @return {OO.ui.MenuItemWidget[]} Menu items
7322 */
7323 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
7324 // Stub, implemented in subclass
7325 return [];
7326 };
7327
7328 /**
7329 * Set of controls for an OO.ui.OutlineWidget.
7330 *
7331 * Controls include moving items up and down, removing items, and adding different kinds of items.
7332 *
7333 * @class
7334 * @extends OO.ui.Widget
7335 * @mixins OO.ui.GroupElement
7336 * @mixins OO.ui.IconedElement
7337 *
7338 * @constructor
7339 * @param {OO.ui.OutlineWidget} outline Outline to control
7340 * @param {Object} [config] Configuration options
7341 */
7342 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
7343 // Configuration initialization
7344 config = $.extend( { 'icon': 'add-item' }, config );
7345
7346 // Parent constructor
7347 OO.ui.OutlineControlsWidget.super.call( this, config );
7348
7349 // Mixin constructors
7350 OO.ui.GroupElement.call( this, this.$( '<div>' ), config );
7351 OO.ui.IconedElement.call( this, this.$( '<div>' ), config );
7352
7353 // Properties
7354 this.outline = outline;
7355 this.$movers = this.$( '<div>' );
7356 this.upButton = new OO.ui.ButtonWidget( {
7357 '$': this.$,
7358 'framed': false,
7359 'icon': 'collapse',
7360 'title': OO.ui.msg( 'ooui-outline-control-move-up' )
7361 } );
7362 this.downButton = new OO.ui.ButtonWidget( {
7363 '$': this.$,
7364 'framed': false,
7365 'icon': 'expand',
7366 'title': OO.ui.msg( 'ooui-outline-control-move-down' )
7367 } );
7368 this.removeButton = new OO.ui.ButtonWidget( {
7369 '$': this.$,
7370 'framed': false,
7371 'icon': 'remove',
7372 'title': OO.ui.msg( 'ooui-outline-control-remove' )
7373 } );
7374
7375 // Events
7376 outline.connect( this, {
7377 'select': 'onOutlineChange',
7378 'add': 'onOutlineChange',
7379 'remove': 'onOutlineChange'
7380 } );
7381 this.upButton.connect( this, { 'click': [ 'emit', 'move', -1 ] } );
7382 this.downButton.connect( this, { 'click': [ 'emit', 'move', 1 ] } );
7383 this.removeButton.connect( this, { 'click': [ 'emit', 'remove' ] } );
7384
7385 // Initialization
7386 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
7387 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
7388 this.$movers
7389 .addClass( 'oo-ui-outlineControlsWidget-movers' )
7390 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
7391 this.$element.append( this.$icon, this.$group, this.$movers );
7392 };
7393
7394 /* Setup */
7395
7396 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
7397 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
7398 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconedElement );
7399
7400 /* Events */
7401
7402 /**
7403 * @event move
7404 * @param {number} places Number of places to move
7405 */
7406
7407 /**
7408 * @event remove
7409 */
7410
7411 /* Methods */
7412
7413 /**
7414 * Handle outline change events.
7415 */
7416 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
7417 var i, len, firstMovable, lastMovable,
7418 items = this.outline.getItems(),
7419 selectedItem = this.outline.getSelectedItem(),
7420 movable = selectedItem && selectedItem.isMovable(),
7421 removable = selectedItem && selectedItem.isRemovable();
7422
7423 if ( movable ) {
7424 i = -1;
7425 len = items.length;
7426 while ( ++i < len ) {
7427 if ( items[i].isMovable() ) {
7428 firstMovable = items[i];
7429 break;
7430 }
7431 }
7432 i = len;
7433 while ( i-- ) {
7434 if ( items[i].isMovable() ) {
7435 lastMovable = items[i];
7436 break;
7437 }
7438 }
7439 }
7440 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
7441 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
7442 this.removeButton.setDisabled( !removable );
7443 };
7444
7445 /**
7446 * Mixin for widgets with a boolean on/off state.
7447 *
7448 * @abstract
7449 * @class
7450 *
7451 * @constructor
7452 * @param {Object} [config] Configuration options
7453 * @cfg {boolean} [value=false] Initial value
7454 */
7455 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
7456 // Configuration initialization
7457 config = config || {};
7458
7459 // Properties
7460 this.value = null;
7461
7462 // Initialization
7463 this.$element.addClass( 'oo-ui-toggleWidget' );
7464 this.setValue( !!config.value );
7465 };
7466
7467 /* Events */
7468
7469 /**
7470 * @event change
7471 * @param {boolean} value Changed value
7472 */
7473
7474 /* Methods */
7475
7476 /**
7477 * Get the value of the toggle.
7478 *
7479 * @return {boolean}
7480 */
7481 OO.ui.ToggleWidget.prototype.getValue = function () {
7482 return this.value;
7483 };
7484
7485 /**
7486 * Set the value of the toggle.
7487 *
7488 * @param {boolean} value New value
7489 * @fires change
7490 * @chainable
7491 */
7492 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
7493 value = !!value;
7494 if ( this.value !== value ) {
7495 this.value = value;
7496 this.emit( 'change', value );
7497 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
7498 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
7499 }
7500 return this;
7501 };
7502
7503 /**
7504 * Group widget for multiple related buttons.
7505 *
7506 * Use together with OO.ui.ButtonWidget.
7507 *
7508 * @class
7509 * @extends OO.ui.Widget
7510 * @mixins OO.ui.GroupElement
7511 *
7512 * @constructor
7513 * @param {Object} [config] Configuration options
7514 * @cfg {OO.ui.ButtonWidget} [items] Buttons to add
7515 */
7516 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
7517 // Parent constructor
7518 OO.ui.ButtonGroupWidget.super.call( this, config );
7519
7520 // Mixin constructors
7521 OO.ui.GroupElement.call( this, this.$element, config );
7522
7523 // Initialization
7524 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
7525 if ( $.isArray( config.items ) ) {
7526 this.addItems( config.items );
7527 }
7528 };
7529
7530 /* Setup */
7531
7532 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
7533 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
7534
7535 /**
7536 * Generic widget for buttons.
7537 *
7538 * @class
7539 * @extends OO.ui.Widget
7540 * @mixins OO.ui.ButtonedElement
7541 * @mixins OO.ui.IconedElement
7542 * @mixins OO.ui.IndicatedElement
7543 * @mixins OO.ui.LabeledElement
7544 * @mixins OO.ui.TitledElement
7545 * @mixins OO.ui.FlaggableElement
7546 *
7547 * @constructor
7548 * @param {Object} [config] Configuration options
7549 * @cfg {string} [href] Hyperlink to visit when clicked
7550 * @cfg {string} [target] Target to open hyperlink in
7551 */
7552 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
7553 // Configuration initialization
7554 config = $.extend( { 'target': '_blank' }, config );
7555
7556 // Parent constructor
7557 OO.ui.ButtonWidget.super.call( this, config );
7558
7559 // Mixin constructors
7560 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
7561 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
7562 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
7563 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
7564 OO.ui.TitledElement.call( this, this.$button, config );
7565 OO.ui.FlaggableElement.call( this, config );
7566
7567 // Properties
7568 this.href = null;
7569 this.target = null;
7570 this.isHyperlink = false;
7571
7572 // Events
7573 this.$button.on( {
7574 'click': OO.ui.bind( this.onClick, this ),
7575 'keypress': OO.ui.bind( this.onKeyPress, this )
7576 } );
7577
7578 // Initialization
7579 this.$button.append( this.$icon, this.$label, this.$indicator );
7580 this.$element
7581 .addClass( 'oo-ui-buttonWidget' )
7582 .append( this.$button );
7583 this.setHref( config.href );
7584 this.setTarget( config.target );
7585 };
7586
7587 /* Setup */
7588
7589 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
7590 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonedElement );
7591 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconedElement );
7592 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatedElement );
7593 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabeledElement );
7594 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
7595 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggableElement );
7596
7597 /* Events */
7598
7599 /**
7600 * @event click
7601 */
7602
7603 /* Methods */
7604
7605 /**
7606 * Handles mouse click events.
7607 *
7608 * @param {jQuery.Event} e Mouse click event
7609 * @fires click
7610 */
7611 OO.ui.ButtonWidget.prototype.onClick = function () {
7612 if ( !this.isDisabled() ) {
7613 this.emit( 'click' );
7614 if ( this.isHyperlink ) {
7615 return true;
7616 }
7617 }
7618 return false;
7619 };
7620
7621 /**
7622 * Handles keypress events.
7623 *
7624 * @param {jQuery.Event} e Keypress event
7625 * @fires click
7626 */
7627 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
7628 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
7629 this.onClick();
7630 if ( this.isHyperlink ) {
7631 return true;
7632 }
7633 }
7634 return false;
7635 };
7636
7637 /**
7638 * Get hyperlink location.
7639 *
7640 * @return {string} Hyperlink location
7641 */
7642 OO.ui.ButtonWidget.prototype.getHref = function () {
7643 return this.href;
7644 };
7645
7646 /**
7647 * Get hyperlink target.
7648 *
7649 * @return {string} Hyperlink target
7650 */
7651 OO.ui.ButtonWidget.prototype.getTarget = function () {
7652 return this.target;
7653 };
7654
7655 /**
7656 * Set hyperlink location.
7657 *
7658 * @param {string|null} href Hyperlink location, null to remove
7659 */
7660 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
7661 href = typeof href === 'string' ? href : null;
7662
7663 if ( href !== this.href ) {
7664 this.href = href;
7665 if ( href !== null ) {
7666 this.$button.attr( 'href', href );
7667 this.isHyperlink = true;
7668 } else {
7669 this.$button.removeAttr( 'href' );
7670 this.isHyperlink = false;
7671 }
7672 }
7673
7674 return this;
7675 };
7676
7677 /**
7678 * Set hyperlink target.
7679 *
7680 * @param {string|null} target Hyperlink target, null to remove
7681 */
7682 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
7683 target = typeof target === 'string' ? target : null;
7684
7685 if ( target !== this.target ) {
7686 this.target = target;
7687 if ( target !== null ) {
7688 this.$button.attr( 'target', target );
7689 } else {
7690 this.$button.removeAttr( 'target' );
7691 }
7692 }
7693
7694 return this;
7695 };
7696
7697 /**
7698 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
7699 *
7700 * @class
7701 * @extends OO.ui.ButtonWidget
7702 *
7703 * @constructor
7704 * @param {Object} [config] Configuration options
7705 * @cfg {string} [action] Symbolic action name
7706 * @cfg {string[]} [modes] Symbolic mode names
7707 */
7708 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
7709 // Config intialization
7710 config = $.extend( { 'framed': false }, config );
7711
7712 // Parent constructor
7713 OO.ui.ActionWidget.super.call( this, config );
7714
7715 // Properties
7716 this.action = config.action || '';
7717 this.modes = config.modes || [];
7718 this.width = 0;
7719 this.height = 0;
7720
7721 // Initialization
7722 this.$element.addClass( 'oo-ui-actionWidget' );
7723 };
7724
7725 /* Setup */
7726
7727 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
7728
7729 /* Events */
7730
7731 /**
7732 * @event resize
7733 */
7734
7735 /* Methods */
7736
7737 /**
7738 * Check if action is available in a certain mode.
7739 *
7740 * @param {string} mode Name of mode
7741 * @return {boolean} Has mode
7742 */
7743 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
7744 return this.modes.indexOf( mode ) !== -1;
7745 };
7746
7747 /**
7748 * Get symbolic action name.
7749 *
7750 * @return {string}
7751 */
7752 OO.ui.ActionWidget.prototype.getAction = function () {
7753 return this.action;
7754 };
7755
7756 /**
7757 * Get symbolic action name.
7758 *
7759 * @return {string}
7760 */
7761 OO.ui.ActionWidget.prototype.getModes = function () {
7762 return this.modes.slice();
7763 };
7764
7765 /**
7766 * Emit a resize event if the size has changed.
7767 *
7768 * @chainable
7769 */
7770 OO.ui.ActionWidget.prototype.propagateResize = function () {
7771 var width, height;
7772
7773 if ( this.isElementAttached() ) {
7774 width = this.$element.width();
7775 height = this.$element.height();
7776
7777 if ( width !== this.width || height !== this.height ) {
7778 this.width = width;
7779 this.height = height;
7780 this.emit( 'resize' );
7781 }
7782 }
7783
7784 return this;
7785 };
7786
7787 /**
7788 * @inheritdoc
7789 */
7790 OO.ui.ActionWidget.prototype.setIcon = function () {
7791 // Mixin method
7792 OO.ui.IconedElement.prototype.setIcon.apply( this, arguments );
7793 this.propagateResize();
7794
7795 return this;
7796 };
7797
7798 /**
7799 * @inheritdoc
7800 */
7801 OO.ui.ActionWidget.prototype.setLabel = function () {
7802 // Mixin method
7803 OO.ui.LabeledElement.prototype.setLabel.apply( this, arguments );
7804 this.propagateResize();
7805
7806 return this;
7807 };
7808
7809 /**
7810 * @inheritdoc
7811 */
7812 OO.ui.ActionWidget.prototype.setFlags = function () {
7813 // Mixin method
7814 OO.ui.FlaggableElement.prototype.setFlags.apply( this, arguments );
7815 this.propagateResize();
7816
7817 return this;
7818 };
7819
7820 /**
7821 * @inheritdoc
7822 */
7823 OO.ui.ActionWidget.prototype.clearFlags = function () {
7824 // Mixin method
7825 OO.ui.FlaggableElement.prototype.clearFlags.apply( this, arguments );
7826 this.propagateResize();
7827
7828 return this;
7829 };
7830
7831 /**
7832 * Toggle visibility of button.
7833 *
7834 * @param {boolean} [show] Show button, omit to toggle visibility
7835 * @chainable
7836 */
7837 OO.ui.ActionWidget.prototype.toggle = function () {
7838 // Parent method
7839 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
7840 this.propagateResize();
7841
7842 return this;
7843 };
7844
7845 /**
7846 * Button that shows and hides a popup.
7847 *
7848 * @class
7849 * @extends OO.ui.ButtonWidget
7850 * @mixins OO.ui.PopuppableElement
7851 *
7852 * @constructor
7853 * @param {Object} [config] Configuration options
7854 */
7855 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
7856 // Parent constructor
7857 OO.ui.PopupButtonWidget.super.call( this, config );
7858
7859 // Mixin constructors
7860 OO.ui.PopuppableElement.call( this, config );
7861
7862 // Initialization
7863 this.$element
7864 .addClass( 'oo-ui-popupButtonWidget' )
7865 .append( this.popup.$element );
7866 };
7867
7868 /* Setup */
7869
7870 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
7871 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopuppableElement );
7872
7873 /* Methods */
7874
7875 /**
7876 * Handles mouse click events.
7877 *
7878 * @param {jQuery.Event} e Mouse click event
7879 */
7880 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
7881 // Skip clicks within the popup
7882 if ( $.contains( this.popup.$element[0], e.target ) ) {
7883 return;
7884 }
7885
7886 if ( !this.isDisabled() ) {
7887 this.popup.toggle();
7888 // Parent method
7889 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
7890 }
7891 return false;
7892 };
7893
7894 /**
7895 * Button that toggles on and off.
7896 *
7897 * @class
7898 * @extends OO.ui.ButtonWidget
7899 * @mixins OO.ui.ToggleWidget
7900 *
7901 * @constructor
7902 * @param {Object} [config] Configuration options
7903 * @cfg {boolean} [value=false] Initial value
7904 */
7905 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
7906 // Configuration initialization
7907 config = config || {};
7908
7909 // Parent constructor
7910 OO.ui.ToggleButtonWidget.super.call( this, config );
7911
7912 // Mixin constructors
7913 OO.ui.ToggleWidget.call( this, config );
7914
7915 // Initialization
7916 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
7917 };
7918
7919 /* Setup */
7920
7921 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
7922 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
7923
7924 /* Methods */
7925
7926 /**
7927 * @inheritdoc
7928 */
7929 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
7930 if ( !this.isDisabled() ) {
7931 this.setValue( !this.value );
7932 }
7933
7934 // Parent method
7935 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
7936 };
7937
7938 /**
7939 * @inheritdoc
7940 */
7941 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
7942 value = !!value;
7943 if ( value !== this.value ) {
7944 this.setActive( value );
7945 }
7946
7947 // Parent method (from mixin)
7948 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
7949
7950 return this;
7951 };
7952
7953 /**
7954 * Icon widget.
7955 *
7956 * @class
7957 * @extends OO.ui.Widget
7958 * @mixins OO.ui.IconedElement
7959 * @mixins OO.ui.TitledElement
7960 *
7961 * @constructor
7962 * @param {Object} [config] Configuration options
7963 */
7964 OO.ui.IconWidget = function OoUiIconWidget( config ) {
7965 // Config intialization
7966 config = config || {};
7967
7968 // Parent constructor
7969 OO.ui.IconWidget.super.call( this, config );
7970
7971 // Mixin constructors
7972 OO.ui.IconedElement.call( this, this.$element, config );
7973 OO.ui.TitledElement.call( this, this.$element, config );
7974
7975 // Initialization
7976 this.$element.addClass( 'oo-ui-iconWidget' );
7977 };
7978
7979 /* Setup */
7980
7981 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
7982 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconedElement );
7983 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
7984
7985 /* Static Properties */
7986
7987 OO.ui.IconWidget.static.tagName = 'span';
7988
7989 /**
7990 * Indicator widget.
7991 *
7992 * See OO.ui.IndicatedElement for more information.
7993 *
7994 * @class
7995 * @extends OO.ui.Widget
7996 * @mixins OO.ui.IndicatedElement
7997 * @mixins OO.ui.TitledElement
7998 *
7999 * @constructor
8000 * @param {Object} [config] Configuration options
8001 */
8002 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
8003 // Config intialization
8004 config = config || {};
8005
8006 // Parent constructor
8007 OO.ui.IndicatorWidget.super.call( this, config );
8008
8009 // Mixin constructors
8010 OO.ui.IndicatedElement.call( this, this.$element, config );
8011 OO.ui.TitledElement.call( this, this.$element, config );
8012
8013 // Initialization
8014 this.$element.addClass( 'oo-ui-indicatorWidget' );
8015 };
8016
8017 /* Setup */
8018
8019 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
8020 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatedElement );
8021 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
8022
8023 /* Static Properties */
8024
8025 OO.ui.IndicatorWidget.static.tagName = 'span';
8026
8027 /**
8028 * Inline menu of options.
8029 *
8030 * Inline menus provide a control for accessing a menu and compose a menu within the widget, which
8031 * can be accessed using the #getMenu method.
8032 *
8033 * Use with OO.ui.MenuOptionWidget.
8034 *
8035 * @class
8036 * @extends OO.ui.Widget
8037 * @mixins OO.ui.IconedElement
8038 * @mixins OO.ui.IndicatedElement
8039 * @mixins OO.ui.LabeledElement
8040 * @mixins OO.ui.TitledElement
8041 *
8042 * @constructor
8043 * @param {Object} [config] Configuration options
8044 * @cfg {Object} [menu] Configuration options to pass to menu widget
8045 */
8046 OO.ui.InlineMenuWidget = function OoUiInlineMenuWidget( config ) {
8047 // Configuration initialization
8048 config = $.extend( { 'indicator': 'down' }, config );
8049
8050 // Parent constructor
8051 OO.ui.InlineMenuWidget.super.call( this, config );
8052
8053 // Mixin constructors
8054 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
8055 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
8056 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
8057 OO.ui.TitledElement.call( this, this.$label, config );
8058
8059 // Properties
8060 this.menu = new OO.ui.MenuWidget( $.extend( { '$': this.$, 'widget': this }, config.menu ) );
8061 this.$handle = this.$( '<span>' );
8062
8063 // Events
8064 this.$element.on( { 'click': OO.ui.bind( this.onClick, this ) } );
8065 this.menu.connect( this, { 'select': 'onMenuSelect' } );
8066
8067 // Initialization
8068 this.$handle
8069 .addClass( 'oo-ui-inlineMenuWidget-handle' )
8070 .append( this.$icon, this.$label, this.$indicator );
8071 this.$element
8072 .addClass( 'oo-ui-inlineMenuWidget' )
8073 .append( this.$handle, this.menu.$element );
8074 };
8075
8076 /* Setup */
8077
8078 OO.inheritClass( OO.ui.InlineMenuWidget, OO.ui.Widget );
8079 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IconedElement );
8080 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.IndicatedElement );
8081 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.LabeledElement );
8082 OO.mixinClass( OO.ui.InlineMenuWidget, OO.ui.TitledElement );
8083
8084 /* Methods */
8085
8086 /**
8087 * Get the menu.
8088 *
8089 * @return {OO.ui.MenuWidget} Menu of widget
8090 */
8091 OO.ui.InlineMenuWidget.prototype.getMenu = function () {
8092 return this.menu;
8093 };
8094
8095 /**
8096 * Handles menu select events.
8097 *
8098 * @param {OO.ui.MenuItemWidget} item Selected menu item
8099 */
8100 OO.ui.InlineMenuWidget.prototype.onMenuSelect = function ( item ) {
8101 var selectedLabel;
8102
8103 if ( !item ) {
8104 return;
8105 }
8106
8107 selectedLabel = item.getLabel();
8108
8109 // If the label is a DOM element, clone it, because setLabel will append() it
8110 if ( selectedLabel instanceof jQuery ) {
8111 selectedLabel = selectedLabel.clone();
8112 }
8113
8114 this.setLabel( selectedLabel );
8115 };
8116
8117 /**
8118 * Handles mouse click events.
8119 *
8120 * @param {jQuery.Event} e Mouse click event
8121 */
8122 OO.ui.InlineMenuWidget.prototype.onClick = function ( e ) {
8123 // Skip clicks within the menu
8124 if ( $.contains( this.menu.$element[0], e.target ) ) {
8125 return;
8126 }
8127
8128 if ( !this.isDisabled() ) {
8129 if ( this.menu.isVisible() ) {
8130 this.menu.toggle( false );
8131 } else {
8132 this.menu.toggle( true );
8133 }
8134 }
8135 return false;
8136 };
8137
8138 /**
8139 * Base class for input widgets.
8140 *
8141 * @abstract
8142 * @class
8143 * @extends OO.ui.Widget
8144 *
8145 * @constructor
8146 * @param {Object} [config] Configuration options
8147 * @cfg {string} [name=''] HTML input name
8148 * @cfg {string} [value=''] Input value
8149 * @cfg {boolean} [readOnly=false] Prevent changes
8150 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
8151 */
8152 OO.ui.InputWidget = function OoUiInputWidget( config ) {
8153 // Config intialization
8154 config = $.extend( { 'readOnly': false }, config );
8155
8156 // Parent constructor
8157 OO.ui.InputWidget.super.call( this, config );
8158
8159 // Properties
8160 this.$input = this.getInputElement( config );
8161 this.value = '';
8162 this.readOnly = false;
8163 this.inputFilter = config.inputFilter;
8164
8165 // Events
8166 this.$input.on( 'keydown mouseup cut paste change input select', OO.ui.bind( this.onEdit, this ) );
8167
8168 // Initialization
8169 this.$input
8170 .attr( 'name', config.name )
8171 .prop( 'disabled', this.isDisabled() );
8172 this.setReadOnly( config.readOnly );
8173 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input );
8174 this.setValue( config.value );
8175 };
8176
8177 /* Setup */
8178
8179 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
8180
8181 /* Events */
8182
8183 /**
8184 * @event change
8185 * @param value
8186 */
8187
8188 /* Methods */
8189
8190 /**
8191 * Get input element.
8192 *
8193 * @param {Object} [config] Configuration options
8194 * @return {jQuery} Input element
8195 */
8196 OO.ui.InputWidget.prototype.getInputElement = function () {
8197 return this.$( '<input>' );
8198 };
8199
8200 /**
8201 * Handle potentially value-changing events.
8202 *
8203 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8204 */
8205 OO.ui.InputWidget.prototype.onEdit = function () {
8206 var widget = this;
8207 if ( !this.isDisabled() ) {
8208 // Allow the stack to clear so the value will be updated
8209 setTimeout( function () {
8210 widget.setValue( widget.$input.val() );
8211 } );
8212 }
8213 };
8214
8215 /**
8216 * Get the value of the input.
8217 *
8218 * @return {string} Input value
8219 */
8220 OO.ui.InputWidget.prototype.getValue = function () {
8221 return this.value;
8222 };
8223
8224 /**
8225 * Sets the direction of the current input, either RTL or LTR
8226 *
8227 * @param {boolean} isRTL
8228 */
8229 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
8230 if ( isRTL ) {
8231 this.$input.removeClass( 'oo-ui-ltr' );
8232 this.$input.addClass( 'oo-ui-rtl' );
8233 } else {
8234 this.$input.removeClass( 'oo-ui-rtl' );
8235 this.$input.addClass( 'oo-ui-ltr' );
8236 }
8237 };
8238
8239 /**
8240 * Set the value of the input.
8241 *
8242 * @param {string} value New value
8243 * @fires change
8244 * @chainable
8245 */
8246 OO.ui.InputWidget.prototype.setValue = function ( value ) {
8247 value = this.sanitizeValue( value );
8248 if ( this.value !== value ) {
8249 this.value = value;
8250 this.emit( 'change', this.value );
8251 }
8252 // Update the DOM if it has changed. Note that with sanitizeValue, it
8253 // is possible for the DOM value to change without this.value changing.
8254 if ( this.$input.val() !== this.value ) {
8255 this.$input.val( this.value );
8256 }
8257 return this;
8258 };
8259
8260 /**
8261 * Sanitize incoming value.
8262 *
8263 * Ensures value is a string, and converts undefined and null to empty strings.
8264 *
8265 * @param {string} value Original value
8266 * @return {string} Sanitized value
8267 */
8268 OO.ui.InputWidget.prototype.sanitizeValue = function ( value ) {
8269 if ( value === undefined || value === null ) {
8270 return '';
8271 } else if ( this.inputFilter ) {
8272 return this.inputFilter( String( value ) );
8273 } else {
8274 return String( value );
8275 }
8276 };
8277
8278 /**
8279 * Simulate the behavior of clicking on a label bound to this input.
8280 */
8281 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
8282 if ( !this.isDisabled() ) {
8283 if ( this.$input.is( ':checkbox,:radio' ) ) {
8284 this.$input.click();
8285 } else if ( this.$input.is( ':input' ) ) {
8286 this.$input.focus();
8287 }
8288 }
8289 };
8290
8291 /**
8292 * Check if the widget is read-only.
8293 *
8294 * @return {boolean}
8295 */
8296 OO.ui.InputWidget.prototype.isReadOnly = function () {
8297 return this.readOnly;
8298 };
8299
8300 /**
8301 * Set the read-only state of the widget.
8302 *
8303 * This should probably change the widgets's appearance and prevent it from being used.
8304 *
8305 * @param {boolean} state Make input read-only
8306 * @chainable
8307 */
8308 OO.ui.InputWidget.prototype.setReadOnly = function ( state ) {
8309 this.readOnly = !!state;
8310 this.$input.prop( 'readOnly', this.readOnly );
8311 return this;
8312 };
8313
8314 /**
8315 * @inheritdoc
8316 */
8317 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
8318 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
8319 if ( this.$input ) {
8320 this.$input.prop( 'disabled', this.isDisabled() );
8321 }
8322 return this;
8323 };
8324
8325 /**
8326 * Focus the input.
8327 *
8328 * @chainable
8329 */
8330 OO.ui.InputWidget.prototype.focus = function () {
8331 this.$input.focus();
8332 return this;
8333 };
8334
8335 /**
8336 * Blur the input.
8337 *
8338 * @chainable
8339 */
8340 OO.ui.InputWidget.prototype.blur = function () {
8341 this.$input.blur();
8342 return this;
8343 };
8344
8345 /**
8346 * Checkbox input widget.
8347 *
8348 * @class
8349 * @extends OO.ui.InputWidget
8350 *
8351 * @constructor
8352 * @param {Object} [config] Configuration options
8353 */
8354 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
8355 // Parent constructor
8356 OO.ui.CheckboxInputWidget.super.call( this, config );
8357
8358 // Initialization
8359 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
8360 };
8361
8362 /* Setup */
8363
8364 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
8365
8366 /* Events */
8367
8368 /* Methods */
8369
8370 /**
8371 * Get input element.
8372 *
8373 * @return {jQuery} Input element
8374 */
8375 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
8376 return this.$( '<input type="checkbox" />' );
8377 };
8378
8379 /**
8380 * Get checked state of the checkbox
8381 *
8382 * @return {boolean} If the checkbox is checked
8383 */
8384 OO.ui.CheckboxInputWidget.prototype.getValue = function () {
8385 return this.value;
8386 };
8387
8388 /**
8389 * Set value
8390 */
8391 OO.ui.CheckboxInputWidget.prototype.setValue = function ( value ) {
8392 value = !!value;
8393 if ( this.value !== value ) {
8394 this.value = value;
8395 this.$input.prop( 'checked', this.value );
8396 this.emit( 'change', this.value );
8397 }
8398 };
8399
8400 /**
8401 * @inheritdoc
8402 */
8403 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
8404 var widget = this;
8405 if ( !this.isDisabled() ) {
8406 // Allow the stack to clear so the value will be updated
8407 setTimeout( function () {
8408 widget.setValue( widget.$input.prop( 'checked' ) );
8409 } );
8410 }
8411 };
8412
8413 /**
8414 * Input widget with a text field.
8415 *
8416 * @class
8417 * @extends OO.ui.InputWidget
8418 *
8419 * @constructor
8420 * @param {Object} [config] Configuration options
8421 * @cfg {string} [placeholder] Placeholder text
8422 * @cfg {string} [icon] Symbolic name of icon
8423 * @cfg {boolean} [multiline=false] Allow multiple lines of text
8424 * @cfg {boolean} [autosize=false] Automatically resize to fit content
8425 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
8426 */
8427 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
8428 var widget = this;
8429 config = $.extend( { 'maxRows': 10 }, config );
8430
8431 // Parent constructor
8432 OO.ui.TextInputWidget.super.call( this, config );
8433
8434 // Properties
8435 this.pending = 0;
8436 this.multiline = !!config.multiline;
8437 this.autosize = !!config.autosize;
8438 this.maxRows = config.maxRows;
8439
8440 // Events
8441 this.$input.on( 'keypress', OO.ui.bind( this.onKeyPress, this ) );
8442 this.$element.on( 'DOMNodeInsertedIntoDocument', OO.ui.bind( this.onElementAttach, this ) );
8443
8444 // Initialization
8445 this.$element.addClass( 'oo-ui-textInputWidget' );
8446 if ( config.icon ) {
8447 this.$element.addClass( 'oo-ui-textInputWidget-decorated' );
8448 this.$element.append(
8449 this.$( '<span>' )
8450 .addClass( 'oo-ui-textInputWidget-icon oo-ui-icon-' + config.icon )
8451 .mousedown( function () {
8452 widget.$input.focus();
8453 return false;
8454 } )
8455 );
8456 }
8457 if ( config.placeholder ) {
8458 this.$input.attr( 'placeholder', config.placeholder );
8459 }
8460 };
8461
8462 /* Setup */
8463
8464 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
8465
8466 /* Events */
8467
8468 /**
8469 * User presses enter inside the text box.
8470 *
8471 * Not called if input is multiline.
8472 *
8473 * @event enter
8474 */
8475
8476 /* Methods */
8477
8478 /**
8479 * Handle key press events.
8480 *
8481 * @param {jQuery.Event} e Key press event
8482 * @fires enter If enter key is pressed and input is not multiline
8483 */
8484 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
8485 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
8486 this.emit( 'enter' );
8487 }
8488 };
8489
8490 /**
8491 * Handle element attach events.
8492 *
8493 * @param {jQuery.Event} e Element attach event
8494 */
8495 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
8496 this.adjustSize();
8497 };
8498
8499 /**
8500 * @inheritdoc
8501 */
8502 OO.ui.TextInputWidget.prototype.onEdit = function () {
8503 this.adjustSize();
8504
8505 // Parent method
8506 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
8507 };
8508
8509 /**
8510 * Automatically adjust the size of the text input.
8511 *
8512 * This only affects multi-line inputs that are auto-sized.
8513 *
8514 * @chainable
8515 */
8516 OO.ui.TextInputWidget.prototype.adjustSize = function () {
8517 var $clone, scrollHeight, innerHeight, outerHeight, maxInnerHeight, idealHeight;
8518
8519 if ( this.multiline && this.autosize ) {
8520 $clone = this.$input.clone()
8521 .val( this.$input.val() )
8522 .css( { 'height': 0 } )
8523 .insertAfter( this.$input );
8524 // Set inline height property to 0 to measure scroll height
8525 scrollHeight = $clone[0].scrollHeight;
8526 // Remove inline height property to measure natural heights
8527 $clone.css( 'height', '' );
8528 innerHeight = $clone.innerHeight();
8529 outerHeight = $clone.outerHeight();
8530 // Measure max rows height
8531 $clone.attr( 'rows', this.maxRows ).css( 'height', 'auto' );
8532 maxInnerHeight = $clone.innerHeight();
8533 $clone.removeAttr( 'rows' ).css( 'height', '' );
8534 $clone.remove();
8535 idealHeight = Math.min( maxInnerHeight, scrollHeight );
8536 // Only apply inline height when expansion beyond natural height is needed
8537 this.$input.css(
8538 'height',
8539 // Use the difference between the inner and outer height as a buffer
8540 idealHeight > outerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''
8541 );
8542 }
8543 return this;
8544 };
8545
8546 /**
8547 * Get input element.
8548 *
8549 * @param {Object} [config] Configuration options
8550 * @return {jQuery} Input element
8551 */
8552 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
8553 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="text" />' );
8554 };
8555
8556 /* Methods */
8557
8558 /**
8559 * Check if input supports multiple lines.
8560 *
8561 * @return {boolean}
8562 */
8563 OO.ui.TextInputWidget.prototype.isMultiline = function () {
8564 return !!this.multiline;
8565 };
8566
8567 /**
8568 * Check if input automatically adjusts its size.
8569 *
8570 * @return {boolean}
8571 */
8572 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
8573 return !!this.autosize;
8574 };
8575
8576 /**
8577 * Check if input is pending.
8578 *
8579 * @return {boolean}
8580 */
8581 OO.ui.TextInputWidget.prototype.isPending = function () {
8582 return !!this.pending;
8583 };
8584
8585 /**
8586 * Increase the pending stack.
8587 *
8588 * @chainable
8589 */
8590 OO.ui.TextInputWidget.prototype.pushPending = function () {
8591 if ( this.pending === 0 ) {
8592 this.$element.addClass( 'oo-ui-textInputWidget-pending' );
8593 this.$input.addClass( 'oo-ui-texture-pending' );
8594 }
8595 this.pending++;
8596
8597 return this;
8598 };
8599
8600 /**
8601 * Reduce the pending stack.
8602 *
8603 * Clamped at zero.
8604 *
8605 * @chainable
8606 */
8607 OO.ui.TextInputWidget.prototype.popPending = function () {
8608 if ( this.pending === 1 ) {
8609 this.$element.removeClass( 'oo-ui-textInputWidget-pending' );
8610 this.$input.removeClass( 'oo-ui-texture-pending' );
8611 }
8612 this.pending = Math.max( 0, this.pending - 1 );
8613
8614 return this;
8615 };
8616
8617 /**
8618 * Select the contents of the input.
8619 *
8620 * @chainable
8621 */
8622 OO.ui.TextInputWidget.prototype.select = function () {
8623 this.$input.select();
8624 return this;
8625 };
8626
8627 /**
8628 * Label widget.
8629 *
8630 * @class
8631 * @extends OO.ui.Widget
8632 * @mixins OO.ui.LabeledElement
8633 *
8634 * @constructor
8635 * @param {Object} [config] Configuration options
8636 */
8637 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
8638 // Config intialization
8639 config = config || {};
8640
8641 // Parent constructor
8642 OO.ui.LabelWidget.super.call( this, config );
8643
8644 // Mixin constructors
8645 OO.ui.LabeledElement.call( this, this.$element, config );
8646
8647 // Properties
8648 this.input = config.input;
8649
8650 // Events
8651 if ( this.input instanceof OO.ui.InputWidget ) {
8652 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
8653 }
8654
8655 // Initialization
8656 this.$element.addClass( 'oo-ui-labelWidget' );
8657 };
8658
8659 /* Setup */
8660
8661 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
8662 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabeledElement );
8663
8664 /* Static Properties */
8665
8666 OO.ui.LabelWidget.static.tagName = 'label';
8667
8668 /* Methods */
8669
8670 /**
8671 * Handles label mouse click events.
8672 *
8673 * @param {jQuery.Event} e Mouse click event
8674 */
8675 OO.ui.LabelWidget.prototype.onClick = function () {
8676 this.input.simulateLabelClick();
8677 return false;
8678 };
8679
8680 /**
8681 * Generic option widget for use with OO.ui.SelectWidget.
8682 *
8683 * @class
8684 * @extends OO.ui.Widget
8685 * @mixins OO.ui.LabeledElement
8686 * @mixins OO.ui.FlaggableElement
8687 *
8688 * @constructor
8689 * @param {Mixed} data Option data
8690 * @param {Object} [config] Configuration options
8691 * @cfg {string} [rel] Value for `rel` attribute in DOM, allowing per-option styling
8692 */
8693 OO.ui.OptionWidget = function OoUiOptionWidget( data, config ) {
8694 // Config intialization
8695 config = config || {};
8696
8697 // Parent constructor
8698 OO.ui.OptionWidget.super.call( this, config );
8699
8700 // Mixin constructors
8701 OO.ui.ItemWidget.call( this );
8702 OO.ui.LabeledElement.call( this, this.$( '<span>' ), config );
8703 OO.ui.FlaggableElement.call( this, config );
8704
8705 // Properties
8706 this.data = data;
8707 this.selected = false;
8708 this.highlighted = false;
8709 this.pressed = false;
8710
8711 // Initialization
8712 this.$element
8713 .data( 'oo-ui-optionWidget', this )
8714 .attr( 'rel', config.rel )
8715 .addClass( 'oo-ui-optionWidget' )
8716 .append( this.$label );
8717 this.$element
8718 .prepend( this.$icon )
8719 .append( this.$indicator );
8720 };
8721
8722 /* Setup */
8723
8724 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
8725 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
8726 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabeledElement );
8727 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggableElement );
8728
8729 /* Static Properties */
8730
8731 OO.ui.OptionWidget.static.tagName = 'li';
8732
8733 OO.ui.OptionWidget.static.selectable = true;
8734
8735 OO.ui.OptionWidget.static.highlightable = true;
8736
8737 OO.ui.OptionWidget.static.pressable = true;
8738
8739 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
8740
8741 /* Methods */
8742
8743 /**
8744 * Check if option can be selected.
8745 *
8746 * @return {boolean} Item is selectable
8747 */
8748 OO.ui.OptionWidget.prototype.isSelectable = function () {
8749 return this.constructor.static.selectable && !this.isDisabled();
8750 };
8751
8752 /**
8753 * Check if option can be highlighted.
8754 *
8755 * @return {boolean} Item is highlightable
8756 */
8757 OO.ui.OptionWidget.prototype.isHighlightable = function () {
8758 return this.constructor.static.highlightable && !this.isDisabled();
8759 };
8760
8761 /**
8762 * Check if option can be pressed.
8763 *
8764 * @return {boolean} Item is pressable
8765 */
8766 OO.ui.OptionWidget.prototype.isPressable = function () {
8767 return this.constructor.static.pressable && !this.isDisabled();
8768 };
8769
8770 /**
8771 * Check if option is selected.
8772 *
8773 * @return {boolean} Item is selected
8774 */
8775 OO.ui.OptionWidget.prototype.isSelected = function () {
8776 return this.selected;
8777 };
8778
8779 /**
8780 * Check if option is highlighted.
8781 *
8782 * @return {boolean} Item is highlighted
8783 */
8784 OO.ui.OptionWidget.prototype.isHighlighted = function () {
8785 return this.highlighted;
8786 };
8787
8788 /**
8789 * Check if option is pressed.
8790 *
8791 * @return {boolean} Item is pressed
8792 */
8793 OO.ui.OptionWidget.prototype.isPressed = function () {
8794 return this.pressed;
8795 };
8796
8797 /**
8798 * Set selected state.
8799 *
8800 * @param {boolean} [state=false] Select option
8801 * @chainable
8802 */
8803 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
8804 if ( this.constructor.static.selectable ) {
8805 this.selected = !!state;
8806 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
8807 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
8808 this.scrollElementIntoView();
8809 }
8810 }
8811 return this;
8812 };
8813
8814 /**
8815 * Set highlighted state.
8816 *
8817 * @param {boolean} [state=false] Highlight option
8818 * @chainable
8819 */
8820 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
8821 if ( this.constructor.static.highlightable ) {
8822 this.highlighted = !!state;
8823 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
8824 }
8825 return this;
8826 };
8827
8828 /**
8829 * Set pressed state.
8830 *
8831 * @param {boolean} [state=false] Press option
8832 * @chainable
8833 */
8834 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
8835 if ( this.constructor.static.pressable ) {
8836 this.pressed = !!state;
8837 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
8838 }
8839 return this;
8840 };
8841
8842 /**
8843 * Make the option's highlight flash.
8844 *
8845 * While flashing, the visual style of the pressed state is removed if present.
8846 *
8847 * @return {jQuery.Promise} Promise resolved when flashing is done
8848 */
8849 OO.ui.OptionWidget.prototype.flash = function () {
8850 var widget = this,
8851 $element = this.$element,
8852 deferred = $.Deferred();
8853
8854 if ( !this.isDisabled() && this.constructor.static.pressable ) {
8855 $element.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
8856 setTimeout( function () {
8857 // Restore original classes
8858 $element
8859 .toggleClass( 'oo-ui-optionWidget-highlighted', widget.highlighted )
8860 .toggleClass( 'oo-ui-optionWidget-pressed', widget.pressed );
8861
8862 setTimeout( function () {
8863 deferred.resolve();
8864 }, 100 );
8865
8866 }, 100 );
8867 }
8868
8869 return deferred.promise();
8870 };
8871
8872 /**
8873 * Get option data.
8874 *
8875 * @return {Mixed} Option data
8876 */
8877 OO.ui.OptionWidget.prototype.getData = function () {
8878 return this.data;
8879 };
8880
8881 /**
8882 * Option widget with an option icon and indicator.
8883 *
8884 * Use together with OO.ui.SelectWidget.
8885 *
8886 * @class
8887 * @extends OO.ui.OptionWidget
8888 * @mixins OO.ui.IconedElement
8889 * @mixins OO.ui.IndicatedElement
8890 *
8891 * @constructor
8892 * @param {Mixed} data Option data
8893 * @param {Object} [config] Configuration options
8894 */
8895 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( data, config ) {
8896 // Parent constructor
8897 OO.ui.DecoratedOptionWidget.super.call( this, data, config );
8898
8899 // Mixin constructors
8900 OO.ui.IconedElement.call( this, this.$( '<span>' ), config );
8901 OO.ui.IndicatedElement.call( this, this.$( '<span>' ), config );
8902
8903 // Initialization
8904 this.$element
8905 .addClass( 'oo-ui-decoratedOptionWidget' )
8906 .prepend( this.$icon )
8907 .append( this.$indicator );
8908 };
8909
8910 /* Setup */
8911
8912 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
8913 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconedElement );
8914 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatedElement );
8915
8916 /**
8917 * Option widget that looks like a button.
8918 *
8919 * Use together with OO.ui.ButtonSelectWidget.
8920 *
8921 * @class
8922 * @extends OO.ui.DecoratedOptionWidget
8923 * @mixins OO.ui.ButtonedElement
8924 *
8925 * @constructor
8926 * @param {Mixed} data Option data
8927 * @param {Object} [config] Configuration options
8928 */
8929 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( data, config ) {
8930 // Parent constructor
8931 OO.ui.ButtonOptionWidget.super.call( this, data, config );
8932
8933 // Mixin constructors
8934 OO.ui.ButtonedElement.call( this, this.$( '<a>' ), config );
8935
8936 // Initialization
8937 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
8938 this.$button.append( this.$element.contents() );
8939 this.$element.append( this.$button );
8940 };
8941
8942 /* Setup */
8943
8944 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
8945 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonedElement );
8946
8947 /* Static Properties */
8948
8949 // Allow button mouse down events to pass through so they can be handled by the parent select widget
8950 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
8951
8952 /* Methods */
8953
8954 /**
8955 * @inheritdoc
8956 */
8957 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
8958 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
8959
8960 if ( this.constructor.static.selectable ) {
8961 this.setActive( state );
8962 }
8963
8964 return this;
8965 };
8966
8967 /**
8968 * Item of an OO.ui.MenuWidget.
8969 *
8970 * @class
8971 * @extends OO.ui.DecoratedOptionWidget
8972 *
8973 * @constructor
8974 * @param {Mixed} data Item data
8975 * @param {Object} [config] Configuration options
8976 */
8977 OO.ui.MenuItemWidget = function OoUiMenuItemWidget( data, config ) {
8978 // Configuration initialization
8979 config = $.extend( { 'icon': 'check' }, config );
8980
8981 // Parent constructor
8982 OO.ui.MenuItemWidget.super.call( this, data, config );
8983
8984 // Initialization
8985 this.$element.addClass( 'oo-ui-menuItemWidget' );
8986 };
8987
8988 /* Setup */
8989
8990 OO.inheritClass( OO.ui.MenuItemWidget, OO.ui.DecoratedOptionWidget );
8991
8992 /**
8993 * Section to group one or more items in a OO.ui.MenuWidget.
8994 *
8995 * @class
8996 * @extends OO.ui.DecoratedOptionWidget
8997 *
8998 * @constructor
8999 * @param {Mixed} data Item data
9000 * @param {Object} [config] Configuration options
9001 */
9002 OO.ui.MenuSectionItemWidget = function OoUiMenuSectionItemWidget( data, config ) {
9003 // Parent constructor
9004 OO.ui.MenuSectionItemWidget.super.call( this, data, config );
9005
9006 // Initialization
9007 this.$element.addClass( 'oo-ui-menuSectionItemWidget' );
9008 };
9009
9010 /* Setup */
9011
9012 OO.inheritClass( OO.ui.MenuSectionItemWidget, OO.ui.DecoratedOptionWidget );
9013
9014 /* Static Properties */
9015
9016 OO.ui.MenuSectionItemWidget.static.selectable = false;
9017
9018 OO.ui.MenuSectionItemWidget.static.highlightable = false;
9019
9020 /**
9021 * Items for an OO.ui.OutlineWidget.
9022 *
9023 * @class
9024 * @extends OO.ui.DecoratedOptionWidget
9025 *
9026 * @constructor
9027 * @param {Mixed} data Item data
9028 * @param {Object} [config] Configuration options
9029 * @cfg {number} [level] Indentation level
9030 * @cfg {boolean} [movable] Allow modification from outline controls
9031 */
9032 OO.ui.OutlineItemWidget = function OoUiOutlineItemWidget( data, config ) {
9033 // Config intialization
9034 config = config || {};
9035
9036 // Parent constructor
9037 OO.ui.OutlineItemWidget.super.call( this, data, config );
9038
9039 // Properties
9040 this.level = 0;
9041 this.movable = !!config.movable;
9042 this.removable = !!config.removable;
9043
9044 // Initialization
9045 this.$element.addClass( 'oo-ui-outlineItemWidget' );
9046 this.setLevel( config.level );
9047 };
9048
9049 /* Setup */
9050
9051 OO.inheritClass( OO.ui.OutlineItemWidget, OO.ui.DecoratedOptionWidget );
9052
9053 /* Static Properties */
9054
9055 OO.ui.OutlineItemWidget.static.highlightable = false;
9056
9057 OO.ui.OutlineItemWidget.static.scrollIntoViewOnSelect = true;
9058
9059 OO.ui.OutlineItemWidget.static.levelClass = 'oo-ui-outlineItemWidget-level-';
9060
9061 OO.ui.OutlineItemWidget.static.levels = 3;
9062
9063 /* Methods */
9064
9065 /**
9066 * Check if item is movable.
9067 *
9068 * Movablilty is used by outline controls.
9069 *
9070 * @return {boolean} Item is movable
9071 */
9072 OO.ui.OutlineItemWidget.prototype.isMovable = function () {
9073 return this.movable;
9074 };
9075
9076 /**
9077 * Check if item is removable.
9078 *
9079 * Removablilty is used by outline controls.
9080 *
9081 * @return {boolean} Item is removable
9082 */
9083 OO.ui.OutlineItemWidget.prototype.isRemovable = function () {
9084 return this.removable;
9085 };
9086
9087 /**
9088 * Get indentation level.
9089 *
9090 * @return {number} Indentation level
9091 */
9092 OO.ui.OutlineItemWidget.prototype.getLevel = function () {
9093 return this.level;
9094 };
9095
9096 /**
9097 * Set movability.
9098 *
9099 * Movablilty is used by outline controls.
9100 *
9101 * @param {boolean} movable Item is movable
9102 * @chainable
9103 */
9104 OO.ui.OutlineItemWidget.prototype.setMovable = function ( movable ) {
9105 this.movable = !!movable;
9106 return this;
9107 };
9108
9109 /**
9110 * Set removability.
9111 *
9112 * Removablilty is used by outline controls.
9113 *
9114 * @param {boolean} movable Item is removable
9115 * @chainable
9116 */
9117 OO.ui.OutlineItemWidget.prototype.setRemovable = function ( removable ) {
9118 this.removable = !!removable;
9119 return this;
9120 };
9121
9122 /**
9123 * Set indentation level.
9124 *
9125 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
9126 * @chainable
9127 */
9128 OO.ui.OutlineItemWidget.prototype.setLevel = function ( level ) {
9129 var levels = this.constructor.static.levels,
9130 levelClass = this.constructor.static.levelClass,
9131 i = levels;
9132
9133 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
9134 while ( i-- ) {
9135 if ( this.level === i ) {
9136 this.$element.addClass( levelClass + i );
9137 } else {
9138 this.$element.removeClass( levelClass + i );
9139 }
9140 }
9141
9142 return this;
9143 };
9144
9145 /**
9146 * Container for content that is overlaid and positioned absolutely.
9147 *
9148 * @class
9149 * @extends OO.ui.Widget
9150 * @mixins OO.ui.LabeledElement
9151 *
9152 * @constructor
9153 * @param {Object} [config] Configuration options
9154 * @cfg {number} [width=320] Width of popup in pixels
9155 * @cfg {number} [height] Height of popup, omit to use automatic height
9156 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
9157 * @cfg {string} [align='center'] Alignment of popup to origin
9158 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
9159 * @cfg {jQuery} [$content] Content to append to the popup's body
9160 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
9161 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
9162 * @cfg {boolean} [head] Show label and close button at the top
9163 * @cfg {boolean} [padded] Add padding to the body
9164 */
9165 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
9166 // Config intialization
9167 config = config || {};
9168
9169 // Parent constructor
9170 OO.ui.PopupWidget.super.call( this, config );
9171
9172 // Mixin constructors
9173 OO.ui.LabeledElement.call( this, this.$( '<div>' ), config );
9174 OO.ui.ClippableElement.call( this, this.$( '<div>' ), config );
9175
9176 // Properties
9177 this.visible = false;
9178 this.$popup = this.$( '<div>' );
9179 this.$head = this.$( '<div>' );
9180 this.$body = this.$clippable;
9181 this.$anchor = this.$( '<div>' );
9182 this.$container = config.$container || this.$( 'body' );
9183 this.autoClose = !!config.autoClose;
9184 this.$autoCloseIgnore = config.$autoCloseIgnore;
9185 this.transitionTimeout = null;
9186 this.anchor = null;
9187 this.width = config.width !== undefined ? config.width : 320;
9188 this.height = config.height !== undefined ? config.height : null;
9189 this.align = config.align || 'center';
9190 this.closeButton = new OO.ui.ButtonWidget( { '$': this.$, 'framed': false, 'icon': 'close' } );
9191 this.onMouseDownHandler = OO.ui.bind( this.onMouseDown, this );
9192
9193 // Events
9194 this.closeButton.connect( this, { 'click': 'onCloseButtonClick' } );
9195
9196 // Initialization
9197 this.toggleAnchor( config.anchor === undefined || config.anchor );
9198 this.$body.addClass( 'oo-ui-popupWidget-body' );
9199 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
9200 this.$head
9201 .addClass( 'oo-ui-popupWidget-head' )
9202 .append( this.$label, this.closeButton.$element );
9203 if ( !config.head ) {
9204 this.$head.hide();
9205 }
9206 this.$popup
9207 .addClass( 'oo-ui-popupWidget-popup' )
9208 .append( this.$head, this.$body );
9209 this.$element
9210 .hide()
9211 .addClass( 'oo-ui-popupWidget' )
9212 .append( this.$popup, this.$anchor );
9213 // Move content, which was added to #$element by OO.ui.Widget, to the body
9214 if ( config.$content instanceof jQuery ) {
9215 this.$body.append( config.$content );
9216 }
9217 if ( config.padded ) {
9218 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
9219 }
9220 };
9221
9222 /* Setup */
9223
9224 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
9225 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabeledElement );
9226 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
9227
9228 /* Events */
9229
9230 /**
9231 * @event hide
9232 */
9233
9234 /**
9235 * @event show
9236 */
9237
9238 /* Methods */
9239
9240 /**
9241 * Handles mouse down events.
9242 *
9243 * @param {jQuery.Event} e Mouse down event
9244 */
9245 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
9246 if (
9247 this.isVisible() &&
9248 !$.contains( this.$element[0], e.target ) &&
9249 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
9250 ) {
9251 this.toggle( false );
9252 }
9253 };
9254
9255 /**
9256 * Bind mouse down listener.
9257 */
9258 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
9259 // Capture clicks outside popup
9260 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
9261 };
9262
9263 /**
9264 * Handles close button click events.
9265 */
9266 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
9267 if ( this.isVisible() ) {
9268 this.toggle( false );
9269 }
9270 };
9271
9272 /**
9273 * Unbind mouse down listener.
9274 */
9275 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
9276 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
9277 };
9278
9279 /**
9280 * Set whether to show a anchor.
9281 *
9282 * @param {boolean} [show] Show anchor, omit to toggle
9283 */
9284 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
9285 show = show === undefined ? !this.anchored : !!show;
9286
9287 if ( this.anchored !== show ) {
9288 if ( show ) {
9289 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
9290 } else {
9291 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
9292 }
9293 this.anchored = show;
9294 }
9295 };
9296
9297 /**
9298 * Check if showing a anchor.
9299 *
9300 * @return {boolean} anchor is visible
9301 */
9302 OO.ui.PopupWidget.prototype.hasAnchor = function () {
9303 return this.anchor;
9304 };
9305
9306 /**
9307 * @inheritdoc
9308 */
9309 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
9310 show = show === undefined ? !this.isVisible() : !!show;
9311
9312 var change = show !== this.isVisible();
9313
9314 // Parent method
9315 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
9316
9317 if ( change ) {
9318 if ( show ) {
9319 this.setClipping( true );
9320 if ( this.autoClose ) {
9321 this.bindMouseDownListener();
9322 }
9323 this.updateDimensions();
9324 } else {
9325 this.setClipping( false );
9326 if ( this.autoClose ) {
9327 this.unbindMouseDownListener();
9328 }
9329 }
9330 }
9331
9332 return this;
9333 };
9334
9335 /**
9336 * Set the size of the popup.
9337 *
9338 * Changing the size may also change the popup's position depending on the alignment.
9339 *
9340 * @param {number} width Width
9341 * @param {number} height Height
9342 * @param {boolean} [transition=false] Use a smooth transition
9343 * @chainable
9344 */
9345 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
9346 this.width = width;
9347 this.height = height !== undefined ? height : null;
9348 if ( this.isVisible() ) {
9349 this.updateDimensions( transition );
9350 }
9351 };
9352
9353 /**
9354 * Update the size and position.
9355 *
9356 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
9357 * be called automatically.
9358 *
9359 * @param {boolean} [transition=false] Use a smooth transition
9360 * @chainable
9361 */
9362 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
9363 var widget = this,
9364 padding = 10,
9365 originOffset = Math.round( this.$element.offset().left ),
9366 containerLeft = Math.round( this.$container.offset().left ),
9367 containerWidth = this.$container.innerWidth(),
9368 containerRight = containerLeft + containerWidth,
9369 popupOffset = this.width * ( { 'left': 0, 'center': -0.5, 'right': -1 } )[this.align],
9370 anchorWidth = this.$anchor.width(),
9371 popupLeft = popupOffset - padding,
9372 popupRight = popupOffset + padding + this.width + padding,
9373 overlapLeft = ( originOffset + popupLeft ) - containerLeft,
9374 overlapRight = containerRight - ( originOffset + popupRight );
9375
9376 // Prevent transition from being interrupted
9377 clearTimeout( this.transitionTimeout );
9378 if ( transition ) {
9379 // Enable transition
9380 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
9381 }
9382
9383 if ( overlapRight < 0 ) {
9384 popupOffset += overlapRight;
9385 } else if ( overlapLeft < 0 ) {
9386 popupOffset -= overlapLeft;
9387 }
9388
9389 // Adjust offset to avoid anchor being rendered too close to the edge
9390 if ( this.align === 'right' ) {
9391 popupOffset += anchorWidth;
9392 } else if ( this.align === 'left' ) {
9393 popupOffset -= anchorWidth;
9394 }
9395
9396 // Position body relative to anchor and resize
9397 this.$popup.css( {
9398 'left': popupOffset,
9399 'width': this.width,
9400 'height': this.height !== null ? this.height : 'auto'
9401 } );
9402
9403 if ( transition ) {
9404 // Prevent transitioning after transition is complete
9405 this.transitionTimeout = setTimeout( function () {
9406 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
9407 }, 200 );
9408 } else {
9409 // Prevent transitioning immediately
9410 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
9411 }
9412
9413 return this;
9414 };
9415
9416 /**
9417 * Search widget.
9418 *
9419 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
9420 * Results are cleared and populated each time the query is changed.
9421 *
9422 * @class
9423 * @extends OO.ui.Widget
9424 *
9425 * @constructor
9426 * @param {Object} [config] Configuration options
9427 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
9428 * @cfg {string} [value] Initial query value
9429 */
9430 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
9431 // Configuration intialization
9432 config = config || {};
9433
9434 // Parent constructor
9435 OO.ui.SearchWidget.super.call( this, config );
9436
9437 // Properties
9438 this.query = new OO.ui.TextInputWidget( {
9439 '$': this.$,
9440 'icon': 'search',
9441 'placeholder': config.placeholder,
9442 'value': config.value
9443 } );
9444 this.results = new OO.ui.SelectWidget( { '$': this.$ } );
9445 this.$query = this.$( '<div>' );
9446 this.$results = this.$( '<div>' );
9447
9448 // Events
9449 this.query.connect( this, {
9450 'change': 'onQueryChange',
9451 'enter': 'onQueryEnter'
9452 } );
9453 this.results.connect( this, {
9454 'highlight': 'onResultsHighlight',
9455 'select': 'onResultsSelect'
9456 } );
9457 this.query.$input.on( 'keydown', OO.ui.bind( this.onQueryKeydown, this ) );
9458
9459 // Initialization
9460 this.$query
9461 .addClass( 'oo-ui-searchWidget-query' )
9462 .append( this.query.$element );
9463 this.$results
9464 .addClass( 'oo-ui-searchWidget-results' )
9465 .append( this.results.$element );
9466 this.$element
9467 .addClass( 'oo-ui-searchWidget' )
9468 .append( this.$results, this.$query );
9469 };
9470
9471 /* Setup */
9472
9473 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
9474
9475 /* Events */
9476
9477 /**
9478 * @event highlight
9479 * @param {Object|null} item Item data or null if no item is highlighted
9480 */
9481
9482 /**
9483 * @event select
9484 * @param {Object|null} item Item data or null if no item is selected
9485 */
9486
9487 /* Methods */
9488
9489 /**
9490 * Handle query key down events.
9491 *
9492 * @param {jQuery.Event} e Key down event
9493 */
9494 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
9495 var highlightedItem, nextItem,
9496 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
9497
9498 if ( dir ) {
9499 highlightedItem = this.results.getHighlightedItem();
9500 if ( !highlightedItem ) {
9501 highlightedItem = this.results.getSelectedItem();
9502 }
9503 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
9504 this.results.highlightItem( nextItem );
9505 nextItem.scrollElementIntoView();
9506 }
9507 };
9508
9509 /**
9510 * Handle select widget select events.
9511 *
9512 * Clears existing results. Subclasses should repopulate items according to new query.
9513 *
9514 * @param {string} value New value
9515 */
9516 OO.ui.SearchWidget.prototype.onQueryChange = function () {
9517 // Reset
9518 this.results.clearItems();
9519 };
9520
9521 /**
9522 * Handle select widget enter key events.
9523 *
9524 * Selects highlighted item.
9525 *
9526 * @param {string} value New value
9527 */
9528 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
9529 // Reset
9530 this.results.selectItem( this.results.getHighlightedItem() );
9531 };
9532
9533 /**
9534 * Handle select widget highlight events.
9535 *
9536 * @param {OO.ui.OptionWidget} item Highlighted item
9537 * @fires highlight
9538 */
9539 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
9540 this.emit( 'highlight', item ? item.getData() : null );
9541 };
9542
9543 /**
9544 * Handle select widget select events.
9545 *
9546 * @param {OO.ui.OptionWidget} item Selected item
9547 * @fires select
9548 */
9549 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
9550 this.emit( 'select', item ? item.getData() : null );
9551 };
9552
9553 /**
9554 * Get the query input.
9555 *
9556 * @return {OO.ui.TextInputWidget} Query input
9557 */
9558 OO.ui.SearchWidget.prototype.getQuery = function () {
9559 return this.query;
9560 };
9561
9562 /**
9563 * Get the results list.
9564 *
9565 * @return {OO.ui.SelectWidget} Select list
9566 */
9567 OO.ui.SearchWidget.prototype.getResults = function () {
9568 return this.results;
9569 };
9570
9571 /**
9572 * Generic selection of options.
9573 *
9574 * Items can contain any rendering, and are uniquely identified by a has of thier data. Any widget
9575 * that provides options, from which the user must choose one, should be built on this class.
9576 *
9577 * Use together with OO.ui.OptionWidget.
9578 *
9579 * @class
9580 * @extends OO.ui.Widget
9581 * @mixins OO.ui.GroupElement
9582 *
9583 * @constructor
9584 * @param {Object} [config] Configuration options
9585 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
9586 */
9587 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
9588 // Config intialization
9589 config = config || {};
9590
9591 // Parent constructor
9592 OO.ui.SelectWidget.super.call( this, config );
9593
9594 // Mixin constructors
9595 OO.ui.GroupWidget.call( this, this.$element, config );
9596
9597 // Properties
9598 this.pressed = false;
9599 this.selecting = null;
9600 this.hashes = {};
9601 this.onMouseUpHandler = OO.ui.bind( this.onMouseUp, this );
9602 this.onMouseMoveHandler = OO.ui.bind( this.onMouseMove, this );
9603
9604 // Events
9605 this.$element.on( {
9606 'mousedown': OO.ui.bind( this.onMouseDown, this ),
9607 'mouseover': OO.ui.bind( this.onMouseOver, this ),
9608 'mouseleave': OO.ui.bind( this.onMouseLeave, this )
9609 } );
9610
9611 // Initialization
9612 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
9613 if ( $.isArray( config.items ) ) {
9614 this.addItems( config.items );
9615 }
9616 };
9617
9618 /* Setup */
9619
9620 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
9621
9622 // Need to mixin base class as well
9623 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
9624 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
9625
9626 /* Events */
9627
9628 /**
9629 * @event highlight
9630 * @param {OO.ui.OptionWidget|null} item Highlighted item
9631 */
9632
9633 /**
9634 * @event press
9635 * @param {OO.ui.OptionWidget|null} item Pressed item
9636 */
9637
9638 /**
9639 * @event select
9640 * @param {OO.ui.OptionWidget|null} item Selected item
9641 */
9642
9643 /**
9644 * @event choose
9645 * @param {OO.ui.OptionWidget|null} item Chosen item
9646 */
9647
9648 /**
9649 * @event add
9650 * @param {OO.ui.OptionWidget[]} items Added items
9651 * @param {number} index Index items were added at
9652 */
9653
9654 /**
9655 * @event remove
9656 * @param {OO.ui.OptionWidget[]} items Removed items
9657 */
9658
9659 /* Static Properties */
9660
9661 OO.ui.SelectWidget.static.tagName = 'ul';
9662
9663 /* Methods */
9664
9665 /**
9666 * Handle mouse down events.
9667 *
9668 * @private
9669 * @param {jQuery.Event} e Mouse down event
9670 */
9671 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
9672 var item;
9673
9674 if ( !this.isDisabled() && e.which === 1 ) {
9675 this.togglePressed( true );
9676 item = this.getTargetItem( e );
9677 if ( item && item.isSelectable() ) {
9678 this.pressItem( item );
9679 this.selecting = item;
9680 this.getElementDocument().addEventListener(
9681 'mouseup',
9682 this.onMouseUpHandler,
9683 true
9684 );
9685 this.getElementDocument().addEventListener(
9686 'mousemove',
9687 this.onMouseMoveHandler,
9688 true
9689 );
9690 }
9691 }
9692 return false;
9693 };
9694
9695 /**
9696 * Handle mouse up events.
9697 *
9698 * @private
9699 * @param {jQuery.Event} e Mouse up event
9700 */
9701 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
9702 var item;
9703
9704 this.togglePressed( false );
9705 if ( !this.selecting ) {
9706 item = this.getTargetItem( e );
9707 if ( item && item.isSelectable() ) {
9708 this.selecting = item;
9709 }
9710 }
9711 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
9712 this.pressItem( null );
9713 this.chooseItem( this.selecting );
9714 this.selecting = null;
9715 }
9716
9717 this.getElementDocument().removeEventListener(
9718 'mouseup',
9719 this.onMouseUpHandler,
9720 true
9721 );
9722 this.getElementDocument().removeEventListener(
9723 'mousemove',
9724 this.onMouseMoveHandler,
9725 true
9726 );
9727
9728 return false;
9729 };
9730
9731 /**
9732 * Handle mouse move events.
9733 *
9734 * @private
9735 * @param {jQuery.Event} e Mouse move event
9736 */
9737 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
9738 var item;
9739
9740 if ( !this.isDisabled() && this.pressed ) {
9741 item = this.getTargetItem( e );
9742 if ( item && item !== this.selecting && item.isSelectable() ) {
9743 this.pressItem( item );
9744 this.selecting = item;
9745 }
9746 }
9747 return false;
9748 };
9749
9750 /**
9751 * Handle mouse over events.
9752 *
9753 * @private
9754 * @param {jQuery.Event} e Mouse over event
9755 */
9756 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
9757 var item;
9758
9759 if ( !this.isDisabled() ) {
9760 item = this.getTargetItem( e );
9761 this.highlightItem( item && item.isHighlightable() ? item : null );
9762 }
9763 return false;
9764 };
9765
9766 /**
9767 * Handle mouse leave events.
9768 *
9769 * @private
9770 * @param {jQuery.Event} e Mouse over event
9771 */
9772 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
9773 if ( !this.isDisabled() ) {
9774 this.highlightItem( null );
9775 }
9776 return false;
9777 };
9778
9779 /**
9780 * Get the closest item to a jQuery.Event.
9781 *
9782 * @private
9783 * @param {jQuery.Event} e
9784 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
9785 */
9786 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
9787 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
9788 if ( $item.length ) {
9789 return $item.data( 'oo-ui-optionWidget' );
9790 }
9791 return null;
9792 };
9793
9794 /**
9795 * Get selected item.
9796 *
9797 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
9798 */
9799 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
9800 var i, len;
9801
9802 for ( i = 0, len = this.items.length; i < len; i++ ) {
9803 if ( this.items[i].isSelected() ) {
9804 return this.items[i];
9805 }
9806 }
9807 return null;
9808 };
9809
9810 /**
9811 * Get highlighted item.
9812 *
9813 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
9814 */
9815 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
9816 var i, len;
9817
9818 for ( i = 0, len = this.items.length; i < len; i++ ) {
9819 if ( this.items[i].isHighlighted() ) {
9820 return this.items[i];
9821 }
9822 }
9823 return null;
9824 };
9825
9826 /**
9827 * Get an existing item with equivilant data.
9828 *
9829 * @param {Object} data Item data to search for
9830 * @return {OO.ui.OptionWidget|null} Item with equivilent value, `null` if none exists
9831 */
9832 OO.ui.SelectWidget.prototype.getItemFromData = function ( data ) {
9833 var hash = OO.getHash( data );
9834
9835 if ( hash in this.hashes ) {
9836 return this.hashes[hash];
9837 }
9838
9839 return null;
9840 };
9841
9842 /**
9843 * Toggle pressed state.
9844 *
9845 * @param {boolean} pressed An option is being pressed
9846 */
9847 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
9848 if ( pressed === undefined ) {
9849 pressed = !this.pressed;
9850 }
9851 if ( pressed !== this.pressed ) {
9852 this.$element
9853 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
9854 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
9855 this.pressed = pressed;
9856 }
9857 };
9858
9859 /**
9860 * Highlight an item.
9861 *
9862 * Highlighting is mutually exclusive.
9863 *
9864 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
9865 * @fires highlight
9866 * @chainable
9867 */
9868 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
9869 var i, len, highlighted,
9870 changed = false;
9871
9872 for ( i = 0, len = this.items.length; i < len; i++ ) {
9873 highlighted = this.items[i] === item;
9874 if ( this.items[i].isHighlighted() !== highlighted ) {
9875 this.items[i].setHighlighted( highlighted );
9876 changed = true;
9877 }
9878 }
9879 if ( changed ) {
9880 this.emit( 'highlight', item );
9881 }
9882
9883 return this;
9884 };
9885
9886 /**
9887 * Select an item.
9888 *
9889 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
9890 * @fires select
9891 * @chainable
9892 */
9893 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
9894 var i, len, selected,
9895 changed = false;
9896
9897 for ( i = 0, len = this.items.length; i < len; i++ ) {
9898 selected = this.items[i] === item;
9899 if ( this.items[i].isSelected() !== selected ) {
9900 this.items[i].setSelected( selected );
9901 changed = true;
9902 }
9903 }
9904 if ( changed ) {
9905 this.emit( 'select', item );
9906 }
9907
9908 return this;
9909 };
9910
9911 /**
9912 * Press an item.
9913 *
9914 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
9915 * @fires press
9916 * @chainable
9917 */
9918 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
9919 var i, len, pressed,
9920 changed = false;
9921
9922 for ( i = 0, len = this.items.length; i < len; i++ ) {
9923 pressed = this.items[i] === item;
9924 if ( this.items[i].isPressed() !== pressed ) {
9925 this.items[i].setPressed( pressed );
9926 changed = true;
9927 }
9928 }
9929 if ( changed ) {
9930 this.emit( 'press', item );
9931 }
9932
9933 return this;
9934 };
9935
9936 /**
9937 * Choose an item.
9938 *
9939 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
9940 * an item is selected using the keyboard or mouse.
9941 *
9942 * @param {OO.ui.OptionWidget} item Item to choose
9943 * @fires choose
9944 * @chainable
9945 */
9946 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
9947 this.selectItem( item );
9948 this.emit( 'choose', item );
9949
9950 return this;
9951 };
9952
9953 /**
9954 * Get an item relative to another one.
9955 *
9956 * @param {OO.ui.OptionWidget} item Item to start at
9957 * @param {number} direction Direction to move in
9958 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
9959 */
9960 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
9961 var inc = direction > 0 ? 1 : -1,
9962 len = this.items.length,
9963 index = item instanceof OO.ui.OptionWidget ?
9964 $.inArray( item, this.items ) : ( inc > 0 ? -1 : 0 ),
9965 stopAt = Math.max( Math.min( index, len - 1 ), 0 ),
9966 i = inc > 0 ?
9967 // Default to 0 instead of -1, if nothing is selected let's start at the beginning
9968 Math.max( index, -1 ) :
9969 // Default to n-1 instead of -1, if nothing is selected let's start at the end
9970 Math.min( index, len );
9971
9972 while ( true ) {
9973 i = ( i + inc + len ) % len;
9974 item = this.items[i];
9975 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
9976 return item;
9977 }
9978 // Stop iterating when we've looped all the way around
9979 if ( i === stopAt ) {
9980 break;
9981 }
9982 }
9983 return null;
9984 };
9985
9986 /**
9987 * Get the next selectable item.
9988 *
9989 * @return {OO.ui.OptionWidget|null} Item, `null` if ther aren't any selectable items
9990 */
9991 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
9992 var i, len, item;
9993
9994 for ( i = 0, len = this.items.length; i < len; i++ ) {
9995 item = this.items[i];
9996 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
9997 return item;
9998 }
9999 }
10000
10001 return null;
10002 };
10003
10004 /**
10005 * Add items.
10006 *
10007 * When items are added with the same values as existing items, the existing items will be
10008 * automatically removed before the new items are added.
10009 *
10010 * @param {OO.ui.OptionWidget[]} items Items to add
10011 * @param {number} [index] Index to insert items after
10012 * @fires add
10013 * @chainable
10014 */
10015 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
10016 var i, len, item, hash,
10017 remove = [];
10018
10019 for ( i = 0, len = items.length; i < len; i++ ) {
10020 item = items[i];
10021 hash = OO.getHash( item.getData() );
10022 if ( hash in this.hashes ) {
10023 // Remove item with same value
10024 remove.push( this.hashes[hash] );
10025 }
10026 this.hashes[hash] = item;
10027 }
10028 if ( remove.length ) {
10029 this.removeItems( remove );
10030 }
10031
10032 // Mixin method
10033 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
10034
10035 // Always provide an index, even if it was omitted
10036 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
10037
10038 return this;
10039 };
10040
10041 /**
10042 * Remove items.
10043 *
10044 * Items will be detached, not removed, so they can be used later.
10045 *
10046 * @param {OO.ui.OptionWidget[]} items Items to remove
10047 * @fires remove
10048 * @chainable
10049 */
10050 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
10051 var i, len, item, hash;
10052
10053 for ( i = 0, len = items.length; i < len; i++ ) {
10054 item = items[i];
10055 hash = OO.getHash( item.getData() );
10056 if ( hash in this.hashes ) {
10057 // Remove existing item
10058 delete this.hashes[hash];
10059 }
10060 if ( item.isSelected() ) {
10061 this.selectItem( null );
10062 }
10063 }
10064
10065 // Mixin method
10066 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
10067
10068 this.emit( 'remove', items );
10069
10070 return this;
10071 };
10072
10073 /**
10074 * Clear all items.
10075 *
10076 * Items will be detached, not removed, so they can be used later.
10077 *
10078 * @fires remove
10079 * @chainable
10080 */
10081 OO.ui.SelectWidget.prototype.clearItems = function () {
10082 var items = this.items.slice();
10083
10084 // Clear all items
10085 this.hashes = {};
10086 // Mixin method
10087 OO.ui.GroupWidget.prototype.clearItems.call( this );
10088 this.selectItem( null );
10089
10090 this.emit( 'remove', items );
10091
10092 return this;
10093 };
10094
10095 /**
10096 * Select widget containing button options.
10097 *
10098 * Use together with OO.ui.ButtonOptionWidget.
10099 *
10100 * @class
10101 * @extends OO.ui.SelectWidget
10102 *
10103 * @constructor
10104 * @param {Object} [config] Configuration options
10105 */
10106 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
10107 // Parent constructor
10108 OO.ui.ButtonSelectWidget.super.call( this, config );
10109
10110 // Initialization
10111 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
10112 };
10113
10114 /* Setup */
10115
10116 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
10117
10118 /**
10119 * Overlaid menu of options.
10120 *
10121 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
10122 * the menu.
10123 *
10124 * Use together with OO.ui.MenuItemWidget.
10125 *
10126 * @class
10127 * @extends OO.ui.SelectWidget
10128 * @mixins OO.ui.ClippableElement
10129 *
10130 * @constructor
10131 * @param {Object} [config] Configuration options
10132 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
10133 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
10134 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
10135 */
10136 OO.ui.MenuWidget = function OoUiMenuWidget( config ) {
10137 // Config intialization
10138 config = config || {};
10139
10140 // Parent constructor
10141 OO.ui.MenuWidget.super.call( this, config );
10142
10143 // Mixin constructors
10144 OO.ui.ClippableElement.call( this, this.$group, config );
10145
10146 // Properties
10147 this.flashing = false;
10148 this.visible = false;
10149 this.newItems = null;
10150 this.autoHide = config.autoHide === undefined || !!config.autoHide;
10151 this.$input = config.input ? config.input.$input : null;
10152 this.$widget = config.widget ? config.widget.$element : null;
10153 this.$previousFocus = null;
10154 this.isolated = !config.input;
10155 this.onKeyDownHandler = OO.ui.bind( this.onKeyDown, this );
10156 this.onDocumentMouseDownHandler = OO.ui.bind( this.onDocumentMouseDown, this );
10157
10158 // Initialization
10159 this.$element
10160 .hide()
10161 .addClass( 'oo-ui-menuWidget' );
10162 };
10163
10164 /* Setup */
10165
10166 OO.inheritClass( OO.ui.MenuWidget, OO.ui.SelectWidget );
10167 OO.mixinClass( OO.ui.MenuWidget, OO.ui.ClippableElement );
10168
10169 /* Methods */
10170
10171 /**
10172 * Handles document mouse down events.
10173 *
10174 * @param {jQuery.Event} e Key down event
10175 */
10176 OO.ui.MenuWidget.prototype.onDocumentMouseDown = function ( e ) {
10177 if ( !$.contains( this.$element[0], e.target ) && ( !this.$widget || !$.contains( this.$widget[0], e.target ) ) ) {
10178 this.toggle( false );
10179 }
10180 };
10181
10182 /**
10183 * Handles key down events.
10184 *
10185 * @param {jQuery.Event} e Key down event
10186 */
10187 OO.ui.MenuWidget.prototype.onKeyDown = function ( e ) {
10188 var nextItem,
10189 handled = false,
10190 highlightItem = this.getHighlightedItem();
10191
10192 if ( !this.isDisabled() && this.isVisible() ) {
10193 if ( !highlightItem ) {
10194 highlightItem = this.getSelectedItem();
10195 }
10196 switch ( e.keyCode ) {
10197 case OO.ui.Keys.ENTER:
10198 this.chooseItem( highlightItem );
10199 handled = true;
10200 break;
10201 case OO.ui.Keys.UP:
10202 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
10203 handled = true;
10204 break;
10205 case OO.ui.Keys.DOWN:
10206 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
10207 handled = true;
10208 break;
10209 case OO.ui.Keys.ESCAPE:
10210 if ( highlightItem ) {
10211 highlightItem.setHighlighted( false );
10212 }
10213 this.toggle( false );
10214 handled = true;
10215 break;
10216 }
10217
10218 if ( nextItem ) {
10219 this.highlightItem( nextItem );
10220 nextItem.scrollElementIntoView();
10221 }
10222
10223 if ( handled ) {
10224 e.preventDefault();
10225 e.stopPropagation();
10226 return false;
10227 }
10228 }
10229 };
10230
10231 /**
10232 * Bind key down listener.
10233 */
10234 OO.ui.MenuWidget.prototype.bindKeyDownListener = function () {
10235 if ( this.$input ) {
10236 this.$input.on( 'keydown', this.onKeyDownHandler );
10237 } else {
10238 // Capture menu navigation keys
10239 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
10240 }
10241 };
10242
10243 /**
10244 * Unbind key down listener.
10245 */
10246 OO.ui.MenuWidget.prototype.unbindKeyDownListener = function () {
10247 if ( this.$input ) {
10248 this.$input.off( 'keydown' );
10249 } else {
10250 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
10251 }
10252 };
10253
10254 /**
10255 * Choose an item.
10256 *
10257 * This will close the menu when done, unlike selectItem which only changes selection.
10258 *
10259 * @param {OO.ui.OptionWidget} item Item to choose
10260 * @chainable
10261 */
10262 OO.ui.MenuWidget.prototype.chooseItem = function ( item ) {
10263 var widget = this;
10264
10265 // Parent method
10266 OO.ui.MenuWidget.super.prototype.chooseItem.call( this, item );
10267
10268 if ( item && !this.flashing ) {
10269 this.flashing = true;
10270 item.flash().done( function () {
10271 widget.toggle( false );
10272 widget.flashing = false;
10273 } );
10274 } else {
10275 this.toggle( false );
10276 }
10277
10278 return this;
10279 };
10280
10281 /**
10282 * Add items.
10283 *
10284 * Adding an existing item (by value) will move it.
10285 *
10286 * @param {OO.ui.MenuItemWidget[]} items Items to add
10287 * @param {number} [index] Index to insert items after
10288 * @chainable
10289 */
10290 OO.ui.MenuWidget.prototype.addItems = function ( items, index ) {
10291 var i, len, item;
10292
10293 // Parent method
10294 OO.ui.MenuWidget.super.prototype.addItems.call( this, items, index );
10295
10296 // Auto-initialize
10297 if ( !this.newItems ) {
10298 this.newItems = [];
10299 }
10300
10301 for ( i = 0, len = items.length; i < len; i++ ) {
10302 item = items[i];
10303 if ( this.isVisible() ) {
10304 // Defer fitting label until
10305 item.fitLabel();
10306 } else {
10307 this.newItems.push( item );
10308 }
10309 }
10310
10311 return this;
10312 };
10313
10314 /**
10315 * @inheritdoc
10316 */
10317 OO.ui.MenuWidget.prototype.toggle = function ( visible ) {
10318 visible = !!visible && !!this.items.length;
10319
10320 var i, len,
10321 change = visible !== this.isVisible();
10322
10323 // Parent method
10324 OO.ui.MenuWidget.super.prototype.toggle.call( this, visible );
10325
10326 if ( change ) {
10327 if ( visible ) {
10328 this.bindKeyDownListener();
10329
10330 // Change focus to enable keyboard navigation
10331 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
10332 this.$previousFocus = this.$( ':focus' );
10333 this.$input.focus();
10334 }
10335 if ( this.newItems && this.newItems.length ) {
10336 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
10337 this.newItems[i].fitLabel();
10338 }
10339 this.newItems = null;
10340 }
10341 this.setClipping( true );
10342
10343 // Auto-hide
10344 if ( this.autoHide ) {
10345 this.getElementDocument().addEventListener(
10346 'mousedown', this.onDocumentMouseDownHandler, true
10347 );
10348 }
10349 } else {
10350 this.unbindKeyDownListener();
10351 if ( this.isolated && this.$previousFocus ) {
10352 this.$previousFocus.focus();
10353 this.$previousFocus = null;
10354 }
10355 this.getElementDocument().removeEventListener(
10356 'mousedown', this.onDocumentMouseDownHandler, true
10357 );
10358 this.setClipping( false );
10359 }
10360 }
10361
10362 return this;
10363 };
10364
10365 /**
10366 * Menu for a text input widget.
10367 *
10368 * This menu is specially designed to be positioned beneeth the text input widget. Even if the input
10369 * is in a different frame, the menu's position is automatically calulated and maintained when the
10370 * menu is toggled or the window is resized.
10371 *
10372 * @class
10373 * @extends OO.ui.MenuWidget
10374 *
10375 * @constructor
10376 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
10377 * @param {Object} [config] Configuration options
10378 * @cfg {jQuery} [$container=input.$element] Element to render menu under
10379 */
10380 OO.ui.TextInputMenuWidget = function OoUiTextInputMenuWidget( input, config ) {
10381 // Parent constructor
10382 OO.ui.TextInputMenuWidget.super.call( this, config );
10383
10384 // Properties
10385 this.input = input;
10386 this.$container = config.$container || this.input.$element;
10387 this.onWindowResizeHandler = OO.ui.bind( this.onWindowResize, this );
10388
10389 // Initialization
10390 this.$element.addClass( 'oo-ui-textInputMenuWidget' );
10391 };
10392
10393 /* Setup */
10394
10395 OO.inheritClass( OO.ui.TextInputMenuWidget, OO.ui.MenuWidget );
10396
10397 /* Methods */
10398
10399 /**
10400 * Handle window resize event.
10401 *
10402 * @param {jQuery.Event} e Window resize event
10403 */
10404 OO.ui.TextInputMenuWidget.prototype.onWindowResize = function () {
10405 this.position();
10406 };
10407
10408 /**
10409 * @inheritdoc
10410 */
10411 OO.ui.TextInputMenuWidget.prototype.toggle = function ( visible ) {
10412 visible = !!visible;
10413
10414 var change = visible !== this.isVisible();
10415
10416 // Parent method
10417 OO.ui.TextInputMenuWidget.super.prototype.toggle.call( this, visible );
10418
10419 if ( change ) {
10420 if ( this.isVisible() ) {
10421 this.position();
10422 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
10423 } else {
10424 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
10425 }
10426 }
10427 return this;
10428 };
10429
10430 /**
10431 * Position the menu.
10432 *
10433 * @chainable
10434 */
10435 OO.ui.TextInputMenuWidget.prototype.position = function () {
10436 var frameOffset,
10437 $container = this.$container,
10438 dimensions = $container.offset();
10439
10440 // Position under input
10441 dimensions.top += $container.height();
10442
10443 // Compensate for frame position if in a differnt frame
10444 if ( this.input.$.frame && this.input.$.context !== this.$element[0].ownerDocument ) {
10445 frameOffset = OO.ui.Element.getRelativePosition(
10446 this.input.$.frame.$element, this.$element.offsetParent()
10447 );
10448 dimensions.left += frameOffset.left;
10449 dimensions.top += frameOffset.top;
10450 } else {
10451 // Fix for RTL (for some reason, no need to fix if the frameoffset is set)
10452 if ( this.$element.css( 'direction' ) === 'rtl' ) {
10453 dimensions.right = this.$element.parent().position().left -
10454 $container.width() - dimensions.left;
10455 // Erase the value for 'left':
10456 delete dimensions.left;
10457 }
10458 }
10459 this.$element.css( dimensions );
10460 this.setIdealSize( $container.width() );
10461
10462 return this;
10463 };
10464
10465 /**
10466 * Structured list of items.
10467 *
10468 * Use with OO.ui.OutlineItemWidget.
10469 *
10470 * @class
10471 * @extends OO.ui.SelectWidget
10472 *
10473 * @constructor
10474 * @param {Object} [config] Configuration options
10475 */
10476 OO.ui.OutlineWidget = function OoUiOutlineWidget( config ) {
10477 // Config intialization
10478 config = config || {};
10479
10480 // Parent constructor
10481 OO.ui.OutlineWidget.super.call( this, config );
10482
10483 // Initialization
10484 this.$element.addClass( 'oo-ui-outlineWidget' );
10485 };
10486
10487 /* Setup */
10488
10489 OO.inheritClass( OO.ui.OutlineWidget, OO.ui.SelectWidget );
10490
10491 /**
10492 * Switch that slides on and off.
10493 *
10494 * @class
10495 * @extends OO.ui.Widget
10496 * @mixins OO.ui.ToggleWidget
10497 *
10498 * @constructor
10499 * @param {Object} [config] Configuration options
10500 * @cfg {boolean} [value=false] Initial value
10501 */
10502 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
10503 // Parent constructor
10504 OO.ui.ToggleSwitchWidget.super.call( this, config );
10505
10506 // Mixin constructors
10507 OO.ui.ToggleWidget.call( this, config );
10508
10509 // Properties
10510 this.dragging = false;
10511 this.dragStart = null;
10512 this.sliding = false;
10513 this.$glow = this.$( '<span>' );
10514 this.$grip = this.$( '<span>' );
10515
10516 // Events
10517 this.$element.on( 'click', OO.ui.bind( this.onClick, this ) );
10518
10519 // Initialization
10520 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
10521 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
10522 this.$element
10523 .addClass( 'oo-ui-toggleSwitchWidget' )
10524 .append( this.$glow, this.$grip );
10525 };
10526
10527 /* Setup */
10528
10529 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
10530 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
10531
10532 /* Methods */
10533
10534 /**
10535 * Handle mouse down events.
10536 *
10537 * @param {jQuery.Event} e Mouse down event
10538 */
10539 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
10540 if ( !this.isDisabled() && e.which === 1 ) {
10541 this.setValue( !this.value );
10542 }
10543 };
10544
10545 }( OO ) );