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