Merge "SpecialTrackingCategories: Read from the extension registry"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.6.3
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-01-16T00:05:04Z
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],
175 params = Array.prototype.slice.call( arguments, 1 );
176 if ( typeof message === 'string' ) {
177 // Perform $1 substitution
178 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
179 var i = parseInt( n, 10 );
180 return params[i - 1] !== undefined ? params[i - 1] : '$' + n;
181 } );
182 } else {
183 // Return placeholder if message not found
184 message = '[' + key + ']';
185 }
186 return message;
187 };
188
189 /**
190 * Package a message and arguments for deferred resolution.
191 *
192 * Use this when you are statically specifying a message and the message may not yet be present.
193 *
194 * @param {string} key Message key
195 * @param {Mixed...} [params] Message parameters
196 * @return {Function} Function that returns the resolved message when executed
197 */
198 OO.ui.deferMsg = function () {
199 var args = arguments;
200 return function () {
201 return OO.ui.msg.apply( OO.ui, args );
202 };
203 };
204
205 /**
206 * Resolve a message.
207 *
208 * If the message is a function it will be executed, otherwise it will pass through directly.
209 *
210 * @param {Function|string} msg Deferred message, or message text
211 * @return {string} Resolved message
212 */
213 OO.ui.resolveMsg = function ( msg ) {
214 if ( $.isFunction( msg ) ) {
215 return msg();
216 }
217 return msg;
218 };
219
220 } )();
221
222 /**
223 * Element that can be marked as pending.
224 *
225 * @abstract
226 * @class
227 *
228 * @constructor
229 * @param {Object} [config] Configuration options
230 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
231 */
232 OO.ui.PendingElement = function OoUiPendingElement( config ) {
233 // Configuration initialization
234 config = config || {};
235
236 // Properties
237 this.pending = 0;
238 this.$pending = null;
239
240 // Initialisation
241 this.setPendingElement( config.$pending || this.$element );
242 };
243
244 /* Setup */
245
246 OO.initClass( OO.ui.PendingElement );
247
248 /* Methods */
249
250 /**
251 * Set the pending element (and clean up any existing one).
252 *
253 * @param {jQuery} $pending The element to set to pending.
254 */
255 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
256 if ( this.$pending ) {
257 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
258 }
259
260 this.$pending = $pending;
261 if ( this.pending > 0 ) {
262 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
263 }
264 };
265
266 /**
267 * Check if input is pending.
268 *
269 * @return {boolean}
270 */
271 OO.ui.PendingElement.prototype.isPending = function () {
272 return !!this.pending;
273 };
274
275 /**
276 * Increase the pending stack.
277 *
278 * @chainable
279 */
280 OO.ui.PendingElement.prototype.pushPending = function () {
281 if ( this.pending === 0 ) {
282 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
283 this.updateThemeClasses();
284 }
285 this.pending++;
286
287 return this;
288 };
289
290 /**
291 * Reduce the pending stack.
292 *
293 * Clamped at zero.
294 *
295 * @chainable
296 */
297 OO.ui.PendingElement.prototype.popPending = function () {
298 if ( this.pending === 1 ) {
299 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
300 this.updateThemeClasses();
301 }
302 this.pending = Math.max( 0, this.pending - 1 );
303
304 return this;
305 };
306
307 /**
308 * List of actions.
309 *
310 * @abstract
311 * @class
312 * @mixins OO.EventEmitter
313 *
314 * @constructor
315 * @param {Object} [config] Configuration options
316 */
317 OO.ui.ActionSet = function OoUiActionSet( config ) {
318 // Configuration initialization
319 config = config || {};
320
321 // Mixin constructors
322 OO.EventEmitter.call( this );
323
324 // Properties
325 this.list = [];
326 this.categories = {
327 actions: 'getAction',
328 flags: 'getFlags',
329 modes: 'getModes'
330 };
331 this.categorized = {};
332 this.special = {};
333 this.others = [];
334 this.organized = false;
335 this.changing = false;
336 this.changed = false;
337 };
338
339 /* Setup */
340
341 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
342
343 /* Static Properties */
344
345 /**
346 * Symbolic name of dialog.
347 *
348 * @abstract
349 * @static
350 * @inheritable
351 * @property {string}
352 */
353 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
354
355 /* Events */
356
357 /**
358 * @event click
359 * @param {OO.ui.ActionWidget} action Action that was clicked
360 */
361
362 /**
363 * @event resize
364 * @param {OO.ui.ActionWidget} action Action that was resized
365 */
366
367 /**
368 * @event add
369 * @param {OO.ui.ActionWidget[]} added Actions added
370 */
371
372 /**
373 * @event remove
374 * @param {OO.ui.ActionWidget[]} added Actions removed
375 */
376
377 /**
378 * @event change
379 */
380
381 /* Methods */
382
383 /**
384 * Handle action change events.
385 *
386 * @fires change
387 */
388 OO.ui.ActionSet.prototype.onActionChange = function () {
389 this.organized = false;
390 if ( this.changing ) {
391 this.changed = true;
392 } else {
393 this.emit( 'change' );
394 }
395 };
396
397 /**
398 * Check if a action is one of the special actions.
399 *
400 * @param {OO.ui.ActionWidget} action Action to check
401 * @return {boolean} Action is special
402 */
403 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
404 var flag;
405
406 for ( flag in this.special ) {
407 if ( action === this.special[flag] ) {
408 return true;
409 }
410 }
411
412 return false;
413 };
414
415 /**
416 * Get actions.
417 *
418 * @param {Object} [filters] Filters to use, omit to get all actions
419 * @param {string|string[]} [filters.actions] Actions that actions must have
420 * @param {string|string[]} [filters.flags] Flags that actions must have
421 * @param {string|string[]} [filters.modes] Modes that actions must have
422 * @param {boolean} [filters.visible] Actions must be visible
423 * @param {boolean} [filters.disabled] Actions must be disabled
424 * @return {OO.ui.ActionWidget[]} Actions matching all criteria
425 */
426 OO.ui.ActionSet.prototype.get = function ( filters ) {
427 var i, len, list, category, actions, index, match, matches;
428
429 if ( filters ) {
430 this.organize();
431
432 // Collect category candidates
433 matches = [];
434 for ( category in this.categorized ) {
435 list = filters[category];
436 if ( list ) {
437 if ( !Array.isArray( list ) ) {
438 list = [ list ];
439 }
440 for ( i = 0, len = list.length; i < len; i++ ) {
441 actions = this.categorized[category][list[i]];
442 if ( Array.isArray( actions ) ) {
443 matches.push.apply( matches, actions );
444 }
445 }
446 }
447 }
448 // Remove by boolean filters
449 for ( i = 0, len = matches.length; i < len; i++ ) {
450 match = matches[i];
451 if (
452 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
453 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
454 ) {
455 matches.splice( i, 1 );
456 len--;
457 i--;
458 }
459 }
460 // Remove duplicates
461 for ( i = 0, len = matches.length; i < len; i++ ) {
462 match = matches[i];
463 index = matches.lastIndexOf( match );
464 while ( index !== i ) {
465 matches.splice( index, 1 );
466 len--;
467 index = matches.lastIndexOf( match );
468 }
469 }
470 return matches;
471 }
472 return this.list.slice();
473 };
474
475 /**
476 * Get special actions.
477 *
478 * Special actions are the first visible actions with special flags, such as 'safe' and 'primary'.
479 * Special flags can be configured by changing #static-specialFlags in a subclass.
480 *
481 * @return {OO.ui.ActionWidget|null} Safe action
482 */
483 OO.ui.ActionSet.prototype.getSpecial = function () {
484 this.organize();
485 return $.extend( {}, this.special );
486 };
487
488 /**
489 * Get other actions.
490 *
491 * Other actions include all non-special visible actions.
492 *
493 * @return {OO.ui.ActionWidget[]} Other actions
494 */
495 OO.ui.ActionSet.prototype.getOthers = function () {
496 this.organize();
497 return this.others.slice();
498 };
499
500 /**
501 * Toggle actions based on their modes.
502 *
503 * Unlike calling toggle on actions with matching flags, this will enforce mutually exclusive
504 * visibility; matching actions will be shown, non-matching actions will be hidden.
505 *
506 * @param {string} mode Mode actions must have
507 * @chainable
508 * @fires toggle
509 * @fires change
510 */
511 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
512 var i, len, action;
513
514 this.changing = true;
515 for ( i = 0, len = this.list.length; i < len; i++ ) {
516 action = this.list[i];
517 action.toggle( action.hasMode( mode ) );
518 }
519
520 this.organized = false;
521 this.changing = false;
522 this.emit( 'change' );
523
524 return this;
525 };
526
527 /**
528 * Change which actions are able to be performed.
529 *
530 * Actions with matching actions will be disabled/enabled. Other actions will not be changed.
531 *
532 * @param {Object.<string,boolean>} actions List of abilities, keyed by action name, values
533 * indicate actions are able to be performed
534 * @chainable
535 */
536 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
537 var i, len, action, item;
538
539 for ( i = 0, len = this.list.length; i < len; i++ ) {
540 item = this.list[i];
541 action = item.getAction();
542 if ( actions[action] !== undefined ) {
543 item.setDisabled( !actions[action] );
544 }
545 }
546
547 return this;
548 };
549
550 /**
551 * Executes a function once per action.
552 *
553 * When making changes to multiple actions, use this method instead of iterating over the actions
554 * manually to defer emitting a change event until after all actions have been changed.
555 *
556 * @param {Object|null} actions Filters to use for which actions to iterate over; see #get
557 * @param {Function} callback Callback to run for each action; callback is invoked with three
558 * arguments: the action, the action's index, the list of actions being iterated over
559 * @chainable
560 */
561 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
562 this.changed = false;
563 this.changing = true;
564 this.get( filter ).forEach( callback );
565 this.changing = false;
566 if ( this.changed ) {
567 this.emit( 'change' );
568 }
569
570 return this;
571 };
572
573 /**
574 * Add actions.
575 *
576 * @param {OO.ui.ActionWidget[]} actions Actions to add
577 * @chainable
578 * @fires add
579 * @fires change
580 */
581 OO.ui.ActionSet.prototype.add = function ( actions ) {
582 var i, len, action;
583
584 this.changing = true;
585 for ( i = 0, len = actions.length; i < len; i++ ) {
586 action = actions[i];
587 action.connect( this, {
588 click: [ 'emit', 'click', action ],
589 resize: [ 'emit', 'resize', action ],
590 toggle: [ 'onActionChange' ]
591 } );
592 this.list.push( action );
593 }
594 this.organized = false;
595 this.emit( 'add', actions );
596 this.changing = false;
597 this.emit( 'change' );
598
599 return this;
600 };
601
602 /**
603 * Remove actions.
604 *
605 * @param {OO.ui.ActionWidget[]} actions Actions to remove
606 * @chainable
607 * @fires remove
608 * @fires change
609 */
610 OO.ui.ActionSet.prototype.remove = function ( actions ) {
611 var i, len, index, action;
612
613 this.changing = true;
614 for ( i = 0, len = actions.length; i < len; i++ ) {
615 action = actions[i];
616 index = this.list.indexOf( action );
617 if ( index !== -1 ) {
618 action.disconnect( this );
619 this.list.splice( index, 1 );
620 }
621 }
622 this.organized = false;
623 this.emit( 'remove', actions );
624 this.changing = false;
625 this.emit( 'change' );
626
627 return this;
628 };
629
630 /**
631 * Remove all actions.
632 *
633 * @chainable
634 * @fires remove
635 * @fires change
636 */
637 OO.ui.ActionSet.prototype.clear = function () {
638 var i, len, action,
639 removed = this.list.slice();
640
641 this.changing = true;
642 for ( i = 0, len = this.list.length; i < len; i++ ) {
643 action = this.list[i];
644 action.disconnect( this );
645 }
646
647 this.list = [];
648
649 this.organized = false;
650 this.emit( 'remove', removed );
651 this.changing = false;
652 this.emit( 'change' );
653
654 return this;
655 };
656
657 /**
658 * Organize actions.
659 *
660 * This is called whenever organized information is requested. It will only reorganize the actions
661 * if something has changed since the last time it ran.
662 *
663 * @private
664 * @chainable
665 */
666 OO.ui.ActionSet.prototype.organize = function () {
667 var i, iLen, j, jLen, flag, action, category, list, item, special,
668 specialFlags = this.constructor.static.specialFlags;
669
670 if ( !this.organized ) {
671 this.categorized = {};
672 this.special = {};
673 this.others = [];
674 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
675 action = this.list[i];
676 if ( action.isVisible() ) {
677 // Populate categories
678 for ( category in this.categories ) {
679 if ( !this.categorized[category] ) {
680 this.categorized[category] = {};
681 }
682 list = action[this.categories[category]]();
683 if ( !Array.isArray( list ) ) {
684 list = [ list ];
685 }
686 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
687 item = list[j];
688 if ( !this.categorized[category][item] ) {
689 this.categorized[category][item] = [];
690 }
691 this.categorized[category][item].push( action );
692 }
693 }
694 // Populate special/others
695 special = false;
696 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
697 flag = specialFlags[j];
698 if ( !this.special[flag] && action.hasFlag( flag ) ) {
699 this.special[flag] = action;
700 special = true;
701 break;
702 }
703 }
704 if ( !special ) {
705 this.others.push( action );
706 }
707 }
708 }
709 this.organized = true;
710 }
711
712 return this;
713 };
714
715 /**
716 * DOM element abstraction.
717 *
718 * @abstract
719 * @class
720 *
721 * @constructor
722 * @param {Object} [config] Configuration options
723 * @cfg {Function} [$] jQuery for the frame the widget is in
724 * @cfg {string[]} [classes] CSS class names to add
725 * @cfg {string} [id] HTML id attribute
726 * @cfg {string} [text] Text to insert
727 * @cfg {jQuery} [$content] Content elements to append (after text)
728 * @cfg {Mixed} [data] Element data
729 */
730 OO.ui.Element = function OoUiElement( config ) {
731 // Configuration initialization
732 config = config || {};
733
734 // Properties
735 this.$ = config.$ || OO.ui.Element.static.getJQuery( document );
736 this.data = config.data;
737 this.$element = this.$( this.$.context.createElement( this.getTagName() ) );
738 this.elementGroup = null;
739 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
740 this.updateThemeClassesPending = false;
741
742 // Initialization
743 if ( $.isArray( config.classes ) ) {
744 this.$element.addClass( config.classes.join( ' ' ) );
745 }
746 if ( config.id ) {
747 this.$element.attr( 'id', config.id );
748 }
749 if ( config.text ) {
750 this.$element.text( config.text );
751 }
752 if ( config.$content ) {
753 this.$element.append( config.$content );
754 }
755 };
756
757 /* Setup */
758
759 OO.initClass( OO.ui.Element );
760
761 /* Static Properties */
762
763 /**
764 * HTML tag name.
765 *
766 * This may be ignored if #getTagName is overridden.
767 *
768 * @static
769 * @inheritable
770 * @property {string}
771 */
772 OO.ui.Element.static.tagName = 'div';
773
774 /* Static Methods */
775
776 /**
777 * Get a jQuery function within a specific document.
778 *
779 * @static
780 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
781 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
782 * not in an iframe
783 * @return {Function} Bound jQuery function
784 */
785 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
786 function wrapper( selector ) {
787 return $( selector, wrapper.context );
788 }
789
790 wrapper.context = this.getDocument( context );
791
792 if ( $iframe ) {
793 wrapper.$iframe = $iframe;
794 }
795
796 return wrapper;
797 };
798
799 /**
800 * Get the document of an element.
801 *
802 * @static
803 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
804 * @return {HTMLDocument|null} Document object
805 */
806 OO.ui.Element.static.getDocument = function ( obj ) {
807 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
808 return ( obj[0] && obj[0].ownerDocument ) ||
809 // Empty jQuery selections might have a context
810 obj.context ||
811 // HTMLElement
812 obj.ownerDocument ||
813 // Window
814 obj.document ||
815 // HTMLDocument
816 ( obj.nodeType === 9 && obj ) ||
817 null;
818 };
819
820 /**
821 * Get the window of an element or document.
822 *
823 * @static
824 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
825 * @return {Window} Window object
826 */
827 OO.ui.Element.static.getWindow = function ( obj ) {
828 var doc = this.getDocument( obj );
829 return doc.parentWindow || doc.defaultView;
830 };
831
832 /**
833 * Get the direction of an element or document.
834 *
835 * @static
836 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
837 * @return {string} Text direction, either 'ltr' or 'rtl'
838 */
839 OO.ui.Element.static.getDir = function ( obj ) {
840 var isDoc, isWin;
841
842 if ( obj instanceof jQuery ) {
843 obj = obj[0];
844 }
845 isDoc = obj.nodeType === 9;
846 isWin = obj.document !== undefined;
847 if ( isDoc || isWin ) {
848 if ( isWin ) {
849 obj = obj.document;
850 }
851 obj = obj.body;
852 }
853 return $( obj ).css( 'direction' );
854 };
855
856 /**
857 * Get the offset between two frames.
858 *
859 * TODO: Make this function not use recursion.
860 *
861 * @static
862 * @param {Window} from Window of the child frame
863 * @param {Window} [to=window] Window of the parent frame
864 * @param {Object} [offset] Offset to start with, used internally
865 * @return {Object} Offset object, containing left and top properties
866 */
867 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
868 var i, len, frames, frame, rect;
869
870 if ( !to ) {
871 to = window;
872 }
873 if ( !offset ) {
874 offset = { top: 0, left: 0 };
875 }
876 if ( from.parent === from ) {
877 return offset;
878 }
879
880 // Get iframe element
881 frames = from.parent.document.getElementsByTagName( 'iframe' );
882 for ( i = 0, len = frames.length; i < len; i++ ) {
883 if ( frames[i].contentWindow === from ) {
884 frame = frames[i];
885 break;
886 }
887 }
888
889 // Recursively accumulate offset values
890 if ( frame ) {
891 rect = frame.getBoundingClientRect();
892 offset.left += rect.left;
893 offset.top += rect.top;
894 if ( from !== to ) {
895 this.getFrameOffset( from.parent, offset );
896 }
897 }
898 return offset;
899 };
900
901 /**
902 * Get the offset between two elements.
903 *
904 * The two elements may be in a different frame, but in that case the frame $element is in must
905 * be contained in the frame $anchor is in.
906 *
907 * @static
908 * @param {jQuery} $element Element whose position to get
909 * @param {jQuery} $anchor Element to get $element's position relative to
910 * @return {Object} Translated position coordinates, containing top and left properties
911 */
912 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
913 var iframe, iframePos,
914 pos = $element.offset(),
915 anchorPos = $anchor.offset(),
916 elementDocument = this.getDocument( $element ),
917 anchorDocument = this.getDocument( $anchor );
918
919 // If $element isn't in the same document as $anchor, traverse up
920 while ( elementDocument !== anchorDocument ) {
921 iframe = elementDocument.defaultView.frameElement;
922 if ( !iframe ) {
923 throw new Error( '$element frame is not contained in $anchor frame' );
924 }
925 iframePos = $( iframe ).offset();
926 pos.left += iframePos.left;
927 pos.top += iframePos.top;
928 elementDocument = iframe.ownerDocument;
929 }
930 pos.left -= anchorPos.left;
931 pos.top -= anchorPos.top;
932 return pos;
933 };
934
935 /**
936 * Get element border sizes.
937 *
938 * @static
939 * @param {HTMLElement} el Element to measure
940 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
941 */
942 OO.ui.Element.static.getBorders = function ( el ) {
943 var doc = el.ownerDocument,
944 win = doc.parentWindow || doc.defaultView,
945 style = win && win.getComputedStyle ?
946 win.getComputedStyle( el, null ) :
947 el.currentStyle,
948 $el = $( el ),
949 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
950 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
951 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
952 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
953
954 return {
955 top: top,
956 left: left,
957 bottom: bottom,
958 right: right
959 };
960 };
961
962 /**
963 * Get dimensions of an element or window.
964 *
965 * @static
966 * @param {HTMLElement|Window} el Element to measure
967 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
968 */
969 OO.ui.Element.static.getDimensions = function ( el ) {
970 var $el, $win,
971 doc = el.ownerDocument || el.document,
972 win = doc.parentWindow || doc.defaultView;
973
974 if ( win === el || el === doc.documentElement ) {
975 $win = $( win );
976 return {
977 borders: { top: 0, left: 0, bottom: 0, right: 0 },
978 scroll: {
979 top: $win.scrollTop(),
980 left: $win.scrollLeft()
981 },
982 scrollbar: { right: 0, bottom: 0 },
983 rect: {
984 top: 0,
985 left: 0,
986 bottom: $win.innerHeight(),
987 right: $win.innerWidth()
988 }
989 };
990 } else {
991 $el = $( el );
992 return {
993 borders: this.getBorders( el ),
994 scroll: {
995 top: $el.scrollTop(),
996 left: $el.scrollLeft()
997 },
998 scrollbar: {
999 right: $el.innerWidth() - el.clientWidth,
1000 bottom: $el.innerHeight() - el.clientHeight
1001 },
1002 rect: el.getBoundingClientRect()
1003 };
1004 }
1005 };
1006
1007 /**
1008 * Get scrollable object parent
1009 *
1010 * documentElement can't be used to get or set the scrollTop
1011 * property on Blink. Changing and testing its value lets us
1012 * use 'body' or 'documentElement' based on what is working.
1013 *
1014 * https://code.google.com/p/chromium/issues/detail?id=303131
1015 *
1016 * @static
1017 * @param {HTMLElement} el Element to find scrollable parent for
1018 * @return {HTMLElement} Scrollable parent
1019 */
1020 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1021 var scrollTop, body;
1022
1023 if ( OO.ui.scrollableElement === undefined ) {
1024 body = el.ownerDocument.body;
1025 scrollTop = body.scrollTop;
1026 body.scrollTop = 1;
1027
1028 if ( body.scrollTop === 1 ) {
1029 body.scrollTop = scrollTop;
1030 OO.ui.scrollableElement = 'body';
1031 } else {
1032 OO.ui.scrollableElement = 'documentElement';
1033 }
1034 }
1035
1036 return el.ownerDocument[ OO.ui.scrollableElement ];
1037 };
1038
1039 /**
1040 * Get closest scrollable container.
1041 *
1042 * Traverses up until either a scrollable element or the root is reached, in which case the window
1043 * will be returned.
1044 *
1045 * @static
1046 * @param {HTMLElement} el Element to find scrollable container for
1047 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1048 * @return {HTMLElement} Closest scrollable container
1049 */
1050 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1051 var i, val,
1052 props = [ 'overflow' ],
1053 $parent = $( el ).parent();
1054
1055 if ( dimension === 'x' || dimension === 'y' ) {
1056 props.push( 'overflow-' + dimension );
1057 }
1058
1059 while ( $parent.length ) {
1060 if ( $parent[0] === this.getRootScrollableElement( el ) ) {
1061 return $parent[0];
1062 }
1063 i = props.length;
1064 while ( i-- ) {
1065 val = $parent.css( props[i] );
1066 if ( val === 'auto' || val === 'scroll' ) {
1067 return $parent[0];
1068 }
1069 }
1070 $parent = $parent.parent();
1071 }
1072 return this.getDocument( el ).body;
1073 };
1074
1075 /**
1076 * Scroll element into view.
1077 *
1078 * @static
1079 * @param {HTMLElement} el Element to scroll into view
1080 * @param {Object} [config] Configuration options
1081 * @param {string} [config.duration] jQuery animation duration value
1082 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1083 * to scroll in both directions
1084 * @param {Function} [config.complete] Function to call when scrolling completes
1085 */
1086 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1087 // Configuration initialization
1088 config = config || {};
1089
1090 var rel, anim = {},
1091 callback = typeof config.complete === 'function' && config.complete,
1092 sc = this.getClosestScrollableContainer( el, config.direction ),
1093 $sc = $( sc ),
1094 eld = this.getDimensions( el ),
1095 scd = this.getDimensions( sc ),
1096 $win = $( this.getWindow( el ) );
1097
1098 // Compute the distances between the edges of el and the edges of the scroll viewport
1099 if ( $sc.is( 'html, body' ) ) {
1100 // If the scrollable container is the root, this is easy
1101 rel = {
1102 top: eld.rect.top,
1103 bottom: $win.innerHeight() - eld.rect.bottom,
1104 left: eld.rect.left,
1105 right: $win.innerWidth() - eld.rect.right
1106 };
1107 } else {
1108 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1109 rel = {
1110 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1111 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1112 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1113 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1114 };
1115 }
1116
1117 if ( !config.direction || config.direction === 'y' ) {
1118 if ( rel.top < 0 ) {
1119 anim.scrollTop = scd.scroll.top + rel.top;
1120 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1121 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1122 }
1123 }
1124 if ( !config.direction || config.direction === 'x' ) {
1125 if ( rel.left < 0 ) {
1126 anim.scrollLeft = scd.scroll.left + rel.left;
1127 } else if ( rel.left > 0 && rel.right < 0 ) {
1128 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1129 }
1130 }
1131 if ( !$.isEmptyObject( anim ) ) {
1132 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1133 if ( callback ) {
1134 $sc.queue( function ( next ) {
1135 callback();
1136 next();
1137 } );
1138 }
1139 } else {
1140 if ( callback ) {
1141 callback();
1142 }
1143 }
1144 };
1145
1146 /* Methods */
1147
1148 /**
1149 * Get element data.
1150 *
1151 * @return {Mixed} Element data
1152 */
1153 OO.ui.Element.prototype.getData = function () {
1154 return this.data;
1155 };
1156
1157 /**
1158 * Set element data.
1159 *
1160 * @param {Mixed} Element data
1161 * @chainable
1162 */
1163 OO.ui.Element.prototype.setData = function ( data ) {
1164 this.data = data;
1165 return this;
1166 };
1167
1168 /**
1169 * Check if element supports one or more methods.
1170 *
1171 * @param {string|string[]} methods Method or list of methods to check
1172 * @return {boolean} All methods are supported
1173 */
1174 OO.ui.Element.prototype.supports = function ( methods ) {
1175 var i, len,
1176 support = 0;
1177
1178 methods = $.isArray( methods ) ? methods : [ methods ];
1179 for ( i = 0, len = methods.length; i < len; i++ ) {
1180 if ( $.isFunction( this[methods[i]] ) ) {
1181 support++;
1182 }
1183 }
1184
1185 return methods.length === support;
1186 };
1187
1188 /**
1189 * Update the theme-provided classes.
1190 *
1191 * @localdoc This is called in element mixins and widget classes any time state changes.
1192 * Updating is debounced, minimizing overhead of changing multiple attributes and
1193 * guaranteeing that theme updates do not occur within an element's constructor
1194 */
1195 OO.ui.Element.prototype.updateThemeClasses = function () {
1196 if ( !this.updateThemeClassesPending ) {
1197 this.updateThemeClassesPending = true;
1198 setTimeout( this.debouncedUpdateThemeClassesHandler );
1199 }
1200 };
1201
1202 /**
1203 * @private
1204 */
1205 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1206 OO.ui.theme.updateElementClasses( this );
1207 this.updateThemeClassesPending = false;
1208 };
1209
1210 /**
1211 * Get the HTML tag name.
1212 *
1213 * Override this method to base the result on instance information.
1214 *
1215 * @return {string} HTML tag name
1216 */
1217 OO.ui.Element.prototype.getTagName = function () {
1218 return this.constructor.static.tagName;
1219 };
1220
1221 /**
1222 * Check if the element is attached to the DOM
1223 * @return {boolean} The element is attached to the DOM
1224 */
1225 OO.ui.Element.prototype.isElementAttached = function () {
1226 return $.contains( this.getElementDocument(), this.$element[0] );
1227 };
1228
1229 /**
1230 * Get the DOM document.
1231 *
1232 * @return {HTMLDocument} Document object
1233 */
1234 OO.ui.Element.prototype.getElementDocument = function () {
1235 // Don't use this.$.context because subclasses can rebind this.$
1236 // Don't cache this in other ways either because subclasses could can change this.$element
1237 return OO.ui.Element.static.getDocument( this.$element );
1238 };
1239
1240 /**
1241 * Get the DOM window.
1242 *
1243 * @return {Window} Window object
1244 */
1245 OO.ui.Element.prototype.getElementWindow = function () {
1246 return OO.ui.Element.static.getWindow( this.$element );
1247 };
1248
1249 /**
1250 * Get closest scrollable container.
1251 */
1252 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1253 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[0] );
1254 };
1255
1256 /**
1257 * Get group element is in.
1258 *
1259 * @return {OO.ui.GroupElement|null} Group element, null if none
1260 */
1261 OO.ui.Element.prototype.getElementGroup = function () {
1262 return this.elementGroup;
1263 };
1264
1265 /**
1266 * Set group element is in.
1267 *
1268 * @param {OO.ui.GroupElement|null} group Group element, null if none
1269 * @chainable
1270 */
1271 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1272 this.elementGroup = group;
1273 return this;
1274 };
1275
1276 /**
1277 * Scroll element into view.
1278 *
1279 * @param {Object} [config] Configuration options
1280 */
1281 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1282 return OO.ui.Element.static.scrollIntoView( this.$element[0], config );
1283 };
1284
1285 /**
1286 * Container for elements.
1287 *
1288 * @abstract
1289 * @class
1290 * @extends OO.ui.Element
1291 * @mixins OO.EventEmitter
1292 *
1293 * @constructor
1294 * @param {Object} [config] Configuration options
1295 */
1296 OO.ui.Layout = function OoUiLayout( config ) {
1297 // Configuration initialization
1298 config = config || {};
1299
1300 // Parent constructor
1301 OO.ui.Layout.super.call( this, config );
1302
1303 // Mixin constructors
1304 OO.EventEmitter.call( this );
1305
1306 // Initialization
1307 this.$element.addClass( 'oo-ui-layout' );
1308 };
1309
1310 /* Setup */
1311
1312 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1313 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1314
1315 /**
1316 * User interface control.
1317 *
1318 * @abstract
1319 * @class
1320 * @extends OO.ui.Element
1321 * @mixins OO.EventEmitter
1322 *
1323 * @constructor
1324 * @param {Object} [config] Configuration options
1325 * @cfg {boolean} [disabled=false] Disable
1326 */
1327 OO.ui.Widget = function OoUiWidget( config ) {
1328 // Initialize config
1329 config = $.extend( { disabled: false }, config );
1330
1331 // Parent constructor
1332 OO.ui.Widget.super.call( this, config );
1333
1334 // Mixin constructors
1335 OO.EventEmitter.call( this );
1336
1337 // Properties
1338 this.visible = true;
1339 this.disabled = null;
1340 this.wasDisabled = null;
1341
1342 // Initialization
1343 this.$element.addClass( 'oo-ui-widget' );
1344 this.setDisabled( !!config.disabled );
1345 };
1346
1347 /* Setup */
1348
1349 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1350 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1351
1352 /* Events */
1353
1354 /**
1355 * @event disable
1356 * @param {boolean} disabled Widget is disabled
1357 */
1358
1359 /**
1360 * @event toggle
1361 * @param {boolean} visible Widget is visible
1362 */
1363
1364 /* Methods */
1365
1366 /**
1367 * Check if the widget is disabled.
1368 *
1369 * @return {boolean} Button is disabled
1370 */
1371 OO.ui.Widget.prototype.isDisabled = function () {
1372 return this.disabled;
1373 };
1374
1375 /**
1376 * Check if widget is visible.
1377 *
1378 * @return {boolean} Widget is visible
1379 */
1380 OO.ui.Widget.prototype.isVisible = function () {
1381 return this.visible;
1382 };
1383
1384 /**
1385 * Set the disabled state of the widget.
1386 *
1387 * This should probably change the widgets' appearance and prevent it from being used.
1388 *
1389 * @param {boolean} disabled Disable widget
1390 * @chainable
1391 */
1392 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1393 var isDisabled;
1394
1395 this.disabled = !!disabled;
1396 isDisabled = this.isDisabled();
1397 if ( isDisabled !== this.wasDisabled ) {
1398 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1399 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1400 this.emit( 'disable', isDisabled );
1401 this.updateThemeClasses();
1402 }
1403 this.wasDisabled = isDisabled;
1404
1405 return this;
1406 };
1407
1408 /**
1409 * Toggle visibility of widget.
1410 *
1411 * @param {boolean} [show] Make widget visible, omit to toggle visibility
1412 * @fires visible
1413 * @chainable
1414 */
1415 OO.ui.Widget.prototype.toggle = function ( show ) {
1416 show = show === undefined ? !this.visible : !!show;
1417
1418 if ( show !== this.isVisible() ) {
1419 this.visible = show;
1420 this.$element.toggle( show );
1421 this.emit( 'toggle', show );
1422 }
1423
1424 return this;
1425 };
1426
1427 /**
1428 * Update the disabled state, in case of changes in parent widget.
1429 *
1430 * @chainable
1431 */
1432 OO.ui.Widget.prototype.updateDisabled = function () {
1433 this.setDisabled( this.disabled );
1434 return this;
1435 };
1436
1437 /**
1438 * Container for elements in a child frame.
1439 *
1440 * Use together with OO.ui.WindowManager.
1441 *
1442 * @abstract
1443 * @class
1444 * @extends OO.ui.Element
1445 * @mixins OO.EventEmitter
1446 *
1447 * When a window is opened, the setup and ready processes are executed. Similarly, the hold and
1448 * teardown processes are executed when the window is closed.
1449 *
1450 * - {@link OO.ui.WindowManager#openWindow} or {@link #open} methods are used to start opening
1451 * - Window manager begins opening window
1452 * - {@link #getSetupProcess} method is called and its result executed
1453 * - {@link #getReadyProcess} method is called and its result executed
1454 * - Window is now open
1455 *
1456 * - {@link OO.ui.WindowManager#closeWindow} or {@link #close} methods are used to start closing
1457 * - Window manager begins closing window
1458 * - {@link #getHoldProcess} method is called and its result executed
1459 * - {@link #getTeardownProcess} method is called and its result executed
1460 * - Window is now closed
1461 *
1462 * Each process (setup, ready, hold and teardown) can be extended in subclasses by overriding
1463 * {@link #getSetupProcess}, {@link #getReadyProcess}, {@link #getHoldProcess} and
1464 * {@link #getTeardownProcess} respectively. Each process is executed in series, so asynchronous
1465 * processing can complete. Always assume window processes are executed asynchronously. See
1466 * OO.ui.Process for more details about how to work with processes. Some events, as well as the
1467 * #open and #close methods, provide promises which are resolved when the window enters a new state.
1468 *
1469 * Sizing of windows is specified using symbolic names which are interpreted by the window manager.
1470 * If the requested size is not recognized, the window manager will choose a sensible fallback.
1471 *
1472 * @constructor
1473 * @param {Object} [config] Configuration options
1474 * @cfg {string} [size] Symbolic name of dialog size, `small`, `medium`, `large`, `larger` or
1475 * `full`; omit to use #static-size
1476 */
1477 OO.ui.Window = function OoUiWindow( config ) {
1478 // Configuration initialization
1479 config = config || {};
1480
1481 // Parent constructor
1482 OO.ui.Window.super.call( this, config );
1483
1484 // Mixin constructors
1485 OO.EventEmitter.call( this );
1486
1487 // Properties
1488 this.manager = null;
1489 this.initialized = false;
1490 this.visible = false;
1491 this.opening = null;
1492 this.closing = null;
1493 this.opened = null;
1494 this.timing = null;
1495 this.loading = null;
1496 this.size = config.size || this.constructor.static.size;
1497 this.$frame = this.$( '<div>' );
1498 this.$overlay = this.$( '<div>' );
1499
1500 // Initialization
1501 this.$element
1502 .addClass( 'oo-ui-window' )
1503 .append( this.$frame, this.$overlay );
1504 this.$frame.addClass( 'oo-ui-window-frame' );
1505 this.$overlay.addClass( 'oo-ui-window-overlay' );
1506
1507 // NOTE: Additional initialization will occur when #setManager is called
1508 };
1509
1510 /* Setup */
1511
1512 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1513 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1514
1515 /* Static Properties */
1516
1517 /**
1518 * Symbolic name of size.
1519 *
1520 * Size is used if no size is configured during construction.
1521 *
1522 * @static
1523 * @inheritable
1524 * @property {string}
1525 */
1526 OO.ui.Window.static.size = 'medium';
1527
1528 /* Static Methods */
1529
1530 /**
1531 * Transplant the CSS styles from as parent document to a frame's document.
1532 *
1533 * This loops over the style sheets in the parent document, and copies their nodes to the
1534 * frame's document. It then polls the document to see when all styles have loaded, and once they
1535 * have, resolves the promise.
1536 *
1537 * If the styles still haven't loaded after a long time (5 seconds by default), we give up waiting
1538 * and resolve the promise anyway. This protects against cases like a display: none; iframe in
1539 * Firefox, where the styles won't load until the iframe becomes visible.
1540 *
1541 * For details of how we arrived at the strategy used in this function, see #load.
1542 *
1543 * @static
1544 * @inheritable
1545 * @param {HTMLDocument} parentDoc Document to transplant styles from
1546 * @param {HTMLDocument} frameDoc Document to transplant styles to
1547 * @param {number} [timeout=5000] How long to wait before giving up (in ms). If 0, never give up.
1548 * @return {jQuery.Promise} Promise resolved when styles have loaded
1549 */
1550 OO.ui.Window.static.transplantStyles = function ( parentDoc, frameDoc, timeout ) {
1551 var i, numSheets, styleNode, styleText, newNode, timeoutID, pollNodeId, $pendingPollNodes,
1552 $pollNodes = $( [] ),
1553 // Fake font-family value
1554 fontFamily = 'oo-ui-frame-transplantStyles-loaded',
1555 nextIndex = parentDoc.oouiFrameTransplantStylesNextIndex || 0,
1556 deferred = $.Deferred();
1557
1558 for ( i = 0, numSheets = parentDoc.styleSheets.length; i < numSheets; i++ ) {
1559 styleNode = parentDoc.styleSheets[i].ownerNode;
1560 if ( styleNode.disabled ) {
1561 continue;
1562 }
1563
1564 if ( styleNode.nodeName.toLowerCase() === 'link' ) {
1565 // External stylesheet; use @import
1566 styleText = '@import url(' + styleNode.href + ');';
1567 } else {
1568 // Internal stylesheet; just copy the text
1569 // For IE10 we need to fall back to .cssText, BUT that's undefined in
1570 // other browsers, so fall back to '' rather than 'undefined'
1571 styleText = styleNode.textContent || parentDoc.styleSheets[i].cssText || '';
1572 }
1573
1574 // Create a node with a unique ID that we're going to monitor to see when the CSS
1575 // has loaded
1576 if ( styleNode.oouiFrameTransplantStylesId ) {
1577 // If we're nesting transplantStyles operations and this node already has
1578 // a CSS rule to wait for loading, reuse it
1579 pollNodeId = styleNode.oouiFrameTransplantStylesId;
1580 } else {
1581 // Otherwise, create a new ID
1582 pollNodeId = 'oo-ui-frame-transplantStyles-loaded-' + nextIndex;
1583 nextIndex++;
1584
1585 // Add #pollNodeId { font-family: ... } to the end of the stylesheet / after the @import
1586 // The font-family rule will only take effect once the @import finishes
1587 styleText += '\n' + '#' + pollNodeId + ' { font-family: ' + fontFamily + '; }';
1588 }
1589
1590 // Create a node with id=pollNodeId
1591 $pollNodes = $pollNodes.add( $( '<div>', frameDoc )
1592 .attr( 'id', pollNodeId )
1593 .appendTo( frameDoc.body )
1594 );
1595
1596 // Add our modified CSS as a <style> tag
1597 newNode = frameDoc.createElement( 'style' );
1598 newNode.textContent = styleText;
1599 newNode.oouiFrameTransplantStylesId = pollNodeId;
1600 frameDoc.head.appendChild( newNode );
1601 }
1602 frameDoc.oouiFrameTransplantStylesNextIndex = nextIndex;
1603
1604 // Poll every 100ms until all external stylesheets have loaded
1605 $pendingPollNodes = $pollNodes;
1606 timeoutID = setTimeout( function pollExternalStylesheets() {
1607 while (
1608 $pendingPollNodes.length > 0 &&
1609 $pendingPollNodes.eq( 0 ).css( 'font-family' ) === fontFamily
1610 ) {
1611 $pendingPollNodes = $pendingPollNodes.slice( 1 );
1612 }
1613
1614 if ( $pendingPollNodes.length === 0 ) {
1615 // We're done!
1616 if ( timeoutID !== null ) {
1617 timeoutID = null;
1618 $pollNodes.remove();
1619 deferred.resolve();
1620 }
1621 } else {
1622 timeoutID = setTimeout( pollExternalStylesheets, 100 );
1623 }
1624 }, 100 );
1625 // ...but give up after a while
1626 if ( timeout !== 0 ) {
1627 setTimeout( function () {
1628 if ( timeoutID ) {
1629 clearTimeout( timeoutID );
1630 timeoutID = null;
1631 $pollNodes.remove();
1632 deferred.reject();
1633 }
1634 }, timeout || 5000 );
1635 }
1636
1637 return deferred.promise();
1638 };
1639
1640 /* Methods */
1641
1642 /**
1643 * Handle mouse down events.
1644 *
1645 * @param {jQuery.Event} e Mouse down event
1646 */
1647 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1648 // Prevent clicking on the click-block from stealing focus
1649 if ( e.target === this.$element[0] ) {
1650 return false;
1651 }
1652 };
1653
1654 /**
1655 * Check if window has been initialized.
1656 *
1657 * @return {boolean} Window has been initialized
1658 */
1659 OO.ui.Window.prototype.isInitialized = function () {
1660 return this.initialized;
1661 };
1662
1663 /**
1664 * Check if window is visible.
1665 *
1666 * @return {boolean} Window is visible
1667 */
1668 OO.ui.Window.prototype.isVisible = function () {
1669 return this.visible;
1670 };
1671
1672 /**
1673 * Check if window is loading.
1674 *
1675 * @return {boolean} Window is loading
1676 */
1677 OO.ui.Window.prototype.isLoading = function () {
1678 return this.loading && this.loading.state() === 'pending';
1679 };
1680
1681 /**
1682 * Check if window is loaded.
1683 *
1684 * @return {boolean} Window is loaded
1685 */
1686 OO.ui.Window.prototype.isLoaded = function () {
1687 return this.loading && this.loading.state() === 'resolved';
1688 };
1689
1690 /**
1691 * Check if window is opening.
1692 *
1693 * This is a wrapper around OO.ui.WindowManager#isOpening.
1694 *
1695 * @return {boolean} Window is opening
1696 */
1697 OO.ui.Window.prototype.isOpening = function () {
1698 return this.manager.isOpening( this );
1699 };
1700
1701 /**
1702 * Check if window is closing.
1703 *
1704 * This is a wrapper around OO.ui.WindowManager#isClosing.
1705 *
1706 * @return {boolean} Window is closing
1707 */
1708 OO.ui.Window.prototype.isClosing = function () {
1709 return this.manager.isClosing( this );
1710 };
1711
1712 /**
1713 * Check if window is opened.
1714 *
1715 * This is a wrapper around OO.ui.WindowManager#isOpened.
1716 *
1717 * @return {boolean} Window is opened
1718 */
1719 OO.ui.Window.prototype.isOpened = function () {
1720 return this.manager.isOpened( this );
1721 };
1722
1723 /**
1724 * Get the window manager.
1725 *
1726 * @return {OO.ui.WindowManager} Manager of window
1727 */
1728 OO.ui.Window.prototype.getManager = function () {
1729 return this.manager;
1730 };
1731
1732 /**
1733 * Get the window size.
1734 *
1735 * @return {string} Symbolic size name, e.g. `small`, `medium`, `large`, `larger`, `full`
1736 */
1737 OO.ui.Window.prototype.getSize = function () {
1738 return this.size;
1739 };
1740
1741 /**
1742 * Disable transitions on window's frame for the duration of the callback function, then enable them
1743 * back.
1744 *
1745 * @private
1746 * @param {Function} callback Function to call while transitions are disabled
1747 */
1748 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1749 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1750 // Disable transitions first, otherwise we'll get values from when the window was animating.
1751 var oldTransition,
1752 styleObj = this.$frame[0].style;
1753 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1754 styleObj.MozTransition || styleObj.WebkitTransition;
1755 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1756 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1757 callback();
1758 // Force reflow to make sure the style changes done inside callback really are not transitioned
1759 this.$frame.height();
1760 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1761 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1762 };
1763
1764 /**
1765 * Get the height of the dialog contents.
1766 *
1767 * @return {number} Content height
1768 */
1769 OO.ui.Window.prototype.getContentHeight = function () {
1770 var bodyHeight,
1771 win = this,
1772 bodyStyleObj = this.$body[0].style,
1773 frameStyleObj = this.$frame[0].style;
1774
1775 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1776 // Disable transitions first, otherwise we'll get values from when the window was animating.
1777 this.withoutSizeTransitions( function () {
1778 var oldHeight = frameStyleObj.height,
1779 oldPosition = bodyStyleObj.position;
1780 frameStyleObj.height = '1px';
1781 // Force body to resize to new width
1782 bodyStyleObj.position = 'relative';
1783 bodyHeight = win.getBodyHeight();
1784 frameStyleObj.height = oldHeight;
1785 bodyStyleObj.position = oldPosition;
1786 } );
1787
1788 return (
1789 // Add buffer for border
1790 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1791 // Use combined heights of children
1792 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1793 );
1794 };
1795
1796 /**
1797 * Get the height of the dialog contents.
1798 *
1799 * When this function is called, the dialog will temporarily have been resized
1800 * to height=1px, so .scrollHeight measurements can be taken accurately.
1801 *
1802 * @return {number} Height of content
1803 */
1804 OO.ui.Window.prototype.getBodyHeight = function () {
1805 return this.$body[0].scrollHeight;
1806 };
1807
1808 /**
1809 * Get the directionality of the frame
1810 *
1811 * @return {string} Directionality, 'ltr' or 'rtl'
1812 */
1813 OO.ui.Window.prototype.getDir = function () {
1814 return this.dir;
1815 };
1816
1817 /**
1818 * Get a process for setting up a window for use.
1819 *
1820 * Each time the window is opened this process will set it up for use in a particular context, based
1821 * on the `data` argument.
1822 *
1823 * When you override this method, you can add additional setup steps to the process the parent
1824 * method provides using the 'first' and 'next' methods.
1825 *
1826 * @abstract
1827 * @param {Object} [data] Window opening data
1828 * @return {OO.ui.Process} Setup process
1829 */
1830 OO.ui.Window.prototype.getSetupProcess = function () {
1831 return new OO.ui.Process();
1832 };
1833
1834 /**
1835 * Get a process for readying a window for use.
1836 *
1837 * Each time the window is open and setup, this process will ready it up for use in a particular
1838 * context, based on the `data` argument.
1839 *
1840 * When you override this method, you can add additional setup steps to the process the parent
1841 * method provides using the 'first' and 'next' methods.
1842 *
1843 * @abstract
1844 * @param {Object} [data] Window opening data
1845 * @return {OO.ui.Process} Setup process
1846 */
1847 OO.ui.Window.prototype.getReadyProcess = function () {
1848 return new OO.ui.Process();
1849 };
1850
1851 /**
1852 * Get a process for holding a window from use.
1853 *
1854 * Each time the window is closed, this process will hold it from use in a particular context, based
1855 * on the `data` argument.
1856 *
1857 * When you override this method, you can add additional setup steps to the process the parent
1858 * method provides using the 'first' and 'next' methods.
1859 *
1860 * @abstract
1861 * @param {Object} [data] Window closing data
1862 * @return {OO.ui.Process} Hold process
1863 */
1864 OO.ui.Window.prototype.getHoldProcess = function () {
1865 return new OO.ui.Process();
1866 };
1867
1868 /**
1869 * Get a process for tearing down a window after use.
1870 *
1871 * Each time the window is closed this process will tear it down and do something with the user's
1872 * interactions within the window, based on the `data` argument.
1873 *
1874 * When you override this method, you can add additional teardown steps to the process the parent
1875 * method provides using the 'first' and 'next' methods.
1876 *
1877 * @abstract
1878 * @param {Object} [data] Window closing data
1879 * @return {OO.ui.Process} Teardown process
1880 */
1881 OO.ui.Window.prototype.getTeardownProcess = function () {
1882 return new OO.ui.Process();
1883 };
1884
1885 /**
1886 * Toggle visibility of window.
1887 *
1888 * If the window is isolated and hasn't fully loaded yet, the visibility property will be used
1889 * instead of display.
1890 *
1891 * @param {boolean} [show] Make window visible, omit to toggle visibility
1892 * @fires toggle
1893 * @chainable
1894 */
1895 OO.ui.Window.prototype.toggle = function ( show ) {
1896 show = show === undefined ? !this.visible : !!show;
1897
1898 if ( show !== this.isVisible() ) {
1899 this.visible = show;
1900
1901 if ( this.isolated && !this.isLoaded() ) {
1902 // Hide the window using visibility instead of display until loading is complete
1903 // Can't use display: none; because that prevents the iframe from loading in Firefox
1904 this.$element.css( 'visibility', show ? 'visible' : 'hidden' );
1905 } else {
1906 this.$element.toggle( show ).css( 'visibility', '' );
1907 }
1908 this.emit( 'toggle', show );
1909 }
1910
1911 return this;
1912 };
1913
1914 /**
1915 * Set the window manager.
1916 *
1917 * This must be called before initialize. Calling it more than once will cause an error.
1918 *
1919 * @param {OO.ui.WindowManager} manager Manager for this window
1920 * @throws {Error} If called more than once
1921 * @chainable
1922 */
1923 OO.ui.Window.prototype.setManager = function ( manager ) {
1924 if ( this.manager ) {
1925 throw new Error( 'Cannot set window manager, window already has a manager' );
1926 }
1927
1928 // Properties
1929 this.manager = manager;
1930 this.isolated = manager.shouldIsolate();
1931
1932 // Initialization
1933 if ( this.isolated ) {
1934 this.$iframe = this.$( '<iframe>' );
1935 this.$iframe.attr( { frameborder: 0, scrolling: 'no' } );
1936 this.$frame.append( this.$iframe );
1937 this.$ = function () {
1938 throw new Error( 'this.$() cannot be used until the frame has been initialized.' );
1939 };
1940 // WARNING: Do not use this.$ again until #initialize is called
1941 } else {
1942 this.$content = this.$( '<div>' );
1943 this.$document = $( this.getElementDocument() );
1944 this.$content.addClass( 'oo-ui-window-content' ).attr( 'tabIndex', 0 );
1945 this.$frame.append( this.$content );
1946 }
1947 this.toggle( false );
1948
1949 // Figure out directionality:
1950 this.dir = OO.ui.Element.static.getDir( this.$iframe || this.$content ) || 'ltr';
1951
1952 return this;
1953 };
1954
1955 /**
1956 * Set the window size.
1957 *
1958 * @param {string} size Symbolic size name, e.g. 'small', 'medium', 'large', 'full'
1959 * @chainable
1960 */
1961 OO.ui.Window.prototype.setSize = function ( size ) {
1962 this.size = size;
1963 this.manager.updateWindowSize( this );
1964 return this;
1965 };
1966
1967 /**
1968 * Set window dimensions.
1969 *
1970 * Properties are applied to the frame container.
1971 *
1972 * @param {Object} dim CSS dimension properties
1973 * @param {string|number} [dim.width] Width
1974 * @param {string|number} [dim.minWidth] Minimum width
1975 * @param {string|number} [dim.maxWidth] Maximum width
1976 * @param {string|number} [dim.width] Height, omit to set based on height of contents
1977 * @param {string|number} [dim.minWidth] Minimum height
1978 * @param {string|number} [dim.maxWidth] Maximum height
1979 * @chainable
1980 */
1981 OO.ui.Window.prototype.setDimensions = function ( dim ) {
1982 var height,
1983 win = this,
1984 styleObj = this.$frame[0].style;
1985
1986 // Calculate the height we need to set using the correct width
1987 if ( dim.height === undefined ) {
1988 this.withoutSizeTransitions( function () {
1989 var oldWidth = styleObj.width;
1990 win.$frame.css( 'width', dim.width || '' );
1991 height = win.getContentHeight();
1992 styleObj.width = oldWidth;
1993 } );
1994 } else {
1995 height = dim.height;
1996 }
1997
1998 this.$frame.css( {
1999 width: dim.width || '',
2000 minWidth: dim.minWidth || '',
2001 maxWidth: dim.maxWidth || '',
2002 height: height || '',
2003 minHeight: dim.minHeight || '',
2004 maxHeight: dim.maxHeight || ''
2005 } );
2006
2007 return this;
2008 };
2009
2010 /**
2011 * Initialize window contents.
2012 *
2013 * The first time the window is opened, #initialize is called when it's safe to begin populating
2014 * its contents. See #getSetupProcess for a way to make changes each time the window opens.
2015 *
2016 * Once this method is called, this.$ can be used to create elements within the frame.
2017 *
2018 * @throws {Error} If not attached to a manager
2019 * @chainable
2020 */
2021 OO.ui.Window.prototype.initialize = function () {
2022 if ( !this.manager ) {
2023 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2024 }
2025
2026 // Properties
2027 this.$head = this.$( '<div>' );
2028 this.$body = this.$( '<div>' );
2029 this.$foot = this.$( '<div>' );
2030 this.$innerOverlay = this.$( '<div>' );
2031
2032 // Events
2033 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2034
2035 // Initialization
2036 this.$head.addClass( 'oo-ui-window-head' );
2037 this.$body.addClass( 'oo-ui-window-body' );
2038 this.$foot.addClass( 'oo-ui-window-foot' );
2039 this.$innerOverlay.addClass( 'oo-ui-window-inner-overlay' );
2040 this.$content.append( this.$head, this.$body, this.$foot, this.$innerOverlay );
2041
2042 return this;
2043 };
2044
2045 /**
2046 * Open window.
2047 *
2048 * This is a wrapper around calling {@link OO.ui.WindowManager#openWindow} on the window manager.
2049 * To do something each time the window opens, use #getSetupProcess or #getReadyProcess.
2050 *
2051 * @param {Object} [data] Window opening data
2052 * @return {jQuery.Promise} Promise resolved when window is opened; when the promise is resolved the
2053 * first argument will be a promise which will be resolved when the window begins closing
2054 */
2055 OO.ui.Window.prototype.open = function ( data ) {
2056 return this.manager.openWindow( this, data );
2057 };
2058
2059 /**
2060 * Close window.
2061 *
2062 * This is a wrapper around calling OO.ui.WindowManager#closeWindow on the window manager.
2063 * To do something each time the window closes, use #getHoldProcess or #getTeardownProcess.
2064 *
2065 * @param {Object} [data] Window closing data
2066 * @return {jQuery.Promise} Promise resolved when window is closed
2067 */
2068 OO.ui.Window.prototype.close = function ( data ) {
2069 return this.manager.closeWindow( this, data );
2070 };
2071
2072 /**
2073 * Setup window.
2074 *
2075 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2076 * by other systems.
2077 *
2078 * @param {Object} [data] Window opening data
2079 * @return {jQuery.Promise} Promise resolved when window is setup
2080 */
2081 OO.ui.Window.prototype.setup = function ( data ) {
2082 var win = this,
2083 deferred = $.Deferred();
2084
2085 this.$element.show();
2086 this.visible = true;
2087 this.getSetupProcess( data ).execute().done( function () {
2088 // Force redraw by asking the browser to measure the elements' widths
2089 win.$element.addClass( 'oo-ui-window-setup' ).width();
2090 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2091 deferred.resolve();
2092 } );
2093
2094 return deferred.promise();
2095 };
2096
2097 /**
2098 * Ready window.
2099 *
2100 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2101 * by other systems.
2102 *
2103 * @param {Object} [data] Window opening data
2104 * @return {jQuery.Promise} Promise resolved when window is ready
2105 */
2106 OO.ui.Window.prototype.ready = function ( data ) {
2107 var win = this,
2108 deferred = $.Deferred();
2109
2110 this.$content.focus();
2111 this.getReadyProcess( data ).execute().done( function () {
2112 // Force redraw by asking the browser to measure the elements' widths
2113 win.$element.addClass( 'oo-ui-window-ready' ).width();
2114 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2115 deferred.resolve();
2116 } );
2117
2118 return deferred.promise();
2119 };
2120
2121 /**
2122 * Hold window.
2123 *
2124 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2125 * by other systems.
2126 *
2127 * @param {Object} [data] Window closing data
2128 * @return {jQuery.Promise} Promise resolved when window is held
2129 */
2130 OO.ui.Window.prototype.hold = function ( data ) {
2131 var win = this,
2132 deferred = $.Deferred();
2133
2134 this.getHoldProcess( data ).execute().done( function () {
2135 // Get the focused element within the window's content
2136 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2137
2138 // Blur the focused element
2139 if ( $focus.length ) {
2140 $focus[0].blur();
2141 }
2142
2143 // Force redraw by asking the browser to measure the elements' widths
2144 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2145 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2146 deferred.resolve();
2147 } );
2148
2149 return deferred.promise();
2150 };
2151
2152 /**
2153 * Teardown window.
2154 *
2155 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2156 * by other systems.
2157 *
2158 * @param {Object} [data] Window closing data
2159 * @return {jQuery.Promise} Promise resolved when window is torn down
2160 */
2161 OO.ui.Window.prototype.teardown = function ( data ) {
2162 var win = this,
2163 deferred = $.Deferred();
2164
2165 this.getTeardownProcess( data ).execute().done( function () {
2166 // Force redraw by asking the browser to measure the elements' widths
2167 win.$element.removeClass( 'oo-ui-window-load oo-ui-window-setup' ).width();
2168 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2169 win.$element.hide();
2170 win.visible = false;
2171 deferred.resolve();
2172 } );
2173
2174 return deferred.promise();
2175 };
2176
2177 /**
2178 * Load the frame contents.
2179 *
2180 * Once the iframe's stylesheets are loaded the returned promise will be resolved. Calling while
2181 * loading will return a promise but not trigger a new loading cycle. Calling after loading is
2182 * complete will return a promise that's already been resolved.
2183 *
2184 * Sounds simple right? Read on...
2185 *
2186 * When you create a dynamic iframe using open/write/close, the window.load event for the
2187 * iframe is triggered when you call close, and there's no further load event to indicate that
2188 * everything is actually loaded.
2189 *
2190 * In Chrome, stylesheets don't show up in document.styleSheets until they have loaded, so we could
2191 * just poll that array and wait for it to have the right length. However, in Firefox, stylesheets
2192 * are added to document.styleSheets immediately, and the only way you can determine whether they've
2193 * loaded is to attempt to access .cssRules and wait for that to stop throwing an exception. But
2194 * cross-domain stylesheets never allow .cssRules to be accessed even after they have loaded.
2195 *
2196 * The workaround is to change all `<link href="...">` tags to `<style>@import url(...)</style>`
2197 * tags. Because `@import` is blocking, Chrome won't add the stylesheet to document.styleSheets
2198 * until the `@import` has finished, and Firefox won't allow .cssRules to be accessed until the
2199 * `@import` has finished. And because the contents of the `<style>` tag are from the same origin,
2200 * accessing .cssRules is allowed.
2201 *
2202 * However, now that we control the styles we're injecting, we might as well do away with
2203 * browser-specific polling hacks like document.styleSheets and .cssRules, and instead inject
2204 * `<style>@import url(...); #foo { font-family: someValue; }</style>`, then create `<div id="foo">`
2205 * and wait for its font-family to change to someValue. Because `@import` is blocking, the
2206 * font-family rule is not applied until after the `@import` finishes.
2207 *
2208 * All this stylesheet injection and polling magic is in #transplantStyles.
2209 *
2210 * @return {jQuery.Promise} Promise resolved when loading is complete
2211 */
2212 OO.ui.Window.prototype.load = function () {
2213 var sub, doc, loading,
2214 win = this;
2215
2216 this.$element.addClass( 'oo-ui-window-load' );
2217
2218 // Non-isolated windows are already "loaded"
2219 if ( !this.loading && !this.isolated ) {
2220 this.loading = $.Deferred().resolve();
2221 this.initialize();
2222 // Set initialized state after so sub-classes aren't confused by it being set by calling
2223 // their parent initialize method
2224 this.initialized = true;
2225 }
2226
2227 // Return existing promise if already loading or loaded
2228 if ( this.loading ) {
2229 return this.loading.promise();
2230 }
2231
2232 // Load the frame
2233 loading = this.loading = $.Deferred();
2234 sub = this.$iframe.prop( 'contentWindow' );
2235 doc = sub.document;
2236
2237 // Initialize contents
2238 doc.open();
2239 doc.write(
2240 '<!doctype html>' +
2241 '<html>' +
2242 '<body class="oo-ui-window-isolated oo-ui-' + this.dir + '"' +
2243 ' style="direction:' + this.dir + ';" dir="' + this.dir + '">' +
2244 '<div class="oo-ui-window-content"></div>' +
2245 '</body>' +
2246 '</html>'
2247 );
2248 doc.close();
2249
2250 // Properties
2251 this.$ = OO.ui.Element.static.getJQuery( doc, this.$iframe );
2252 this.$content = this.$( '.oo-ui-window-content' ).attr( 'tabIndex', 0 );
2253 this.$document = this.$( doc );
2254
2255 // Initialization
2256 this.constructor.static.transplantStyles( this.getElementDocument(), this.$document[0] )
2257 .always( function () {
2258 // Initialize isolated windows
2259 win.initialize();
2260 // Set initialized state after so sub-classes aren't confused by it being set by calling
2261 // their parent initialize method
2262 win.initialized = true;
2263 // Undo the visibility: hidden; hack and apply display: none;
2264 // We can do this safely now that the iframe has initialized
2265 // (don't do this from within #initialize because it has to happen
2266 // after the all subclasses have been handled as well).
2267 win.toggle( win.isVisible() );
2268
2269 loading.resolve();
2270 } );
2271
2272 return loading.promise();
2273 };
2274
2275 /**
2276 * Base class for all dialogs.
2277 *
2278 * Logic:
2279 * - Manage the window (open and close, etc.).
2280 * - Store the internal name and display title.
2281 * - A stack to track one or more pending actions.
2282 * - Manage a set of actions that can be performed.
2283 * - Configure and create action widgets.
2284 *
2285 * User interface:
2286 * - Close the dialog with Escape key.
2287 * - Visually lock the dialog while an action is in
2288 * progress (aka "pending").
2289 *
2290 * Subclass responsibilities:
2291 * - Display the title somewhere.
2292 * - Add content to the dialog.
2293 * - Provide a UI to close the dialog.
2294 * - Display the action widgets somewhere.
2295 *
2296 * @abstract
2297 * @class
2298 * @extends OO.ui.Window
2299 * @mixins OO.ui.PendingElement
2300 *
2301 * @constructor
2302 * @param {Object} [config] Configuration options
2303 */
2304 OO.ui.Dialog = function OoUiDialog( config ) {
2305 // Parent constructor
2306 OO.ui.Dialog.super.call( this, config );
2307
2308 // Mixin constructors
2309 OO.ui.PendingElement.call( this );
2310
2311 // Properties
2312 this.actions = new OO.ui.ActionSet();
2313 this.attachedActions = [];
2314 this.currentAction = null;
2315 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2316
2317 // Events
2318 this.actions.connect( this, {
2319 click: 'onActionClick',
2320 resize: 'onActionResize',
2321 change: 'onActionsChange'
2322 } );
2323
2324 // Initialization
2325 this.$element
2326 .addClass( 'oo-ui-dialog' )
2327 .attr( 'role', 'dialog' );
2328 };
2329
2330 /* Setup */
2331
2332 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2333 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2334
2335 /* Static Properties */
2336
2337 /**
2338 * Symbolic name of dialog.
2339 *
2340 * @abstract
2341 * @static
2342 * @inheritable
2343 * @property {string}
2344 */
2345 OO.ui.Dialog.static.name = '';
2346
2347 /**
2348 * Dialog title.
2349 *
2350 * @abstract
2351 * @static
2352 * @inheritable
2353 * @property {jQuery|string|Function} Label nodes, text or a function that returns nodes or text
2354 */
2355 OO.ui.Dialog.static.title = '';
2356
2357 /**
2358 * List of OO.ui.ActionWidget configuration options.
2359 *
2360 * @static
2361 * inheritable
2362 * @property {Object[]}
2363 */
2364 OO.ui.Dialog.static.actions = [];
2365
2366 /**
2367 * Close dialog when the escape key is pressed.
2368 *
2369 * @static
2370 * @abstract
2371 * @inheritable
2372 * @property {boolean}
2373 */
2374 OO.ui.Dialog.static.escapable = true;
2375
2376 /* Methods */
2377
2378 /**
2379 * Handle frame document key down events.
2380 *
2381 * @param {jQuery.Event} e Key down event
2382 */
2383 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2384 if ( e.which === OO.ui.Keys.ESCAPE ) {
2385 this.close();
2386 e.preventDefault();
2387 e.stopPropagation();
2388 }
2389 };
2390
2391 /**
2392 * Handle action resized events.
2393 *
2394 * @param {OO.ui.ActionWidget} action Action that was resized
2395 */
2396 OO.ui.Dialog.prototype.onActionResize = function () {
2397 // Override in subclass
2398 };
2399
2400 /**
2401 * Handle action click events.
2402 *
2403 * @param {OO.ui.ActionWidget} action Action that was clicked
2404 */
2405 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2406 if ( !this.isPending() ) {
2407 this.currentAction = action;
2408 this.executeAction( action.getAction() );
2409 }
2410 };
2411
2412 /**
2413 * Handle actions change event.
2414 */
2415 OO.ui.Dialog.prototype.onActionsChange = function () {
2416 this.detachActions();
2417 if ( !this.isClosing() ) {
2418 this.attachActions();
2419 }
2420 };
2421
2422 /**
2423 * Get set of actions.
2424 *
2425 * @return {OO.ui.ActionSet}
2426 */
2427 OO.ui.Dialog.prototype.getActions = function () {
2428 return this.actions;
2429 };
2430
2431 /**
2432 * Get a process for taking action.
2433 *
2434 * When you override this method, you can add additional accept steps to the process the parent
2435 * method provides using the 'first' and 'next' methods.
2436 *
2437 * @abstract
2438 * @param {string} [action] Symbolic name of action
2439 * @return {OO.ui.Process} Action process
2440 */
2441 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2442 return new OO.ui.Process()
2443 .next( function () {
2444 if ( !action ) {
2445 // An empty action always closes the dialog without data, which should always be
2446 // safe and make no changes
2447 this.close();
2448 }
2449 }, this );
2450 };
2451
2452 /**
2453 * @inheritdoc
2454 *
2455 * @param {Object} [data] Dialog opening data
2456 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use #static-title
2457 * @param {Object[]} [data.actions] List of OO.ui.ActionWidget configuration options for each
2458 * action item, omit to use #static-actions
2459 */
2460 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2461 data = data || {};
2462
2463 // Parent method
2464 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2465 .next( function () {
2466 var i, len,
2467 items = [],
2468 config = this.constructor.static,
2469 actions = data.actions !== undefined ? data.actions : config.actions;
2470
2471 this.title.setLabel(
2472 data.title !== undefined ? data.title : this.constructor.static.title
2473 );
2474 for ( i = 0, len = actions.length; i < len; i++ ) {
2475 items.push(
2476 new OO.ui.ActionWidget( $.extend( { $: this.$ }, actions[i] ) )
2477 );
2478 }
2479 this.actions.add( items );
2480
2481 if ( this.constructor.static.escapable ) {
2482 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2483 }
2484 }, this );
2485 };
2486
2487 /**
2488 * @inheritdoc
2489 */
2490 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2491 // Parent method
2492 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2493 .first( function () {
2494 if ( this.constructor.static.escapable ) {
2495 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2496 }
2497
2498 this.actions.clear();
2499 this.currentAction = null;
2500 }, this );
2501 };
2502
2503 /**
2504 * @inheritdoc
2505 */
2506 OO.ui.Dialog.prototype.initialize = function () {
2507 // Parent method
2508 OO.ui.Dialog.super.prototype.initialize.call( this );
2509
2510 // Properties
2511 this.title = new OO.ui.LabelWidget( { $: this.$ } );
2512
2513 // Initialization
2514 this.$content.addClass( 'oo-ui-dialog-content' );
2515 this.setPendingElement( this.$head );
2516 };
2517
2518 /**
2519 * Attach action actions.
2520 */
2521 OO.ui.Dialog.prototype.attachActions = function () {
2522 // Remember the list of potentially attached actions
2523 this.attachedActions = this.actions.get();
2524 };
2525
2526 /**
2527 * Detach action actions.
2528 *
2529 * @chainable
2530 */
2531 OO.ui.Dialog.prototype.detachActions = function () {
2532 var i, len;
2533
2534 // Detach all actions that may have been previously attached
2535 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2536 this.attachedActions[i].$element.detach();
2537 }
2538 this.attachedActions = [];
2539 };
2540
2541 /**
2542 * Execute an action.
2543 *
2544 * @param {string} action Symbolic name of action to execute
2545 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2546 */
2547 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2548 this.pushPending();
2549 return this.getActionProcess( action ).execute()
2550 .always( this.popPending.bind( this ) );
2551 };
2552
2553 /**
2554 * Collection of windows.
2555 *
2556 * @class
2557 * @extends OO.ui.Element
2558 * @mixins OO.EventEmitter
2559 *
2560 * Managed windows are mutually exclusive. If a window is opened while there is a current window
2561 * already opening or opened, the current window will be closed without data. Empty closing data
2562 * should always result in the window being closed without causing constructive or destructive
2563 * action.
2564 *
2565 * As a window is opened and closed, it passes through several stages and the manager emits several
2566 * corresponding events.
2567 *
2568 * - {@link #openWindow} or {@link OO.ui.Window#open} methods are used to start opening
2569 * - {@link #event-opening} is emitted with `opening` promise
2570 * - {@link #getSetupDelay} is called the returned value is used to time a pause in execution
2571 * - {@link OO.ui.Window#getSetupProcess} method is called on the window and its result executed
2572 * - `setup` progress notification is emitted from opening promise
2573 * - {@link #getReadyDelay} is called the returned value is used to time a pause in execution
2574 * - {@link OO.ui.Window#getReadyProcess} method is called on the window and its result executed
2575 * - `ready` progress notification is emitted from opening promise
2576 * - `opening` promise is resolved with `opened` promise
2577 * - Window is now open
2578 *
2579 * - {@link #closeWindow} or {@link OO.ui.Window#close} methods are used to start closing
2580 * - `opened` promise is resolved with `closing` promise
2581 * - {@link #event-closing} is emitted with `closing` promise
2582 * - {@link #getHoldDelay} is called the returned value is used to time a pause in execution
2583 * - {@link OO.ui.Window#getHoldProcess} method is called on the window and its result executed
2584 * - `hold` progress notification is emitted from opening promise
2585 * - {@link #getTeardownDelay} is called the returned value is used to time a pause in execution
2586 * - {@link OO.ui.Window#getTeardownProcess} method is called on the window and its result executed
2587 * - `teardown` progress notification is emitted from opening promise
2588 * - Closing promise is resolved
2589 * - Window is now closed
2590 *
2591 * @constructor
2592 * @param {Object} [config] Configuration options
2593 * @cfg {boolean} [isolate] Configure managed windows to isolate their content using inline frames
2594 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2595 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2596 */
2597 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2598 // Configuration initialization
2599 config = config || {};
2600
2601 // Parent constructor
2602 OO.ui.WindowManager.super.call( this, config );
2603
2604 // Mixin constructors
2605 OO.EventEmitter.call( this );
2606
2607 // Properties
2608 this.factory = config.factory;
2609 this.modal = config.modal === undefined || !!config.modal;
2610 this.isolate = !!config.isolate;
2611 this.windows = {};
2612 this.opening = null;
2613 this.opened = null;
2614 this.closing = null;
2615 this.preparingToOpen = null;
2616 this.preparingToClose = null;
2617 this.size = null;
2618 this.currentWindow = null;
2619 this.$ariaHidden = null;
2620 this.requestedSize = null;
2621 this.onWindowResizeTimeout = null;
2622 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2623 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2624 this.onWindowMouseWheelHandler = this.onWindowMouseWheel.bind( this );
2625 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2626
2627 // Initialization
2628 this.$element
2629 .addClass( 'oo-ui-windowManager' )
2630 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2631 };
2632
2633 /* Setup */
2634
2635 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2636 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2637
2638 /* Events */
2639
2640 /**
2641 * Window is opening.
2642 *
2643 * Fired when the window begins to be opened.
2644 *
2645 * @event opening
2646 * @param {OO.ui.Window} win Window that's being opened
2647 * @param {jQuery.Promise} opening Promise resolved when window is opened; when the promise is
2648 * resolved the first argument will be a promise which will be resolved when the window begins
2649 * closing, the second argument will be the opening data; progress notifications will be fired on
2650 * the promise for `setup` and `ready` when those processes are completed respectively.
2651 * @param {Object} data Window opening data
2652 */
2653
2654 /**
2655 * Window is closing.
2656 *
2657 * Fired when the window begins to be closed.
2658 *
2659 * @event closing
2660 * @param {OO.ui.Window} win Window that's being closed
2661 * @param {jQuery.Promise} opening Promise resolved when window is closed; when the promise
2662 * is resolved the first argument will be a the closing data; progress notifications will be fired
2663 * on the promise for `hold` and `teardown` when those processes are completed respectively.
2664 * @param {Object} data Window closing data
2665 */
2666
2667 /**
2668 * Window was resized.
2669 *
2670 * @event resize
2671 * @param {OO.ui.Window} win Window that was resized
2672 */
2673
2674 /* Static Properties */
2675
2676 /**
2677 * Map of symbolic size names and CSS properties.
2678 *
2679 * @static
2680 * @inheritable
2681 * @property {Object}
2682 */
2683 OO.ui.WindowManager.static.sizes = {
2684 small: {
2685 width: 300
2686 },
2687 medium: {
2688 width: 500
2689 },
2690 large: {
2691 width: 700
2692 },
2693 larger: {
2694 width: 900
2695 },
2696 full: {
2697 // These can be non-numeric because they are never used in calculations
2698 width: '100%',
2699 height: '100%'
2700 }
2701 };
2702
2703 /**
2704 * Symbolic name of default size.
2705 *
2706 * Default size is used if the window's requested size is not recognized.
2707 *
2708 * @static
2709 * @inheritable
2710 * @property {string}
2711 */
2712 OO.ui.WindowManager.static.defaultSize = 'medium';
2713
2714 /* Methods */
2715
2716 /**
2717 * Handle window resize events.
2718 *
2719 * @param {jQuery.Event} e Window resize event
2720 */
2721 OO.ui.WindowManager.prototype.onWindowResize = function () {
2722 clearTimeout( this.onWindowResizeTimeout );
2723 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2724 };
2725
2726 /**
2727 * Handle window resize events.
2728 *
2729 * @param {jQuery.Event} e Window resize event
2730 */
2731 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2732 if ( this.currentWindow ) {
2733 this.updateWindowSize( this.currentWindow );
2734 }
2735 };
2736
2737 /**
2738 * Handle window mouse wheel events.
2739 *
2740 * @param {jQuery.Event} e Mouse wheel event
2741 */
2742 OO.ui.WindowManager.prototype.onWindowMouseWheel = function () {
2743 // Kill all events in the parent window if the child window is isolated
2744 return !this.shouldIsolate();
2745 };
2746
2747 /**
2748 * Handle document key down events.
2749 *
2750 * @param {jQuery.Event} e Key down event
2751 */
2752 OO.ui.WindowManager.prototype.onDocumentKeyDown = function ( e ) {
2753 switch ( e.which ) {
2754 case OO.ui.Keys.PAGEUP:
2755 case OO.ui.Keys.PAGEDOWN:
2756 case OO.ui.Keys.END:
2757 case OO.ui.Keys.HOME:
2758 case OO.ui.Keys.LEFT:
2759 case OO.ui.Keys.UP:
2760 case OO.ui.Keys.RIGHT:
2761 case OO.ui.Keys.DOWN:
2762 // Kill all events in the parent window if the child window is isolated
2763 return !this.shouldIsolate();
2764 }
2765 };
2766
2767 /**
2768 * Check if window is opening.
2769 *
2770 * @return {boolean} Window is opening
2771 */
2772 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2773 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2774 };
2775
2776 /**
2777 * Check if window is closing.
2778 *
2779 * @return {boolean} Window is closing
2780 */
2781 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2782 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2783 };
2784
2785 /**
2786 * Check if window is opened.
2787 *
2788 * @return {boolean} Window is opened
2789 */
2790 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2791 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2792 };
2793
2794 /**
2795 * Check if window contents should be isolated.
2796 *
2797 * Window content isolation is done using inline frames.
2798 *
2799 * @return {boolean} Window contents should be isolated
2800 */
2801 OO.ui.WindowManager.prototype.shouldIsolate = function () {
2802 return this.isolate;
2803 };
2804
2805 /**
2806 * Check if a window is being managed.
2807 *
2808 * @param {OO.ui.Window} win Window to check
2809 * @return {boolean} Window is being managed
2810 */
2811 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2812 var name;
2813
2814 for ( name in this.windows ) {
2815 if ( this.windows[name] === win ) {
2816 return true;
2817 }
2818 }
2819
2820 return false;
2821 };
2822
2823 /**
2824 * Get the number of milliseconds to wait between beginning opening and executing setup process.
2825 *
2826 * @param {OO.ui.Window} win Window being opened
2827 * @param {Object} [data] Window opening data
2828 * @return {number} Milliseconds to wait
2829 */
2830 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2831 return 0;
2832 };
2833
2834 /**
2835 * Get the number of milliseconds to wait between finishing setup and executing ready process.
2836 *
2837 * @param {OO.ui.Window} win Window being opened
2838 * @param {Object} [data] Window opening data
2839 * @return {number} Milliseconds to wait
2840 */
2841 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2842 return 0;
2843 };
2844
2845 /**
2846 * Get the number of milliseconds to wait between beginning closing and executing hold process.
2847 *
2848 * @param {OO.ui.Window} win Window being closed
2849 * @param {Object} [data] Window closing data
2850 * @return {number} Milliseconds to wait
2851 */
2852 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2853 return 0;
2854 };
2855
2856 /**
2857 * Get the number of milliseconds to wait between finishing hold and executing teardown process.
2858 *
2859 * @param {OO.ui.Window} win Window being closed
2860 * @param {Object} [data] Window closing data
2861 * @return {number} Milliseconds to wait
2862 */
2863 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2864 return this.modal ? 250 : 0;
2865 };
2866
2867 /**
2868 * Get managed window by symbolic name.
2869 *
2870 * If window is not yet instantiated, it will be instantiated and added automatically.
2871 *
2872 * @param {string} name Symbolic window name
2873 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2874 * @throws {Error} If the symbolic name is unrecognized by the factory
2875 * @throws {Error} If the symbolic name unrecognized as a managed window
2876 */
2877 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2878 var deferred = $.Deferred(),
2879 win = this.windows[name];
2880
2881 if ( !( win instanceof OO.ui.Window ) ) {
2882 if ( this.factory ) {
2883 if ( !this.factory.lookup( name ) ) {
2884 deferred.reject( new OO.ui.Error(
2885 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2886 ) );
2887 } else {
2888 win = this.factory.create( name, this, { $: this.$ } );
2889 this.addWindows( [ win ] );
2890 deferred.resolve( win );
2891 }
2892 } else {
2893 deferred.reject( new OO.ui.Error(
2894 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2895 ) );
2896 }
2897 } else {
2898 deferred.resolve( win );
2899 }
2900
2901 return deferred.promise();
2902 };
2903
2904 /**
2905 * Get current window.
2906 *
2907 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2908 */
2909 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2910 return this.currentWindow;
2911 };
2912
2913 /**
2914 * Open a window.
2915 *
2916 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2917 * @param {Object} [data] Window opening data
2918 * @return {jQuery.Promise} Promise resolved when window is done opening; see {@link #event-opening}
2919 * for more details about the `opening` promise
2920 * @fires opening
2921 */
2922 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
2923 var manager = this,
2924 preparing = [],
2925 opening = $.Deferred();
2926
2927 // Argument handling
2928 if ( typeof win === 'string' ) {
2929 return this.getWindow( win ).then( function ( win ) {
2930 return manager.openWindow( win, data );
2931 } );
2932 }
2933
2934 // Error handling
2935 if ( !this.hasWindow( win ) ) {
2936 opening.reject( new OO.ui.Error(
2937 'Cannot open window: window is not attached to manager'
2938 ) );
2939 } else if ( this.preparingToOpen || this.opening || this.opened ) {
2940 opening.reject( new OO.ui.Error(
2941 'Cannot open window: another window is opening or open'
2942 ) );
2943 }
2944
2945 // Window opening
2946 if ( opening.state() !== 'rejected' ) {
2947 if ( !win.getManager() ) {
2948 win.setManager( this );
2949 }
2950 preparing.push( win.load() );
2951
2952 if ( this.closing ) {
2953 // If a window is currently closing, wait for it to complete
2954 preparing.push( this.closing );
2955 }
2956
2957 this.preparingToOpen = $.when.apply( $, preparing );
2958 // Ensure handlers get called after preparingToOpen is set
2959 this.preparingToOpen.done( function () {
2960 if ( manager.modal ) {
2961 manager.toggleGlobalEvents( true );
2962 manager.toggleAriaIsolation( true );
2963 }
2964 manager.currentWindow = win;
2965 manager.opening = opening;
2966 manager.preparingToOpen = null;
2967 manager.emit( 'opening', win, opening, data );
2968 setTimeout( function () {
2969 win.setup( data ).then( function () {
2970 manager.updateWindowSize( win );
2971 manager.opening.notify( { state: 'setup' } );
2972 setTimeout( function () {
2973 win.ready( data ).then( function () {
2974 manager.opening.notify( { state: 'ready' } );
2975 manager.opening = null;
2976 manager.opened = $.Deferred();
2977 opening.resolve( manager.opened.promise(), data );
2978 } );
2979 }, manager.getReadyDelay() );
2980 } );
2981 }, manager.getSetupDelay() );
2982 } );
2983 }
2984
2985 return opening.promise();
2986 };
2987
2988 /**
2989 * Close a window.
2990 *
2991 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
2992 * @param {Object} [data] Window closing data
2993 * @return {jQuery.Promise} Promise resolved when window is done closing; see {@link #event-closing}
2994 * for more details about the `closing` promise
2995 * @throws {Error} If no window by that name is being managed
2996 * @fires closing
2997 */
2998 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
2999 var manager = this,
3000 preparing = [],
3001 closing = $.Deferred(),
3002 opened;
3003
3004 // Argument handling
3005 if ( typeof win === 'string' ) {
3006 win = this.windows[win];
3007 } else if ( !this.hasWindow( win ) ) {
3008 win = null;
3009 }
3010
3011 // Error handling
3012 if ( !win ) {
3013 closing.reject( new OO.ui.Error(
3014 'Cannot close window: window is not attached to manager'
3015 ) );
3016 } else if ( win !== this.currentWindow ) {
3017 closing.reject( new OO.ui.Error(
3018 'Cannot close window: window already closed with different data'
3019 ) );
3020 } else if ( this.preparingToClose || this.closing ) {
3021 closing.reject( new OO.ui.Error(
3022 'Cannot close window: window already closing with different data'
3023 ) );
3024 }
3025
3026 // Window closing
3027 if ( closing.state() !== 'rejected' ) {
3028 if ( this.opening ) {
3029 // If the window is currently opening, close it when it's done
3030 preparing.push( this.opening );
3031 }
3032
3033 this.preparingToClose = $.when.apply( $, preparing );
3034 // Ensure handlers get called after preparingToClose is set
3035 this.preparingToClose.done( function () {
3036 manager.closing = closing;
3037 manager.preparingToClose = null;
3038 manager.emit( 'closing', win, closing, data );
3039 opened = manager.opened;
3040 manager.opened = null;
3041 opened.resolve( closing.promise(), data );
3042 setTimeout( function () {
3043 win.hold( data ).then( function () {
3044 closing.notify( { state: 'hold' } );
3045 setTimeout( function () {
3046 win.teardown( data ).then( function () {
3047 closing.notify( { state: 'teardown' } );
3048 if ( manager.modal ) {
3049 manager.toggleGlobalEvents( false );
3050 manager.toggleAriaIsolation( false );
3051 }
3052 manager.closing = null;
3053 manager.currentWindow = null;
3054 closing.resolve( data );
3055 } );
3056 }, manager.getTeardownDelay() );
3057 } );
3058 }, manager.getHoldDelay() );
3059 } );
3060 }
3061
3062 return closing.promise();
3063 };
3064
3065 /**
3066 * Add windows.
3067 *
3068 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows Windows to add
3069 * @throws {Error} If one of the windows being added without an explicit symbolic name does not have
3070 * a statically configured symbolic name
3071 */
3072 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3073 var i, len, win, name, list;
3074
3075 if ( $.isArray( windows ) ) {
3076 // Convert to map of windows by looking up symbolic names from static configuration
3077 list = {};
3078 for ( i = 0, len = windows.length; i < len; i++ ) {
3079 name = windows[i].constructor.static.name;
3080 if ( typeof name !== 'string' ) {
3081 throw new Error( 'Cannot add window' );
3082 }
3083 list[name] = windows[i];
3084 }
3085 } else if ( $.isPlainObject( windows ) ) {
3086 list = windows;
3087 }
3088
3089 // Add windows
3090 for ( name in list ) {
3091 win = list[name];
3092 this.windows[name] = win;
3093 this.$element.append( win.$element );
3094 }
3095 };
3096
3097 /**
3098 * Remove windows.
3099 *
3100 * Windows will be closed before they are removed.
3101 *
3102 * @param {string[]} names Symbolic names of windows to remove
3103 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3104 * @throws {Error} If windows being removed are not being managed
3105 */
3106 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3107 var i, len, win, name, cleanupWindow,
3108 manager = this,
3109 promises = [],
3110 cleanup = function ( name, win ) {
3111 delete manager.windows[name];
3112 win.$element.detach();
3113 };
3114
3115 for ( i = 0, len = names.length; i < len; i++ ) {
3116 name = names[i];
3117 win = this.windows[name];
3118 if ( !win ) {
3119 throw new Error( 'Cannot remove window' );
3120 }
3121 cleanupWindow = cleanup.bind( null, name, win );
3122 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3123 }
3124
3125 return $.when.apply( $, promises );
3126 };
3127
3128 /**
3129 * Remove all windows.
3130 *
3131 * Windows will be closed before they are removed.
3132 *
3133 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3134 */
3135 OO.ui.WindowManager.prototype.clearWindows = function () {
3136 return this.removeWindows( Object.keys( this.windows ) );
3137 };
3138
3139 /**
3140 * Set dialog size.
3141 *
3142 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3143 *
3144 * @chainable
3145 */
3146 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3147 // Bypass for non-current, and thus invisible, windows
3148 if ( win !== this.currentWindow ) {
3149 return;
3150 }
3151
3152 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3153 sizes = this.constructor.static.sizes,
3154 size = win.getSize();
3155
3156 if ( !sizes[size] ) {
3157 size = this.constructor.static.defaultSize;
3158 }
3159 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[size].width ) {
3160 size = 'full';
3161 }
3162
3163 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3164 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3165 win.setDimensions( sizes[size] );
3166
3167 this.emit( 'resize', win );
3168
3169 return this;
3170 };
3171
3172 /**
3173 * Bind or unbind global events for scrolling.
3174 *
3175 * @param {boolean} [on] Bind global events
3176 * @chainable
3177 */
3178 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3179 on = on === undefined ? !!this.globalEvents : !!on;
3180
3181 if ( on ) {
3182 if ( !this.globalEvents ) {
3183 this.$( this.getElementDocument() ).on( {
3184 // Prevent scrolling by keys in top-level window
3185 keydown: this.onDocumentKeyDownHandler
3186 } );
3187 this.$( this.getElementWindow() ).on( {
3188 // Prevent scrolling by wheel in top-level window
3189 mousewheel: this.onWindowMouseWheelHandler,
3190 // Start listening for top-level window dimension changes
3191 'orientationchange resize': this.onWindowResizeHandler
3192 } );
3193 // Disable window scrolling in isolated windows
3194 if ( !this.shouldIsolate() ) {
3195 $( this.getElementDocument().body ).css( 'overflow', 'hidden' );
3196 }
3197 this.globalEvents = true;
3198 }
3199 } else if ( this.globalEvents ) {
3200 // Unbind global events
3201 this.$( this.getElementDocument() ).off( {
3202 // Allow scrolling by keys in top-level window
3203 keydown: this.onDocumentKeyDownHandler
3204 } );
3205 this.$( this.getElementWindow() ).off( {
3206 // Allow scrolling by wheel in top-level window
3207 mousewheel: this.onWindowMouseWheelHandler,
3208 // Stop listening for top-level window dimension changes
3209 'orientationchange resize': this.onWindowResizeHandler
3210 } );
3211 if ( !this.shouldIsolate() ) {
3212 $( this.getElementDocument().body ).css( 'overflow', '' );
3213 }
3214 this.globalEvents = false;
3215 }
3216
3217 return this;
3218 };
3219
3220 /**
3221 * Toggle screen reader visibility of content other than the window manager.
3222 *
3223 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3224 * @chainable
3225 */
3226 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3227 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3228
3229 if ( isolate ) {
3230 if ( !this.$ariaHidden ) {
3231 // Hide everything other than the window manager from screen readers
3232 this.$ariaHidden = $( 'body' )
3233 .children()
3234 .not( this.$element.parentsUntil( 'body' ).last() )
3235 .attr( 'aria-hidden', '' );
3236 }
3237 } else if ( this.$ariaHidden ) {
3238 // Restore screen reader visibility
3239 this.$ariaHidden.removeAttr( 'aria-hidden' );
3240 this.$ariaHidden = null;
3241 }
3242
3243 return this;
3244 };
3245
3246 /**
3247 * Destroy window manager.
3248 */
3249 OO.ui.WindowManager.prototype.destroy = function () {
3250 this.toggleGlobalEvents( false );
3251 this.toggleAriaIsolation( false );
3252 this.clearWindows();
3253 this.$element.remove();
3254 };
3255
3256 /**
3257 * @class
3258 *
3259 * @constructor
3260 * @param {string|jQuery} message Description of error
3261 * @param {Object} [config] Configuration options
3262 * @cfg {boolean} [recoverable=true] Error is recoverable
3263 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3264 */
3265 OO.ui.Error = function OoUiElement( message, config ) {
3266 // Configuration initialization
3267 config = config || {};
3268
3269 // Properties
3270 this.message = message instanceof jQuery ? message : String( message );
3271 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3272 this.warning = !!config.warning;
3273 };
3274
3275 /* Setup */
3276
3277 OO.initClass( OO.ui.Error );
3278
3279 /* Methods */
3280
3281 /**
3282 * Check if error can be recovered from.
3283 *
3284 * @return {boolean} Error is recoverable
3285 */
3286 OO.ui.Error.prototype.isRecoverable = function () {
3287 return this.recoverable;
3288 };
3289
3290 /**
3291 * Check if the error is a warning
3292 *
3293 * @return {boolean} Error is warning
3294 */
3295 OO.ui.Error.prototype.isWarning = function () {
3296 return this.warning;
3297 };
3298
3299 /**
3300 * Get error message as DOM nodes.
3301 *
3302 * @return {jQuery} Error message in DOM nodes
3303 */
3304 OO.ui.Error.prototype.getMessage = function () {
3305 return this.message instanceof jQuery ?
3306 this.message.clone() :
3307 $( '<div>' ).text( this.message ).contents();
3308 };
3309
3310 /**
3311 * Get error message as text.
3312 *
3313 * @return {string} Error message
3314 */
3315 OO.ui.Error.prototype.getMessageText = function () {
3316 return this.message instanceof jQuery ? this.message.text() : this.message;
3317 };
3318
3319 /**
3320 * A list of functions, called in sequence.
3321 *
3322 * If a function added to a process returns boolean false the process will stop; if it returns an
3323 * object with a `promise` method the process will use the promise to either continue to the next
3324 * step when the promise is resolved or stop when the promise is rejected.
3325 *
3326 * @class
3327 *
3328 * @constructor
3329 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3330 * call, see #createStep for more information
3331 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3332 * or a promise
3333 * @return {Object} Step object, with `callback` and `context` properties
3334 */
3335 OO.ui.Process = function ( step, context ) {
3336 // Properties
3337 this.steps = [];
3338
3339 // Initialization
3340 if ( step !== undefined ) {
3341 this.next( step, context );
3342 }
3343 };
3344
3345 /* Setup */
3346
3347 OO.initClass( OO.ui.Process );
3348
3349 /* Methods */
3350
3351 /**
3352 * Start the process.
3353 *
3354 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3355 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3356 * process, the remaining steps will not be taken
3357 */
3358 OO.ui.Process.prototype.execute = function () {
3359 var i, len, promise;
3360
3361 /**
3362 * Continue execution.
3363 *
3364 * @ignore
3365 * @param {Array} step A function and the context it should be called in
3366 * @return {Function} Function that continues the process
3367 */
3368 function proceed( step ) {
3369 return function () {
3370 // Execute step in the correct context
3371 var deferred,
3372 result = step.callback.call( step.context );
3373
3374 if ( result === false ) {
3375 // Use rejected promise for boolean false results
3376 return $.Deferred().reject( [] ).promise();
3377 }
3378 if ( typeof result === 'number' ) {
3379 if ( result < 0 ) {
3380 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3381 }
3382 // Use a delayed promise for numbers, expecting them to be in milliseconds
3383 deferred = $.Deferred();
3384 setTimeout( deferred.resolve, result );
3385 return deferred.promise();
3386 }
3387 if ( result instanceof OO.ui.Error ) {
3388 // Use rejected promise for error
3389 return $.Deferred().reject( [ result ] ).promise();
3390 }
3391 if ( $.isArray( result ) && result.length && result[0] instanceof OO.ui.Error ) {
3392 // Use rejected promise for list of errors
3393 return $.Deferred().reject( result ).promise();
3394 }
3395 // Duck-type the object to see if it can produce a promise
3396 if ( result && $.isFunction( result.promise ) ) {
3397 // Use a promise generated from the result
3398 return result.promise();
3399 }
3400 // Use resolved promise for other results
3401 return $.Deferred().resolve().promise();
3402 };
3403 }
3404
3405 if ( this.steps.length ) {
3406 // Generate a chain reaction of promises
3407 promise = proceed( this.steps[0] )();
3408 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3409 promise = promise.then( proceed( this.steps[i] ) );
3410 }
3411 } else {
3412 promise = $.Deferred().resolve().promise();
3413 }
3414
3415 return promise;
3416 };
3417
3418 /**
3419 * Create a process step.
3420 *
3421 * @private
3422 * @param {number|jQuery.Promise|Function} step
3423 *
3424 * - Number of milliseconds to wait; or
3425 * - Promise to wait to be resolved; or
3426 * - Function to execute
3427 * - If it returns boolean false the process will stop
3428 * - If it returns an object with a `promise` method the process will use the promise to either
3429 * continue to the next step when the promise is resolved or stop when the promise is rejected
3430 * - If it returns a number, the process will wait for that number of milliseconds before
3431 * proceeding
3432 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3433 * or a promise
3434 * @return {Object} Step object, with `callback` and `context` properties
3435 */
3436 OO.ui.Process.prototype.createStep = function ( step, context ) {
3437 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3438 return {
3439 callback: function () {
3440 return step;
3441 },
3442 context: null
3443 };
3444 }
3445 if ( $.isFunction( step ) ) {
3446 return {
3447 callback: step,
3448 context: context
3449 };
3450 }
3451 throw new Error( 'Cannot create process step: number, promise or function expected' );
3452 };
3453
3454 /**
3455 * Add step to the beginning of the process.
3456 *
3457 * @inheritdoc #createStep
3458 * @return {OO.ui.Process} this
3459 * @chainable
3460 */
3461 OO.ui.Process.prototype.first = function ( step, context ) {
3462 this.steps.unshift( this.createStep( step, context ) );
3463 return this;
3464 };
3465
3466 /**
3467 * Add step to the end of the process.
3468 *
3469 * @inheritdoc #createStep
3470 * @return {OO.ui.Process} this
3471 * @chainable
3472 */
3473 OO.ui.Process.prototype.next = function ( step, context ) {
3474 this.steps.push( this.createStep( step, context ) );
3475 return this;
3476 };
3477
3478 /**
3479 * Factory for tools.
3480 *
3481 * @class
3482 * @extends OO.Factory
3483 * @constructor
3484 */
3485 OO.ui.ToolFactory = function OoUiToolFactory() {
3486 // Parent constructor
3487 OO.ui.ToolFactory.super.call( this );
3488 };
3489
3490 /* Setup */
3491
3492 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3493
3494 /* Methods */
3495
3496 /**
3497 * Get tools from the factory
3498 *
3499 * @param {Array} include Included tools
3500 * @param {Array} exclude Excluded tools
3501 * @param {Array} promote Promoted tools
3502 * @param {Array} demote Demoted tools
3503 * @return {string[]} List of tools
3504 */
3505 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3506 var i, len, included, promoted, demoted,
3507 auto = [],
3508 used = {};
3509
3510 // Collect included and not excluded tools
3511 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3512
3513 // Promotion
3514 promoted = this.extract( promote, used );
3515 demoted = this.extract( demote, used );
3516
3517 // Auto
3518 for ( i = 0, len = included.length; i < len; i++ ) {
3519 if ( !used[included[i]] ) {
3520 auto.push( included[i] );
3521 }
3522 }
3523
3524 return promoted.concat( auto ).concat( demoted );
3525 };
3526
3527 /**
3528 * Get a flat list of names from a list of names or groups.
3529 *
3530 * Tools can be specified in the following ways:
3531 *
3532 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3533 * - All tools in a group: `{ group: 'group-name' }`
3534 * - All tools: `'*'`
3535 *
3536 * @private
3537 * @param {Array|string} collection List of tools
3538 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3539 * names will be added as properties
3540 * @return {string[]} List of extracted names
3541 */
3542 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3543 var i, len, item, name, tool,
3544 names = [];
3545
3546 if ( collection === '*' ) {
3547 for ( name in this.registry ) {
3548 tool = this.registry[name];
3549 if (
3550 // Only add tools by group name when auto-add is enabled
3551 tool.static.autoAddToCatchall &&
3552 // Exclude already used tools
3553 ( !used || !used[name] )
3554 ) {
3555 names.push( name );
3556 if ( used ) {
3557 used[name] = true;
3558 }
3559 }
3560 }
3561 } else if ( $.isArray( collection ) ) {
3562 for ( i = 0, len = collection.length; i < len; i++ ) {
3563 item = collection[i];
3564 // Allow plain strings as shorthand for named tools
3565 if ( typeof item === 'string' ) {
3566 item = { name: item };
3567 }
3568 if ( OO.isPlainObject( item ) ) {
3569 if ( item.group ) {
3570 for ( name in this.registry ) {
3571 tool = this.registry[name];
3572 if (
3573 // Include tools with matching group
3574 tool.static.group === item.group &&
3575 // Only add tools by group name when auto-add is enabled
3576 tool.static.autoAddToGroup &&
3577 // Exclude already used tools
3578 ( !used || !used[name] )
3579 ) {
3580 names.push( name );
3581 if ( used ) {
3582 used[name] = true;
3583 }
3584 }
3585 }
3586 // Include tools with matching name and exclude already used tools
3587 } else if ( item.name && ( !used || !used[item.name] ) ) {
3588 names.push( item.name );
3589 if ( used ) {
3590 used[item.name] = true;
3591 }
3592 }
3593 }
3594 }
3595 }
3596 return names;
3597 };
3598
3599 /**
3600 * Factory for tool groups.
3601 *
3602 * @class
3603 * @extends OO.Factory
3604 * @constructor
3605 */
3606 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3607 // Parent constructor
3608 OO.Factory.call( this );
3609
3610 var i, l,
3611 defaultClasses = this.constructor.static.getDefaultClasses();
3612
3613 // Register default toolgroups
3614 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3615 this.register( defaultClasses[i] );
3616 }
3617 };
3618
3619 /* Setup */
3620
3621 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3622
3623 /* Static Methods */
3624
3625 /**
3626 * Get a default set of classes to be registered on construction
3627 *
3628 * @return {Function[]} Default classes
3629 */
3630 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3631 return [
3632 OO.ui.BarToolGroup,
3633 OO.ui.ListToolGroup,
3634 OO.ui.MenuToolGroup
3635 ];
3636 };
3637
3638 /**
3639 * Theme logic.
3640 *
3641 * @abstract
3642 * @class
3643 *
3644 * @constructor
3645 * @param {Object} [config] Configuration options
3646 */
3647 OO.ui.Theme = function OoUiTheme( config ) {
3648 // Configuration initialization
3649 config = config || {};
3650 };
3651
3652 /* Setup */
3653
3654 OO.initClass( OO.ui.Theme );
3655
3656 /* Methods */
3657
3658 /**
3659 * Get a list of classes to be applied to a widget.
3660 *
3661 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3662 * otherwise state transitions will not work properly.
3663 *
3664 * @param {OO.ui.Element} element Element for which to get classes
3665 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3666 */
3667 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3668 return { on: [], off: [] };
3669 };
3670
3671 /**
3672 * Update CSS classes provided by the theme.
3673 *
3674 * For elements with theme logic hooks, this should be called any time there's a state change.
3675 *
3676 * @param {OO.ui.Element} element Element for which to update classes
3677 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3678 */
3679 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3680 var classes = this.getElementClasses( element );
3681
3682 element.$element
3683 .removeClass( classes.off.join( ' ' ) )
3684 .addClass( classes.on.join( ' ' ) );
3685 };
3686
3687 /**
3688 * Element with a button.
3689 *
3690 * Buttons are used for controls which can be clicked. They can be configured to use tab indexing
3691 * and access keys for accessibility purposes.
3692 *
3693 * @abstract
3694 * @class
3695 *
3696 * @constructor
3697 * @param {Object} [config] Configuration options
3698 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3699 * @cfg {boolean} [framed=true] Render button with a frame
3700 * @cfg {number} [tabIndex=0] Button's tab index. Use 0 to use default ordering, use -1 to prevent
3701 * tab focusing.
3702 * @cfg {string} [accessKey] Button's access key
3703 */
3704 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3705 // Configuration initialization
3706 config = config || {};
3707
3708 // Properties
3709 this.$button = null;
3710 this.framed = null;
3711 this.tabIndex = null;
3712 this.accessKey = null;
3713 this.active = false;
3714 this.onMouseUpHandler = this.onMouseUp.bind( this );
3715 this.onMouseDownHandler = this.onMouseDown.bind( this );
3716
3717 // Initialization
3718 this.$element.addClass( 'oo-ui-buttonElement' );
3719 this.toggleFramed( config.framed === undefined || config.framed );
3720 this.setTabIndex( config.tabIndex || 0 );
3721 this.setAccessKey( config.accessKey );
3722 this.setButtonElement( config.$button || this.$( '<a>' ) );
3723 };
3724
3725 /* Setup */
3726
3727 OO.initClass( OO.ui.ButtonElement );
3728
3729 /* Static Properties */
3730
3731 /**
3732 * Cancel mouse down events.
3733 *
3734 * @static
3735 * @inheritable
3736 * @property {boolean}
3737 */
3738 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3739
3740 /* Methods */
3741
3742 /**
3743 * Set the button element.
3744 *
3745 * If an element is already set, it will be cleaned up before setting up the new element.
3746 *
3747 * @param {jQuery} $button Element to use as button
3748 */
3749 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
3750 if ( this.$button ) {
3751 this.$button
3752 .removeClass( 'oo-ui-buttonElement-button' )
3753 .removeAttr( 'role accesskey tabindex' )
3754 .off( 'mousedown', this.onMouseDownHandler );
3755 }
3756
3757 this.$button = $button
3758 .addClass( 'oo-ui-buttonElement-button' )
3759 .attr( { role: 'button', accesskey: this.accessKey, tabindex: this.tabIndex } )
3760 .on( 'mousedown', this.onMouseDownHandler );
3761 };
3762
3763 /**
3764 * Handles mouse down events.
3765 *
3766 * @param {jQuery.Event} e Mouse down event
3767 */
3768 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
3769 if ( this.isDisabled() || e.which !== 1 ) {
3770 return false;
3771 }
3772 // Remove the tab-index while the button is down to prevent the button from stealing focus
3773 this.$button.removeAttr( 'tabindex' );
3774 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
3775 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
3776 // reliably reapply the tabindex and remove the pressed class
3777 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
3778 // Prevent change of focus unless specifically configured otherwise
3779 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
3780 return false;
3781 }
3782 };
3783
3784 /**
3785 * Handles mouse up events.
3786 *
3787 * @param {jQuery.Event} e Mouse up event
3788 */
3789 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
3790 if ( this.isDisabled() || e.which !== 1 ) {
3791 return false;
3792 }
3793 // Restore the tab-index after the button is up to restore the button's accessibility
3794 this.$button.attr( 'tabindex', this.tabIndex );
3795 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
3796 // Stop listening for mouseup, since we only needed this once
3797 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
3798 };
3799
3800 /**
3801 * Check if button has a frame.
3802 *
3803 * @return {boolean} Button is framed
3804 */
3805 OO.ui.ButtonElement.prototype.isFramed = function () {
3806 return this.framed;
3807 };
3808
3809 /**
3810 * Toggle frame.
3811 *
3812 * @param {boolean} [framed] Make button framed, omit to toggle
3813 * @chainable
3814 */
3815 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
3816 framed = framed === undefined ? !this.framed : !!framed;
3817 if ( framed !== this.framed ) {
3818 this.framed = framed;
3819 this.$element
3820 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
3821 .toggleClass( 'oo-ui-buttonElement-framed', framed );
3822 this.updateThemeClasses();
3823 }
3824
3825 return this;
3826 };
3827
3828 /**
3829 * Set tab index.
3830 *
3831 * @param {number|null} tabIndex Button's tab index, use null to remove
3832 * @chainable
3833 */
3834 OO.ui.ButtonElement.prototype.setTabIndex = function ( tabIndex ) {
3835 tabIndex = typeof tabIndex === 'number' && tabIndex >= 0 ? tabIndex : null;
3836
3837 if ( this.tabIndex !== tabIndex ) {
3838 if ( this.$button ) {
3839 if ( tabIndex !== null ) {
3840 this.$button.attr( 'tabindex', tabIndex );
3841 } else {
3842 this.$button.removeAttr( 'tabindex' );
3843 }
3844 }
3845 this.tabIndex = tabIndex;
3846 }
3847
3848 return this;
3849 };
3850
3851 /**
3852 * Set access key.
3853 *
3854 * @param {string} accessKey Button's access key, use empty string to remove
3855 * @chainable
3856 */
3857 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
3858 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
3859
3860 if ( this.accessKey !== accessKey ) {
3861 if ( this.$button ) {
3862 if ( accessKey !== null ) {
3863 this.$button.attr( 'accesskey', accessKey );
3864 } else {
3865 this.$button.removeAttr( 'accesskey' );
3866 }
3867 }
3868 this.accessKey = accessKey;
3869 }
3870
3871 return this;
3872 };
3873
3874 /**
3875 * Set active state.
3876 *
3877 * @param {boolean} [value] Make button active
3878 * @chainable
3879 */
3880 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
3881 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
3882 return this;
3883 };
3884
3885 /**
3886 * Element containing a sequence of child elements.
3887 *
3888 * @abstract
3889 * @class
3890 *
3891 * @constructor
3892 * @param {Object} [config] Configuration options
3893 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
3894 */
3895 OO.ui.GroupElement = function OoUiGroupElement( config ) {
3896 // Configuration initialization
3897 config = config || {};
3898
3899 // Properties
3900 this.$group = null;
3901 this.items = [];
3902 this.aggregateItemEvents = {};
3903
3904 // Initialization
3905 this.setGroupElement( config.$group || this.$( '<div>' ) );
3906 };
3907
3908 /* Methods */
3909
3910 /**
3911 * Set the group element.
3912 *
3913 * If an element is already set, items will be moved to the new element.
3914 *
3915 * @param {jQuery} $group Element to use as group
3916 */
3917 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
3918 var i, len;
3919
3920 this.$group = $group;
3921 for ( i = 0, len = this.items.length; i < len; i++ ) {
3922 this.$group.append( this.items[i].$element );
3923 }
3924 };
3925
3926 /**
3927 * Check if there are no items.
3928 *
3929 * @return {boolean} Group is empty
3930 */
3931 OO.ui.GroupElement.prototype.isEmpty = function () {
3932 return !this.items.length;
3933 };
3934
3935 /**
3936 * Get items.
3937 *
3938 * @return {OO.ui.Element[]} Items
3939 */
3940 OO.ui.GroupElement.prototype.getItems = function () {
3941 return this.items.slice( 0 );
3942 };
3943
3944 /**
3945 * Get an item by its data.
3946 *
3947 * Data is compared by a hash of its value. Only the first item with matching data will be returned.
3948 *
3949 * @param {Object} data Item data to search for
3950 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
3951 */
3952 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
3953 var i, len, item,
3954 hash = OO.getHash( data );
3955
3956 for ( i = 0, len = this.items.length; i < len; i++ ) {
3957 item = this.items[i];
3958 if ( hash === OO.getHash( item.getData() ) ) {
3959 return item;
3960 }
3961 }
3962
3963 return null;
3964 };
3965
3966 /**
3967 * Get items by their data.
3968 *
3969 * Data is compared by a hash of its value. All items with matching data will be returned.
3970 *
3971 * @param {Object} data Item data to search for
3972 * @return {OO.ui.Element[]} Items with equivalent data
3973 */
3974 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
3975 var i, len, item,
3976 hash = OO.getHash( data ),
3977 items = [];
3978
3979 for ( i = 0, len = this.items.length; i < len; i++ ) {
3980 item = this.items[i];
3981 if ( hash === OO.getHash( item.getData() ) ) {
3982 items.push( item );
3983 }
3984 }
3985
3986 return items;
3987 };
3988
3989 /**
3990 * Add an aggregate item event.
3991 *
3992 * Aggregated events are listened to on each item and then emitted by the group under a new name,
3993 * and with an additional leading parameter containing the item that emitted the original event.
3994 * Other arguments that were emitted from the original event are passed through.
3995 *
3996 * @param {Object.<string,string|null>} events Aggregate events emitted by group, keyed by item
3997 * event, use null value to remove aggregation
3998 * @throws {Error} If aggregation already exists
3999 */
4000 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4001 var i, len, item, add, remove, itemEvent, groupEvent;
4002
4003 for ( itemEvent in events ) {
4004 groupEvent = events[itemEvent];
4005
4006 // Remove existing aggregated event
4007 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4008 // Don't allow duplicate aggregations
4009 if ( groupEvent ) {
4010 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4011 }
4012 // Remove event aggregation from existing items
4013 for ( i = 0, len = this.items.length; i < len; i++ ) {
4014 item = this.items[i];
4015 if ( item.connect && item.disconnect ) {
4016 remove = {};
4017 remove[itemEvent] = [ 'emit', groupEvent, item ];
4018 item.disconnect( this, remove );
4019 }
4020 }
4021 // Prevent future items from aggregating event
4022 delete this.aggregateItemEvents[itemEvent];
4023 }
4024
4025 // Add new aggregate event
4026 if ( groupEvent ) {
4027 // Make future items aggregate event
4028 this.aggregateItemEvents[itemEvent] = groupEvent;
4029 // Add event aggregation to existing items
4030 for ( i = 0, len = this.items.length; i < len; i++ ) {
4031 item = this.items[i];
4032 if ( item.connect && item.disconnect ) {
4033 add = {};
4034 add[itemEvent] = [ 'emit', groupEvent, item ];
4035 item.connect( this, add );
4036 }
4037 }
4038 }
4039 }
4040 };
4041
4042 /**
4043 * Add items.
4044 *
4045 * Adding an existing item will move it.
4046 *
4047 * @param {OO.ui.Element[]} items Items
4048 * @param {number} [index] Index to insert items at
4049 * @chainable
4050 */
4051 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4052 var i, len, item, event, events, currentIndex,
4053 itemElements = [];
4054
4055 for ( i = 0, len = items.length; i < len; i++ ) {
4056 item = items[i];
4057
4058 // Check if item exists then remove it first, effectively "moving" it
4059 currentIndex = $.inArray( item, this.items );
4060 if ( currentIndex >= 0 ) {
4061 this.removeItems( [ item ] );
4062 // Adjust index to compensate for removal
4063 if ( currentIndex < index ) {
4064 index--;
4065 }
4066 }
4067 // Add the item
4068 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4069 events = {};
4070 for ( event in this.aggregateItemEvents ) {
4071 events[event] = [ 'emit', this.aggregateItemEvents[event], item ];
4072 }
4073 item.connect( this, events );
4074 }
4075 item.setElementGroup( this );
4076 itemElements.push( item.$element.get( 0 ) );
4077 }
4078
4079 if ( index === undefined || index < 0 || index >= this.items.length ) {
4080 this.$group.append( itemElements );
4081 this.items.push.apply( this.items, items );
4082 } else if ( index === 0 ) {
4083 this.$group.prepend( itemElements );
4084 this.items.unshift.apply( this.items, items );
4085 } else {
4086 this.items[index].$element.before( itemElements );
4087 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4088 }
4089
4090 return this;
4091 };
4092
4093 /**
4094 * Remove items.
4095 *
4096 * Items will be detached, not removed, so they can be used later.
4097 *
4098 * @param {OO.ui.Element[]} items Items to remove
4099 * @chainable
4100 */
4101 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4102 var i, len, item, index, remove, itemEvent;
4103
4104 // Remove specific items
4105 for ( i = 0, len = items.length; i < len; i++ ) {
4106 item = items[i];
4107 index = $.inArray( item, this.items );
4108 if ( index !== -1 ) {
4109 if (
4110 item.connect && item.disconnect &&
4111 !$.isEmptyObject( this.aggregateItemEvents )
4112 ) {
4113 remove = {};
4114 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4115 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4116 }
4117 item.disconnect( this, remove );
4118 }
4119 item.setElementGroup( null );
4120 this.items.splice( index, 1 );
4121 item.$element.detach();
4122 }
4123 }
4124
4125 return this;
4126 };
4127
4128 /**
4129 * Clear all items.
4130 *
4131 * Items will be detached, not removed, so they can be used later.
4132 *
4133 * @chainable
4134 */
4135 OO.ui.GroupElement.prototype.clearItems = function () {
4136 var i, len, item, remove, itemEvent;
4137
4138 // Remove all items
4139 for ( i = 0, len = this.items.length; i < len; i++ ) {
4140 item = this.items[i];
4141 if (
4142 item.connect && item.disconnect &&
4143 !$.isEmptyObject( this.aggregateItemEvents )
4144 ) {
4145 remove = {};
4146 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4147 remove[itemEvent] = [ 'emit', this.aggregateItemEvents[itemEvent], item ];
4148 }
4149 item.disconnect( this, remove );
4150 }
4151 item.setElementGroup( null );
4152 item.$element.detach();
4153 }
4154
4155 this.items = [];
4156 return this;
4157 };
4158
4159 /**
4160 * A mixin for an element that can be dragged and dropped.
4161 * Use in conjunction with DragGroupWidget
4162 *
4163 * @abstract
4164 * @class
4165 *
4166 * @constructor
4167 */
4168 OO.ui.DraggableElement = function OoUiDraggableElement() {
4169 // Properties
4170 this.index = null;
4171
4172 // Initialize and events
4173 this.$element
4174 .attr( 'draggable', true )
4175 .addClass( 'oo-ui-draggableElement' )
4176 .on( {
4177 dragstart: this.onDragStart.bind( this ),
4178 dragover: this.onDragOver.bind( this ),
4179 dragend: this.onDragEnd.bind( this ),
4180 drop: this.onDrop.bind( this )
4181 } );
4182 };
4183
4184 /* Events */
4185
4186 /**
4187 * @event dragstart
4188 * @param {OO.ui.DraggableElement} item Dragging item
4189 */
4190
4191 /**
4192 * @event dragend
4193 */
4194
4195 /**
4196 * @event drop
4197 */
4198
4199 /* Methods */
4200
4201 /**
4202 * Respond to dragstart event.
4203 * @param {jQuery.Event} event jQuery event
4204 * @fires dragstart
4205 */
4206 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4207 var dataTransfer = e.originalEvent.dataTransfer;
4208 // Define drop effect
4209 dataTransfer.dropEffect = 'none';
4210 dataTransfer.effectAllowed = 'move';
4211 // We must set up a dataTransfer data property or Firefox seems to
4212 // ignore the fact the element is draggable.
4213 try {
4214 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4215 } catch ( err ) {
4216 // The above is only for firefox. No need to set a catch clause
4217 // if it fails, move on.
4218 }
4219 // Add dragging class
4220 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4221 // Emit event
4222 this.emit( 'dragstart', this );
4223 return true;
4224 };
4225
4226 /**
4227 * Respond to dragend event.
4228 * @fires dragend
4229 */
4230 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4231 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4232 this.emit( 'dragend' );
4233 };
4234
4235 /**
4236 * Handle drop event.
4237 * @param {jQuery.Event} event jQuery event
4238 * @fires drop
4239 */
4240 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4241 e.preventDefault();
4242 this.emit( 'drop', e );
4243 };
4244
4245 /**
4246 * In order for drag/drop to work, the dragover event must
4247 * return false and stop propogation.
4248 */
4249 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4250 e.preventDefault();
4251 };
4252
4253 /**
4254 * Set item index.
4255 * Store it in the DOM so we can access from the widget drag event
4256 * @param {number} Item index
4257 */
4258 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4259 if ( this.index !== index ) {
4260 this.index = index;
4261 this.$element.data( 'index', index );
4262 }
4263 };
4264
4265 /**
4266 * Get item index
4267 * @return {number} Item index
4268 */
4269 OO.ui.DraggableElement.prototype.getIndex = function () {
4270 return this.index;
4271 };
4272
4273 /**
4274 * Element containing a sequence of child elements that can be dragged
4275 * and dropped.
4276 *
4277 * @abstract
4278 * @class
4279 *
4280 * @constructor
4281 * @param {Object} [config] Configuration options
4282 * @cfg {jQuery} [$group] Container node, assigned to #$group, omit to use a generated `<div>`
4283 * @cfg {string} [orientation] Item orientation, 'horizontal' or 'vertical'. Defaults to 'vertical'
4284 */
4285 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4286 // Configuration initialization
4287 config = config || {};
4288
4289 // Parent constructor
4290 OO.ui.GroupElement.call( this, config );
4291
4292 // Properties
4293 this.orientation = config.orientation || 'vertical';
4294 this.dragItem = null;
4295 this.itemDragOver = null;
4296 this.itemKeys = {};
4297 this.sideInsertion = '';
4298
4299 // Events
4300 this.aggregate( {
4301 dragstart: 'itemDragStart',
4302 dragend: 'itemDragEnd',
4303 drop: 'itemDrop'
4304 } );
4305 this.connect( this, {
4306 itemDragStart: 'onItemDragStart',
4307 itemDrop: 'onItemDrop',
4308 itemDragEnd: 'onItemDragEnd'
4309 } );
4310 this.$element.on( {
4311 dragover: $.proxy( this.onDragOver, this ),
4312 dragleave: $.proxy( this.onDragLeave, this )
4313 } );
4314
4315 // Initialize
4316 if ( $.isArray( config.items ) ) {
4317 this.addItems( config.items );
4318 }
4319 this.$placeholder = $( '<div>' )
4320 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4321 this.$element
4322 .addClass( 'oo-ui-draggableGroupElement' )
4323 .append( this.$status )
4324 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4325 .prepend( this.$placeholder );
4326 };
4327
4328 /* Setup */
4329 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4330
4331 /* Events */
4332
4333 /**
4334 * @event reorder
4335 * @param {OO.ui.DraggableElement} item Reordered item
4336 * @param {number} [newIndex] New index for the item
4337 */
4338
4339 /* Methods */
4340
4341 /**
4342 * Respond to item drag start event
4343 * @param {OO.ui.DraggableElement} item Dragged item
4344 */
4345 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4346 var i, len;
4347
4348 // Map the index of each object
4349 for ( i = 0, len = this.items.length; i < len; i++ ) {
4350 this.items[i].setIndex( i );
4351 }
4352
4353 if ( this.orientation === 'horizontal' ) {
4354 // Set the height of the indicator
4355 this.$placeholder.css( {
4356 height: item.$element.outerHeight(),
4357 width: 2
4358 } );
4359 } else {
4360 // Set the width of the indicator
4361 this.$placeholder.css( {
4362 height: 2,
4363 width: item.$element.outerWidth()
4364 } );
4365 }
4366 this.setDragItem( item );
4367 };
4368
4369 /**
4370 * Respond to item drag end event
4371 */
4372 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4373 this.unsetDragItem();
4374 return false;
4375 };
4376
4377 /**
4378 * Handle drop event and switch the order of the items accordingly
4379 * @param {OO.ui.DraggableElement} item Dropped item
4380 * @fires reorder
4381 */
4382 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4383 var toIndex = item.getIndex();
4384 // Check if the dropped item is from the current group
4385 // TODO: Figure out a way to configure a list of legally droppable
4386 // elements even if they are not yet in the list
4387 if ( this.getDragItem() ) {
4388 // If the insertion point is 'after', the insertion index
4389 // is shifted to the right (or to the left in RTL, hence 'after')
4390 if ( this.sideInsertion === 'after' ) {
4391 toIndex++;
4392 }
4393 // Emit change event
4394 this.emit( 'reorder', this.getDragItem(), toIndex );
4395 }
4396 // Return false to prevent propogation
4397 return false;
4398 };
4399
4400 /**
4401 * Handle dragleave event.
4402 */
4403 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4404 // This means the item was dragged outside the widget
4405 this.$placeholder
4406 .css( 'left', 0 )
4407 .hide();
4408 };
4409
4410 /**
4411 * Respond to dragover event
4412 * @param {jQuery.Event} event Event details
4413 */
4414 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4415 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4416 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4417 clientX = e.originalEvent.clientX,
4418 clientY = e.originalEvent.clientY;
4419
4420 // Get the OptionWidget item we are dragging over
4421 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4422 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4423 if ( $optionWidget[0] ) {
4424 itemOffset = $optionWidget.offset();
4425 itemBoundingRect = $optionWidget[0].getBoundingClientRect();
4426 itemPosition = $optionWidget.position();
4427 itemIndex = $optionWidget.data( 'index' );
4428 }
4429
4430 if (
4431 itemOffset &&
4432 this.isDragging() &&
4433 itemIndex !== this.getDragItem().getIndex()
4434 ) {
4435 if ( this.orientation === 'horizontal' ) {
4436 // Calculate where the mouse is relative to the item width
4437 itemSize = itemBoundingRect.width;
4438 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4439 dragPosition = clientX;
4440 // Which side of the item we hover over will dictate
4441 // where the placeholder will appear, on the left or
4442 // on the right
4443 cssOutput = {
4444 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4445 top: itemPosition.top
4446 };
4447 } else {
4448 // Calculate where the mouse is relative to the item height
4449 itemSize = itemBoundingRect.height;
4450 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4451 dragPosition = clientY;
4452 // Which side of the item we hover over will dictate
4453 // where the placeholder will appear, on the top or
4454 // on the bottom
4455 cssOutput = {
4456 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4457 left: itemPosition.left
4458 };
4459 }
4460 // Store whether we are before or after an item to rearrange
4461 // For horizontal layout, we need to account for RTL, as this is flipped
4462 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4463 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4464 } else {
4465 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4466 }
4467 // Add drop indicator between objects
4468 if ( this.sideInsertion ) {
4469 this.$placeholder
4470 .css( cssOutput )
4471 .show();
4472 } else {
4473 this.$placeholder
4474 .css( {
4475 left: 0,
4476 top: 0
4477 } )
4478 .hide();
4479 }
4480 } else {
4481 // This means the item was dragged outside the widget
4482 this.$placeholder
4483 .css( 'left', 0 )
4484 .hide();
4485 }
4486 // Prevent default
4487 e.preventDefault();
4488 };
4489
4490 /**
4491 * Set a dragged item
4492 * @param {OO.ui.DraggableElement} item Dragged item
4493 */
4494 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4495 this.dragItem = item;
4496 };
4497
4498 /**
4499 * Unset the current dragged item
4500 */
4501 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4502 this.dragItem = null;
4503 this.itemDragOver = null;
4504 this.$placeholder.hide();
4505 this.sideInsertion = '';
4506 };
4507
4508 /**
4509 * Get the current dragged item
4510 * @return {OO.ui.DraggableElement|null} item Dragged item or null if no item is dragged
4511 */
4512 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4513 return this.dragItem;
4514 };
4515
4516 /**
4517 * Check if there's an item being dragged.
4518 * @return {Boolean} Item is being dragged
4519 */
4520 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4521 return this.getDragItem() !== null;
4522 };
4523
4524 /**
4525 * Element containing an icon.
4526 *
4527 * Icons are graphics, about the size of normal text. They can be used to aid the user in locating
4528 * a control or convey information in a more space efficient way. Icons should rarely be used
4529 * without labels; such as in a toolbar where space is at a premium or within a context where the
4530 * meaning is very clear to the user.
4531 *
4532 * @abstract
4533 * @class
4534 *
4535 * @constructor
4536 * @param {Object} [config] Configuration options
4537 * @cfg {jQuery} [$icon] Icon node, assigned to #$icon, omit to use a generated `<span>`
4538 * @cfg {Object|string} [icon=''] Symbolic icon name, or map of icon names keyed by language ID;
4539 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4540 * language
4541 * @cfg {string} [iconTitle] Icon title text or a function that returns text
4542 */
4543 OO.ui.IconElement = function OoUiIconElement( config ) {
4544 // Configuration initialization
4545 config = config || {};
4546
4547 // Properties
4548 this.$icon = null;
4549 this.icon = null;
4550 this.iconTitle = null;
4551
4552 // Initialization
4553 this.setIcon( config.icon || this.constructor.static.icon );
4554 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4555 this.setIconElement( config.$icon || this.$( '<span>' ) );
4556 };
4557
4558 /* Setup */
4559
4560 OO.initClass( OO.ui.IconElement );
4561
4562 /* Static Properties */
4563
4564 /**
4565 * Icon.
4566 *
4567 * Value should be the unique portion of an icon CSS class name, such as 'up' for 'oo-ui-icon-up'.
4568 *
4569 * For i18n purposes, this property can be an object containing a `default` icon name property and
4570 * additional icon names keyed by language code.
4571 *
4572 * Example of i18n icon definition:
4573 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4574 *
4575 * @static
4576 * @inheritable
4577 * @property {Object|string} Symbolic icon name, or map of icon names keyed by language ID;
4578 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4579 * language
4580 */
4581 OO.ui.IconElement.static.icon = null;
4582
4583 /**
4584 * Icon title.
4585 *
4586 * @static
4587 * @inheritable
4588 * @property {string|Function|null} Icon title text, a function that returns text or null for no
4589 * icon title
4590 */
4591 OO.ui.IconElement.static.iconTitle = null;
4592
4593 /* Methods */
4594
4595 /**
4596 * Set the icon element.
4597 *
4598 * If an element is already set, it will be cleaned up before setting up the new element.
4599 *
4600 * @param {jQuery} $icon Element to use as icon
4601 */
4602 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4603 if ( this.$icon ) {
4604 this.$icon
4605 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4606 .removeAttr( 'title' );
4607 }
4608
4609 this.$icon = $icon
4610 .addClass( 'oo-ui-iconElement-icon' )
4611 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4612 if ( this.iconTitle !== null ) {
4613 this.$icon.attr( 'title', this.iconTitle );
4614 }
4615 };
4616
4617 /**
4618 * Set icon name.
4619 *
4620 * @param {Object|string|null} icon Symbolic icon name, or map of icon names keyed by language ID;
4621 * use the 'default' key to specify the icon to be used when there is no icon in the user's
4622 * language, use null to remove icon
4623 * @chainable
4624 */
4625 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
4626 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
4627 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
4628
4629 if ( this.icon !== icon ) {
4630 if ( this.$icon ) {
4631 if ( this.icon !== null ) {
4632 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
4633 }
4634 if ( icon !== null ) {
4635 this.$icon.addClass( 'oo-ui-icon-' + icon );
4636 }
4637 }
4638 this.icon = icon;
4639 }
4640
4641 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
4642 this.updateThemeClasses();
4643
4644 return this;
4645 };
4646
4647 /**
4648 * Set icon title.
4649 *
4650 * @param {string|Function|null} icon Icon title text, a function that returns text or null
4651 * for no icon title
4652 * @chainable
4653 */
4654 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
4655 iconTitle = typeof iconTitle === 'function' ||
4656 ( typeof iconTitle === 'string' && iconTitle.length ) ?
4657 OO.ui.resolveMsg( iconTitle ) : null;
4658
4659 if ( this.iconTitle !== iconTitle ) {
4660 this.iconTitle = iconTitle;
4661 if ( this.$icon ) {
4662 if ( this.iconTitle !== null ) {
4663 this.$icon.attr( 'title', iconTitle );
4664 } else {
4665 this.$icon.removeAttr( 'title' );
4666 }
4667 }
4668 }
4669
4670 return this;
4671 };
4672
4673 /**
4674 * Get icon name.
4675 *
4676 * @return {string} Icon name
4677 */
4678 OO.ui.IconElement.prototype.getIcon = function () {
4679 return this.icon;
4680 };
4681
4682 /**
4683 * Get icon title.
4684 *
4685 * @return {string} Icon title text
4686 */
4687 OO.ui.IconElement.prototype.getIconTitle = function () {
4688 return this.iconTitle;
4689 };
4690
4691 /**
4692 * Element containing an indicator.
4693 *
4694 * Indicators are graphics, smaller than normal text. They can be used to describe unique status or
4695 * behavior. Indicators should only be used in exceptional cases; such as a button that opens a menu
4696 * instead of performing an action directly, or an item in a list which has errors that need to be
4697 * resolved.
4698 *
4699 * @abstract
4700 * @class
4701 *
4702 * @constructor
4703 * @param {Object} [config] Configuration options
4704 * @cfg {jQuery} [$indicator] Indicator node, assigned to #$indicator, omit to use a generated
4705 * `<span>`
4706 * @cfg {string} [indicator] Symbolic indicator name
4707 * @cfg {string} [indicatorTitle] Indicator title text or a function that returns text
4708 */
4709 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
4710 // Configuration initialization
4711 config = config || {};
4712
4713 // Properties
4714 this.$indicator = null;
4715 this.indicator = null;
4716 this.indicatorTitle = null;
4717
4718 // Initialization
4719 this.setIndicator( config.indicator || this.constructor.static.indicator );
4720 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
4721 this.setIndicatorElement( config.$indicator || this.$( '<span>' ) );
4722 };
4723
4724 /* Setup */
4725
4726 OO.initClass( OO.ui.IndicatorElement );
4727
4728 /* Static Properties */
4729
4730 /**
4731 * indicator.
4732 *
4733 * @static
4734 * @inheritable
4735 * @property {string|null} Symbolic indicator name
4736 */
4737 OO.ui.IndicatorElement.static.indicator = null;
4738
4739 /**
4740 * Indicator title.
4741 *
4742 * @static
4743 * @inheritable
4744 * @property {string|Function|null} Indicator title text, a function that returns text or null for no
4745 * indicator title
4746 */
4747 OO.ui.IndicatorElement.static.indicatorTitle = null;
4748
4749 /* Methods */
4750
4751 /**
4752 * Set the indicator element.
4753 *
4754 * If an element is already set, it will be cleaned up before setting up the new element.
4755 *
4756 * @param {jQuery} $indicator Element to use as indicator
4757 */
4758 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
4759 if ( this.$indicator ) {
4760 this.$indicator
4761 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
4762 .removeAttr( 'title' );
4763 }
4764
4765 this.$indicator = $indicator
4766 .addClass( 'oo-ui-indicatorElement-indicator' )
4767 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
4768 if ( this.indicatorTitle !== null ) {
4769 this.$indicator.attr( 'title', this.indicatorTitle );
4770 }
4771 };
4772
4773 /**
4774 * Set indicator name.
4775 *
4776 * @param {string|null} indicator Symbolic name of indicator to use or null for no indicator
4777 * @chainable
4778 */
4779 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
4780 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
4781
4782 if ( this.indicator !== indicator ) {
4783 if ( this.$indicator ) {
4784 if ( this.indicator !== null ) {
4785 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
4786 }
4787 if ( indicator !== null ) {
4788 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
4789 }
4790 }
4791 this.indicator = indicator;
4792 }
4793
4794 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
4795 this.updateThemeClasses();
4796
4797 return this;
4798 };
4799
4800 /**
4801 * Set indicator title.
4802 *
4803 * @param {string|Function|null} indicator Indicator title text, a function that returns text or
4804 * null for no indicator title
4805 * @chainable
4806 */
4807 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
4808 indicatorTitle = typeof indicatorTitle === 'function' ||
4809 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
4810 OO.ui.resolveMsg( indicatorTitle ) : null;
4811
4812 if ( this.indicatorTitle !== indicatorTitle ) {
4813 this.indicatorTitle = indicatorTitle;
4814 if ( this.$indicator ) {
4815 if ( this.indicatorTitle !== null ) {
4816 this.$indicator.attr( 'title', indicatorTitle );
4817 } else {
4818 this.$indicator.removeAttr( 'title' );
4819 }
4820 }
4821 }
4822
4823 return this;
4824 };
4825
4826 /**
4827 * Get indicator name.
4828 *
4829 * @return {string} Symbolic name of indicator
4830 */
4831 OO.ui.IndicatorElement.prototype.getIndicator = function () {
4832 return this.indicator;
4833 };
4834
4835 /**
4836 * Get indicator title.
4837 *
4838 * @return {string} Indicator title text
4839 */
4840 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
4841 return this.indicatorTitle;
4842 };
4843
4844 /**
4845 * Element containing a label.
4846 *
4847 * @abstract
4848 * @class
4849 *
4850 * @constructor
4851 * @param {Object} [config] Configuration options
4852 * @cfg {jQuery} [$label] Label node, assigned to #$label, omit to use a generated `<span>`
4853 * @cfg {jQuery|string|Function} [label] Label nodes, text or a function that returns nodes or text
4854 * @cfg {boolean} [autoFitLabel=true] Whether to fit the label or not.
4855 */
4856 OO.ui.LabelElement = function OoUiLabelElement( config ) {
4857 // Configuration initialization
4858 config = config || {};
4859
4860 // Properties
4861 this.$label = null;
4862 this.label = null;
4863 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
4864
4865 // Initialization
4866 this.setLabel( config.label || this.constructor.static.label );
4867 this.setLabelElement( config.$label || this.$( '<span>' ) );
4868 };
4869
4870 /* Setup */
4871
4872 OO.initClass( OO.ui.LabelElement );
4873
4874 /* Static Properties */
4875
4876 /**
4877 * Label.
4878 *
4879 * @static
4880 * @inheritable
4881 * @property {string|Function|null} Label text; a function that returns nodes or text; or null for
4882 * no label
4883 */
4884 OO.ui.LabelElement.static.label = null;
4885
4886 /* Methods */
4887
4888 /**
4889 * Set the label element.
4890 *
4891 * If an element is already set, it will be cleaned up before setting up the new element.
4892 *
4893 * @param {jQuery} $label Element to use as label
4894 */
4895 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
4896 if ( this.$label ) {
4897 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
4898 }
4899
4900 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
4901 this.setLabelContent( this.label );
4902 };
4903
4904 /**
4905 * Set the label.
4906 *
4907 * An empty string will result in the label being hidden. A string containing only whitespace will
4908 * be converted to a single `&nbsp;`.
4909 *
4910 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4911 * text; or null for no label
4912 * @chainable
4913 */
4914 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
4915 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
4916 label = ( typeof label === 'string' && label.length ) || label instanceof jQuery ? label : null;
4917
4918 if ( this.label !== label ) {
4919 if ( this.$label ) {
4920 this.setLabelContent( label );
4921 }
4922 this.label = label;
4923 }
4924
4925 this.$element.toggleClass( 'oo-ui-labelElement', !!this.label );
4926
4927 return this;
4928 };
4929
4930 /**
4931 * Get the label.
4932 *
4933 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
4934 * text; or null for no label
4935 */
4936 OO.ui.LabelElement.prototype.getLabel = function () {
4937 return this.label;
4938 };
4939
4940 /**
4941 * Fit the label.
4942 *
4943 * @chainable
4944 */
4945 OO.ui.LabelElement.prototype.fitLabel = function () {
4946 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
4947 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
4948 }
4949
4950 return this;
4951 };
4952
4953 /**
4954 * Set the content of the label.
4955 *
4956 * Do not call this method until after the label element has been set by #setLabelElement.
4957 *
4958 * @private
4959 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
4960 * text; or null for no label
4961 */
4962 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
4963 if ( typeof label === 'string' ) {
4964 if ( label.match( /^\s*$/ ) ) {
4965 // Convert whitespace only string to a single non-breaking space
4966 this.$label.html( '&nbsp;' );
4967 } else {
4968 this.$label.text( label );
4969 }
4970 } else if ( label instanceof jQuery ) {
4971 this.$label.empty().append( label );
4972 } else {
4973 this.$label.empty();
4974 }
4975 };
4976
4977 /**
4978 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
4979 *
4980 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
4981 * be aware that this will cause new suggestions to be looked up for the new value. If this is
4982 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
4983 *
4984 * @class
4985 * @abstract
4986 *
4987 * @constructor
4988 * @param {Object} [config] Configuration options
4989 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
4990 * @cfg {jQuery} [$container=this.$element] Element to render menu under
4991 */
4992 OO.ui.LookupElement = function OoUiLookupElement( config ) {
4993 // Configuration initialization
4994 config = config || {};
4995
4996 // Properties
4997 this.$overlay = config.$overlay || this.$element;
4998 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
4999 $: OO.ui.Element.static.getJQuery( this.$overlay ),
5000 $container: config.$container
5001 } );
5002 this.lookupCache = {};
5003 this.lookupQuery = null;
5004 this.lookupRequest = null;
5005 this.lookupsDisabled = false;
5006 this.lookupInputFocused = false;
5007
5008 // Events
5009 this.$input.on( {
5010 focus: this.onLookupInputFocus.bind( this ),
5011 blur: this.onLookupInputBlur.bind( this ),
5012 mousedown: this.onLookupInputMouseDown.bind( this )
5013 } );
5014 this.connect( this, { change: 'onLookupInputChange' } );
5015 this.lookupMenu.connect( this, {
5016 toggle: 'onLookupMenuToggle',
5017 choose: 'onLookupMenuItemChoose'
5018 } );
5019
5020 // Initialization
5021 this.$element.addClass( 'oo-ui-lookupElement' );
5022 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5023 this.$overlay.append( this.lookupMenu.$element );
5024 };
5025
5026 /* Methods */
5027
5028 /**
5029 * Handle input focus event.
5030 *
5031 * @param {jQuery.Event} e Input focus event
5032 */
5033 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5034 this.lookupInputFocused = true;
5035 this.populateLookupMenu();
5036 };
5037
5038 /**
5039 * Handle input blur event.
5040 *
5041 * @param {jQuery.Event} e Input blur event
5042 */
5043 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5044 this.closeLookupMenu();
5045 this.lookupInputFocused = false;
5046 };
5047
5048 /**
5049 * Handle input mouse down event.
5050 *
5051 * @param {jQuery.Event} e Input mouse down event
5052 */
5053 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5054 // Only open the menu if the input was already focused.
5055 // This way we allow the user to open the menu again after closing it with Esc
5056 // by clicking in the input. Opening (and populating) the menu when initially
5057 // clicking into the input is handled by the focus handler.
5058 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5059 this.populateLookupMenu();
5060 }
5061 };
5062
5063 /**
5064 * Handle input change event.
5065 *
5066 * @param {string} value New input value
5067 */
5068 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5069 if ( this.lookupInputFocused ) {
5070 this.populateLookupMenu();
5071 }
5072 };
5073
5074 /**
5075 * Handle the lookup menu being shown/hidden.
5076 *
5077 * @param {boolean} visible Whether the lookup menu is now visible.
5078 */
5079 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5080 if ( !visible ) {
5081 // When the menu is hidden, abort any active request and clear the menu.
5082 // This has to be done here in addition to closeLookupMenu(), because
5083 // MenuSelectWidget will close itself when the user presses Esc.
5084 this.abortLookupRequest();
5085 this.lookupMenu.clearItems();
5086 }
5087 };
5088
5089 /**
5090 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5091 *
5092 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5093 */
5094 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5095 if ( item ) {
5096 this.setValue( item.getData() );
5097 }
5098 };
5099
5100 /**
5101 * Get lookup menu.
5102 *
5103 * @return {OO.ui.TextInputMenuSelectWidget}
5104 */
5105 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5106 return this.lookupMenu;
5107 };
5108
5109 /**
5110 * Disable or re-enable lookups.
5111 *
5112 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5113 *
5114 * @param {boolean} disabled Disable lookups
5115 */
5116 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5117 this.lookupsDisabled = !!disabled;
5118 };
5119
5120 /**
5121 * Open the menu. If there are no entries in the menu, this does nothing.
5122 *
5123 * @chainable
5124 */
5125 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5126 if ( !this.lookupMenu.isEmpty() ) {
5127 this.lookupMenu.toggle( true );
5128 }
5129 return this;
5130 };
5131
5132 /**
5133 * Close the menu, empty it, and abort any pending request.
5134 *
5135 * @chainable
5136 */
5137 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5138 this.lookupMenu.toggle( false );
5139 this.abortLookupRequest();
5140 this.lookupMenu.clearItems();
5141 return this;
5142 };
5143
5144 /**
5145 * Request menu items based on the input's current value, and when they arrive,
5146 * populate the menu with these items and show the menu.
5147 *
5148 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5149 *
5150 * @chainable
5151 */
5152 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5153 var widget = this,
5154 value = this.getValue();
5155
5156 if ( this.lookupsDisabled ) {
5157 return;
5158 }
5159
5160 // If the input is empty, clear the menu
5161 if ( value === '' ) {
5162 this.closeLookupMenu();
5163 // Skip population if there is already a request pending for the current value
5164 } else if ( value !== this.lookupQuery ) {
5165 this.getLookupMenuItems()
5166 .done( function ( items ) {
5167 widget.lookupMenu.clearItems();
5168 if ( items.length ) {
5169 widget.lookupMenu
5170 .addItems( items )
5171 .toggle( true );
5172 widget.initializeLookupMenuSelection();
5173 } else {
5174 widget.lookupMenu.toggle( false );
5175 }
5176 } )
5177 .fail( function () {
5178 widget.lookupMenu.clearItems();
5179 } );
5180 }
5181
5182 return this;
5183 };
5184
5185 /**
5186 * Select and highlight the first selectable item in the menu.
5187 *
5188 * @chainable
5189 */
5190 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5191 if ( !this.lookupMenu.getSelectedItem() ) {
5192 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5193 }
5194 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5195 };
5196
5197 /**
5198 * Get lookup menu items for the current query.
5199 *
5200 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5201 * the done event. If the request was aborted to make way for a subsequent request, this promise
5202 * will not be rejected: it will remain pending forever.
5203 */
5204 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5205 var widget = this,
5206 value = this.getValue(),
5207 deferred = $.Deferred(),
5208 ourRequest;
5209
5210 this.abortLookupRequest();
5211 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5212 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[value] ) );
5213 } else {
5214 this.pushPending();
5215 this.lookupQuery = value;
5216 ourRequest = this.lookupRequest = this.getLookupRequest();
5217 ourRequest
5218 .always( function () {
5219 // We need to pop pending even if this is an old request, otherwise
5220 // the widget will remain pending forever.
5221 // TODO: this assumes that an aborted request will fail or succeed soon after
5222 // being aborted, or at least eventually. It would be nice if we could popPending()
5223 // at abort time, but only if we knew that we hadn't already called popPending()
5224 // for that request.
5225 widget.popPending();
5226 } )
5227 .done( function ( data ) {
5228 // If this is an old request (and aborting it somehow caused it to still succeed),
5229 // ignore its success completely
5230 if ( ourRequest === widget.lookupRequest ) {
5231 widget.lookupQuery = null;
5232 widget.lookupRequest = null;
5233 widget.lookupCache[value] = widget.getLookupCacheDataFromResponse( data );
5234 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[value] ) );
5235 }
5236 } )
5237 .fail( function () {
5238 // If this is an old request (or a request failing because it's being aborted),
5239 // ignore its failure completely
5240 if ( ourRequest === widget.lookupRequest ) {
5241 widget.lookupQuery = null;
5242 widget.lookupRequest = null;
5243 deferred.reject();
5244 }
5245 } );
5246 }
5247 return deferred.promise();
5248 };
5249
5250 /**
5251 * Abort the currently pending lookup request, if any.
5252 */
5253 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5254 var oldRequest = this.lookupRequest;
5255 if ( oldRequest ) {
5256 // First unset this.lookupRequest to the fail handler will notice
5257 // that the request is no longer current
5258 this.lookupRequest = null;
5259 this.lookupQuery = null;
5260 oldRequest.abort();
5261 }
5262 };
5263
5264 /**
5265 * Get a new request object of the current lookup query value.
5266 *
5267 * @abstract
5268 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5269 */
5270 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5271 // Stub, implemented in subclass
5272 return null;
5273 };
5274
5275 /**
5276 * Pre-process data returned by the request from #getLookupRequest.
5277 *
5278 * The return value of this function will be cached, and any further queries for the given value
5279 * will use the cache rather than doing API requests.
5280 *
5281 * @abstract
5282 * @param {Mixed} data Response from server
5283 * @return {Mixed} Cached result data
5284 */
5285 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5286 // Stub, implemented in subclass
5287 return [];
5288 };
5289
5290 /**
5291 * Get a list of menu option widgets from the (possibly cached) data returned by
5292 * #getLookupCacheDataFromResponse.
5293 *
5294 * @abstract
5295 * @param {Mixed} data Cached result data, usually an array
5296 * @return {OO.ui.MenuOptionWidget[]} Menu items
5297 */
5298 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5299 // Stub, implemented in subclass
5300 return [];
5301 };
5302
5303 /**
5304 * Element containing an OO.ui.PopupWidget object.
5305 *
5306 * @abstract
5307 * @class
5308 *
5309 * @constructor
5310 * @param {Object} [config] Configuration options
5311 * @cfg {Object} [popup] Configuration to pass to popup
5312 * @cfg {boolean} [autoClose=true] Popup auto-closes when it loses focus
5313 */
5314 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5315 // Configuration initialization
5316 config = config || {};
5317
5318 // Properties
5319 this.popup = new OO.ui.PopupWidget( $.extend(
5320 { autoClose: true },
5321 config.popup,
5322 { $: this.$, $autoCloseIgnore: this.$element }
5323 ) );
5324 };
5325
5326 /* Methods */
5327
5328 /**
5329 * Get popup.
5330 *
5331 * @return {OO.ui.PopupWidget} Popup widget
5332 */
5333 OO.ui.PopupElement.prototype.getPopup = function () {
5334 return this.popup;
5335 };
5336
5337 /**
5338 * Element with named flags that can be added, removed, listed and checked.
5339 *
5340 * A flag, when set, adds a CSS class on the `$element` by combining `oo-ui-flaggedElement-` with
5341 * the flag name. Flags are primarily useful for styling.
5342 *
5343 * @abstract
5344 * @class
5345 *
5346 * @constructor
5347 * @param {Object} [config] Configuration options
5348 * @cfg {string|string[]} [flags] Flags describing importance and functionality, e.g. 'primary',
5349 * 'safe', 'progressive', 'destructive' or 'constructive'
5350 * @cfg {jQuery} [$flagged] Flagged node, assigned to #$flagged, omit to use #$element
5351 */
5352 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5353 // Configuration initialization
5354 config = config || {};
5355
5356 // Properties
5357 this.flags = {};
5358 this.$flagged = null;
5359
5360 // Initialization
5361 this.setFlags( config.flags );
5362 this.setFlaggedElement( config.$flagged || this.$element );
5363 };
5364
5365 /* Events */
5366
5367 /**
5368 * @event flag
5369 * @param {Object.<string,boolean>} changes Object keyed by flag name containing boolean
5370 * added/removed properties
5371 */
5372
5373 /* Methods */
5374
5375 /**
5376 * Set the flagged element.
5377 *
5378 * If an element is already set, it will be cleaned up before setting up the new element.
5379 *
5380 * @param {jQuery} $flagged Element to add flags to
5381 */
5382 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5383 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5384 return 'oo-ui-flaggedElement-' + flag;
5385 } ).join( ' ' );
5386
5387 if ( this.$flagged ) {
5388 this.$flagged.removeClass( classNames );
5389 }
5390
5391 this.$flagged = $flagged.addClass( classNames );
5392 };
5393
5394 /**
5395 * Check if a flag is set.
5396 *
5397 * @param {string} flag Name of flag
5398 * @return {boolean} Has flag
5399 */
5400 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5401 return flag in this.flags;
5402 };
5403
5404 /**
5405 * Get the names of all flags set.
5406 *
5407 * @return {string[]} Flag names
5408 */
5409 OO.ui.FlaggedElement.prototype.getFlags = function () {
5410 return Object.keys( this.flags );
5411 };
5412
5413 /**
5414 * Clear all flags.
5415 *
5416 * @chainable
5417 * @fires flag
5418 */
5419 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5420 var flag, className,
5421 changes = {},
5422 remove = [],
5423 classPrefix = 'oo-ui-flaggedElement-';
5424
5425 for ( flag in this.flags ) {
5426 className = classPrefix + flag;
5427 changes[flag] = false;
5428 delete this.flags[flag];
5429 remove.push( className );
5430 }
5431
5432 if ( this.$flagged ) {
5433 this.$flagged.removeClass( remove.join( ' ' ) );
5434 }
5435
5436 this.updateThemeClasses();
5437 this.emit( 'flag', changes );
5438
5439 return this;
5440 };
5441
5442 /**
5443 * Add one or more flags.
5444 *
5445 * @param {string|string[]|Object.<string, boolean>} flags One or more flags to add, or an object
5446 * keyed by flag name containing boolean set/remove instructions.
5447 * @chainable
5448 * @fires flag
5449 */
5450 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5451 var i, len, flag, className,
5452 changes = {},
5453 add = [],
5454 remove = [],
5455 classPrefix = 'oo-ui-flaggedElement-';
5456
5457 if ( typeof flags === 'string' ) {
5458 className = classPrefix + flags;
5459 // Set
5460 if ( !this.flags[flags] ) {
5461 this.flags[flags] = true;
5462 add.push( className );
5463 }
5464 } else if ( $.isArray( flags ) ) {
5465 for ( i = 0, len = flags.length; i < len; i++ ) {
5466 flag = flags[i];
5467 className = classPrefix + flag;
5468 // Set
5469 if ( !this.flags[flag] ) {
5470 changes[flag] = true;
5471 this.flags[flag] = true;
5472 add.push( className );
5473 }
5474 }
5475 } else if ( OO.isPlainObject( flags ) ) {
5476 for ( flag in flags ) {
5477 className = classPrefix + flag;
5478 if ( flags[flag] ) {
5479 // Set
5480 if ( !this.flags[flag] ) {
5481 changes[flag] = true;
5482 this.flags[flag] = true;
5483 add.push( className );
5484 }
5485 } else {
5486 // Remove
5487 if ( this.flags[flag] ) {
5488 changes[flag] = false;
5489 delete this.flags[flag];
5490 remove.push( className );
5491 }
5492 }
5493 }
5494 }
5495
5496 if ( this.$flagged ) {
5497 this.$flagged
5498 .addClass( add.join( ' ' ) )
5499 .removeClass( remove.join( ' ' ) );
5500 }
5501
5502 this.updateThemeClasses();
5503 this.emit( 'flag', changes );
5504
5505 return this;
5506 };
5507
5508 /**
5509 * Element with a title.
5510 *
5511 * Titles are rendered by the browser and are made visible when hovering the element. Titles are
5512 * not visible on touch devices.
5513 *
5514 * @abstract
5515 * @class
5516 *
5517 * @constructor
5518 * @param {Object} [config] Configuration options
5519 * @cfg {jQuery} [$titled] Titled node, assigned to #$titled, omit to use #$element
5520 * @cfg {string|Function} [title] Title text or a function that returns text. If not provided, the
5521 * static property 'title' is used.
5522 */
5523 OO.ui.TitledElement = function OoUiTitledElement( config ) {
5524 // Configuration initialization
5525 config = config || {};
5526
5527 // Properties
5528 this.$titled = null;
5529 this.title = null;
5530
5531 // Initialization
5532 this.setTitle( config.title || this.constructor.static.title );
5533 this.setTitledElement( config.$titled || this.$element );
5534 };
5535
5536 /* Setup */
5537
5538 OO.initClass( OO.ui.TitledElement );
5539
5540 /* Static Properties */
5541
5542 /**
5543 * Title.
5544 *
5545 * @static
5546 * @inheritable
5547 * @property {string|Function} Title text or a function that returns text
5548 */
5549 OO.ui.TitledElement.static.title = null;
5550
5551 /* Methods */
5552
5553 /**
5554 * Set the titled element.
5555 *
5556 * If an element is already set, it will be cleaned up before setting up the new element.
5557 *
5558 * @param {jQuery} $titled Element to set title on
5559 */
5560 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
5561 if ( this.$titled ) {
5562 this.$titled.removeAttr( 'title' );
5563 }
5564
5565 this.$titled = $titled;
5566 if ( this.title ) {
5567 this.$titled.attr( 'title', this.title );
5568 }
5569 };
5570
5571 /**
5572 * Set title.
5573 *
5574 * @param {string|Function|null} title Title text, a function that returns text or null for no title
5575 * @chainable
5576 */
5577 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
5578 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
5579
5580 if ( this.title !== title ) {
5581 if ( this.$titled ) {
5582 if ( title !== null ) {
5583 this.$titled.attr( 'title', title );
5584 } else {
5585 this.$titled.removeAttr( 'title' );
5586 }
5587 }
5588 this.title = title;
5589 }
5590
5591 return this;
5592 };
5593
5594 /**
5595 * Get title.
5596 *
5597 * @return {string} Title string
5598 */
5599 OO.ui.TitledElement.prototype.getTitle = function () {
5600 return this.title;
5601 };
5602
5603 /**
5604 * Element that can be automatically clipped to visible boundaries.
5605 *
5606 * Whenever the element's natural height changes, you have to call
5607 * #clip to make sure it's still clipping correctly.
5608 *
5609 * @abstract
5610 * @class
5611 *
5612 * @constructor
5613 * @param {Object} [config] Configuration options
5614 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
5615 */
5616 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
5617 // Configuration initialization
5618 config = config || {};
5619
5620 // Properties
5621 this.$clippable = null;
5622 this.clipping = false;
5623 this.clippedHorizontally = false;
5624 this.clippedVertically = false;
5625 this.$clippableContainer = null;
5626 this.$clippableScroller = null;
5627 this.$clippableWindow = null;
5628 this.idealWidth = null;
5629 this.idealHeight = null;
5630 this.onClippableContainerScrollHandler = this.clip.bind( this );
5631 this.onClippableWindowResizeHandler = this.clip.bind( this );
5632
5633 // Initialization
5634 this.setClippableElement( config.$clippable || this.$element );
5635 };
5636
5637 /* Methods */
5638
5639 /**
5640 * Set clippable element.
5641 *
5642 * If an element is already set, it will be cleaned up before setting up the new element.
5643 *
5644 * @param {jQuery} $clippable Element to make clippable
5645 */
5646 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
5647 if ( this.$clippable ) {
5648 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
5649 this.$clippable.css( { width: '', height: '' } );
5650 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5651 this.$clippable.css( { overflowX: '', overflowY: '' } );
5652 }
5653
5654 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
5655 this.clip();
5656 };
5657
5658 /**
5659 * Toggle clipping.
5660 *
5661 * Do not turn clipping on until after the element is attached to the DOM and visible.
5662 *
5663 * @param {boolean} [clipping] Enable clipping, omit to toggle
5664 * @chainable
5665 */
5666 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
5667 clipping = clipping === undefined ? !this.clipping : !!clipping;
5668
5669 if ( this.clipping !== clipping ) {
5670 this.clipping = clipping;
5671 if ( clipping ) {
5672 this.$clippableContainer = this.$( this.getClosestScrollableElementContainer() );
5673 // If the clippable container is the root, we have to listen to scroll events and check
5674 // jQuery.scrollTop on the window because of browser inconsistencies
5675 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
5676 this.$( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
5677 this.$clippableContainer;
5678 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
5679 this.$clippableWindow = this.$( this.getElementWindow() )
5680 .on( 'resize', this.onClippableWindowResizeHandler );
5681 // Initial clip after visible
5682 this.clip();
5683 } else {
5684 this.$clippable.css( { width: '', height: '' } );
5685 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5686 this.$clippable.css( { overflowX: '', overflowY: '' } );
5687
5688 this.$clippableContainer = null;
5689 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
5690 this.$clippableScroller = null;
5691 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
5692 this.$clippableWindow = null;
5693 }
5694 }
5695
5696 return this;
5697 };
5698
5699 /**
5700 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
5701 *
5702 * @return {boolean} Element will be clipped to the visible area
5703 */
5704 OO.ui.ClippableElement.prototype.isClipping = function () {
5705 return this.clipping;
5706 };
5707
5708 /**
5709 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
5710 *
5711 * @return {boolean} Part of the element is being clipped
5712 */
5713 OO.ui.ClippableElement.prototype.isClipped = function () {
5714 return this.clippedHorizontally || this.clippedVertically;
5715 };
5716
5717 /**
5718 * Check if the right of the element is being clipped by the nearest scrollable container.
5719 *
5720 * @return {boolean} Part of the element is being clipped
5721 */
5722 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
5723 return this.clippedHorizontally;
5724 };
5725
5726 /**
5727 * Check if the bottom of the element is being clipped by the nearest scrollable container.
5728 *
5729 * @return {boolean} Part of the element is being clipped
5730 */
5731 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
5732 return this.clippedVertically;
5733 };
5734
5735 /**
5736 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
5737 *
5738 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
5739 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
5740 */
5741 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
5742 this.idealWidth = width;
5743 this.idealHeight = height;
5744
5745 if ( !this.clipping ) {
5746 // Update dimensions
5747 this.$clippable.css( { width: width, height: height } );
5748 }
5749 // While clipping, idealWidth and idealHeight are not considered
5750 };
5751
5752 /**
5753 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
5754 * the element's natural height changes.
5755 *
5756 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
5757 * overlapped by, the visible area of the nearest scrollable container.
5758 *
5759 * @chainable
5760 */
5761 OO.ui.ClippableElement.prototype.clip = function () {
5762 if ( !this.clipping ) {
5763 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
5764 return this;
5765 }
5766
5767 var buffer = 7, // Chosen by fair dice roll
5768 cOffset = this.$clippable.offset(),
5769 $container = this.$clippableContainer.is( 'html, body' ) ?
5770 this.$clippableWindow : this.$clippableContainer,
5771 ccOffset = $container.offset() || { top: 0, left: 0 },
5772 ccHeight = $container.innerHeight() - buffer,
5773 ccWidth = $container.innerWidth() - buffer,
5774 cHeight = this.$clippable.outerHeight() + buffer,
5775 cWidth = this.$clippable.outerWidth() + buffer,
5776 scrollTop = this.$clippableScroller.scrollTop(),
5777 scrollLeft = this.$clippableScroller.scrollLeft(),
5778 desiredWidth = cOffset.left < 0 ?
5779 cWidth + cOffset.left :
5780 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
5781 desiredHeight = cOffset.top < 0 ?
5782 cHeight + cOffset.top :
5783 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
5784 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
5785 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
5786 clipWidth = desiredWidth < naturalWidth,
5787 clipHeight = desiredHeight < naturalHeight;
5788
5789 if ( clipWidth ) {
5790 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
5791 } else {
5792 this.$clippable.css( 'width', this.idealWidth || '' );
5793 this.$clippable.width(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5794 this.$clippable.css( 'overflowX', '' );
5795 }
5796 if ( clipHeight ) {
5797 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
5798 } else {
5799 this.$clippable.css( 'height', this.idealHeight || '' );
5800 this.$clippable.height(); // Force reflow for https://code.google.com/p/chromium/issues/detail?id=387290
5801 this.$clippable.css( 'overflowY', '' );
5802 }
5803
5804 this.clippedHorizontally = clipWidth;
5805 this.clippedVertically = clipHeight;
5806
5807 return this;
5808 };
5809
5810 /**
5811 * Generic toolbar tool.
5812 *
5813 * @abstract
5814 * @class
5815 * @extends OO.ui.Widget
5816 * @mixins OO.ui.IconElement
5817 * @mixins OO.ui.FlaggedElement
5818 *
5819 * @constructor
5820 * @param {OO.ui.ToolGroup} toolGroup
5821 * @param {Object} [config] Configuration options
5822 * @cfg {string|Function} [title] Title text or a function that returns text
5823 */
5824 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
5825 // Configuration initialization
5826 config = config || {};
5827
5828 // Parent constructor
5829 OO.ui.Tool.super.call( this, config );
5830
5831 // Mixin constructors
5832 OO.ui.IconElement.call( this, config );
5833 OO.ui.FlaggedElement.call( this, config );
5834
5835 // Properties
5836 this.toolGroup = toolGroup;
5837 this.toolbar = this.toolGroup.getToolbar();
5838 this.active = false;
5839 this.$title = this.$( '<span>' );
5840 this.$accel = this.$( '<span>' );
5841 this.$link = this.$( '<a>' );
5842 this.title = null;
5843
5844 // Events
5845 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
5846
5847 // Initialization
5848 this.$title.addClass( 'oo-ui-tool-title' );
5849 this.$accel
5850 .addClass( 'oo-ui-tool-accel' )
5851 .prop( {
5852 // This may need to be changed if the key names are ever localized,
5853 // but for now they are essentially written in English
5854 dir: 'ltr',
5855 lang: 'en'
5856 } );
5857 this.$link
5858 .addClass( 'oo-ui-tool-link' )
5859 .append( this.$icon, this.$title, this.$accel )
5860 .prop( 'tabIndex', 0 )
5861 .attr( 'role', 'button' );
5862 this.$element
5863 .data( 'oo-ui-tool', this )
5864 .addClass(
5865 'oo-ui-tool ' + 'oo-ui-tool-name-' +
5866 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
5867 )
5868 .append( this.$link );
5869 this.setTitle( config.title || this.constructor.static.title );
5870 };
5871
5872 /* Setup */
5873
5874 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
5875 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
5876 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
5877
5878 /* Events */
5879
5880 /**
5881 * @event select
5882 */
5883
5884 /* Static Properties */
5885
5886 /**
5887 * @static
5888 * @inheritdoc
5889 */
5890 OO.ui.Tool.static.tagName = 'span';
5891
5892 /**
5893 * Symbolic name of tool.
5894 *
5895 * @abstract
5896 * @static
5897 * @inheritable
5898 * @property {string}
5899 */
5900 OO.ui.Tool.static.name = '';
5901
5902 /**
5903 * Tool group.
5904 *
5905 * @abstract
5906 * @static
5907 * @inheritable
5908 * @property {string}
5909 */
5910 OO.ui.Tool.static.group = '';
5911
5912 /**
5913 * Tool title.
5914 *
5915 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
5916 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
5917 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
5918 * appended to the title if the tool is part of a bar tool group.
5919 *
5920 * @abstract
5921 * @static
5922 * @inheritable
5923 * @property {string|Function} Title text or a function that returns text
5924 */
5925 OO.ui.Tool.static.title = '';
5926
5927 /**
5928 * Tool can be automatically added to catch-all groups.
5929 *
5930 * @static
5931 * @inheritable
5932 * @property {boolean}
5933 */
5934 OO.ui.Tool.static.autoAddToCatchall = true;
5935
5936 /**
5937 * Tool can be automatically added to named groups.
5938 *
5939 * @static
5940 * @property {boolean}
5941 * @inheritable
5942 */
5943 OO.ui.Tool.static.autoAddToGroup = true;
5944
5945 /**
5946 * Check if this tool is compatible with given data.
5947 *
5948 * @static
5949 * @inheritable
5950 * @param {Mixed} data Data to check
5951 * @return {boolean} Tool can be used with data
5952 */
5953 OO.ui.Tool.static.isCompatibleWith = function () {
5954 return false;
5955 };
5956
5957 /* Methods */
5958
5959 /**
5960 * Handle the toolbar state being updated.
5961 *
5962 * This is an abstract method that must be overridden in a concrete subclass.
5963 *
5964 * @abstract
5965 */
5966 OO.ui.Tool.prototype.onUpdateState = function () {
5967 throw new Error(
5968 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
5969 );
5970 };
5971
5972 /**
5973 * Handle the tool being selected.
5974 *
5975 * This is an abstract method that must be overridden in a concrete subclass.
5976 *
5977 * @abstract
5978 */
5979 OO.ui.Tool.prototype.onSelect = function () {
5980 throw new Error(
5981 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
5982 );
5983 };
5984
5985 /**
5986 * Check if the button is active.
5987 *
5988 * @return {boolean} Button is active
5989 */
5990 OO.ui.Tool.prototype.isActive = function () {
5991 return this.active;
5992 };
5993
5994 /**
5995 * Make the button appear active or inactive.
5996 *
5997 * @param {boolean} state Make button appear active
5998 */
5999 OO.ui.Tool.prototype.setActive = function ( state ) {
6000 this.active = !!state;
6001 if ( this.active ) {
6002 this.$element.addClass( 'oo-ui-tool-active' );
6003 } else {
6004 this.$element.removeClass( 'oo-ui-tool-active' );
6005 }
6006 };
6007
6008 /**
6009 * Get the tool title.
6010 *
6011 * @param {string|Function} title Title text or a function that returns text
6012 * @chainable
6013 */
6014 OO.ui.Tool.prototype.setTitle = function ( title ) {
6015 this.title = OO.ui.resolveMsg( title );
6016 this.updateTitle();
6017 return this;
6018 };
6019
6020 /**
6021 * Get the tool title.
6022 *
6023 * @return {string} Title text
6024 */
6025 OO.ui.Tool.prototype.getTitle = function () {
6026 return this.title;
6027 };
6028
6029 /**
6030 * Get the tool's symbolic name.
6031 *
6032 * @return {string} Symbolic name of tool
6033 */
6034 OO.ui.Tool.prototype.getName = function () {
6035 return this.constructor.static.name;
6036 };
6037
6038 /**
6039 * Update the title.
6040 */
6041 OO.ui.Tool.prototype.updateTitle = function () {
6042 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6043 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6044 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6045 tooltipParts = [];
6046
6047 this.$title.text( this.title );
6048 this.$accel.text( accel );
6049
6050 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6051 tooltipParts.push( this.title );
6052 }
6053 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6054 tooltipParts.push( accel );
6055 }
6056 if ( tooltipParts.length ) {
6057 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6058 } else {
6059 this.$link.removeAttr( 'title' );
6060 }
6061 };
6062
6063 /**
6064 * Destroy tool.
6065 */
6066 OO.ui.Tool.prototype.destroy = function () {
6067 this.toolbar.disconnect( this );
6068 this.$element.remove();
6069 };
6070
6071 /**
6072 * Collection of tool groups.
6073 *
6074 * @class
6075 * @extends OO.ui.Element
6076 * @mixins OO.EventEmitter
6077 * @mixins OO.ui.GroupElement
6078 *
6079 * @constructor
6080 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6081 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6082 * @param {Object} [config] Configuration options
6083 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6084 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6085 */
6086 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6087 // Configuration initialization
6088 config = config || {};
6089
6090 // Parent constructor
6091 OO.ui.Toolbar.super.call( this, config );
6092
6093 // Mixin constructors
6094 OO.EventEmitter.call( this );
6095 OO.ui.GroupElement.call( this, config );
6096
6097 // Properties
6098 this.toolFactory = toolFactory;
6099 this.toolGroupFactory = toolGroupFactory;
6100 this.groups = [];
6101 this.tools = {};
6102 this.$bar = this.$( '<div>' );
6103 this.$actions = this.$( '<div>' );
6104 this.initialized = false;
6105
6106 // Events
6107 this.$element
6108 .add( this.$bar ).add( this.$group ).add( this.$actions )
6109 .on( 'mousedown touchstart', this.onPointerDown.bind( this ) );
6110
6111 // Initialization
6112 this.$group.addClass( 'oo-ui-toolbar-tools' );
6113 if ( config.actions ) {
6114 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6115 }
6116 this.$bar
6117 .addClass( 'oo-ui-toolbar-bar' )
6118 .append( this.$group, '<div style="clear:both"></div>' );
6119 if ( config.shadow ) {
6120 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6121 }
6122 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6123 };
6124
6125 /* Setup */
6126
6127 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6128 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6129 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6130
6131 /* Methods */
6132
6133 /**
6134 * Get the tool factory.
6135 *
6136 * @return {OO.ui.ToolFactory} Tool factory
6137 */
6138 OO.ui.Toolbar.prototype.getToolFactory = function () {
6139 return this.toolFactory;
6140 };
6141
6142 /**
6143 * Get the tool group factory.
6144 *
6145 * @return {OO.Factory} Tool group factory
6146 */
6147 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6148 return this.toolGroupFactory;
6149 };
6150
6151 /**
6152 * Handles mouse down events.
6153 *
6154 * @param {jQuery.Event} e Mouse down event
6155 */
6156 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6157 var $closestWidgetToEvent = this.$( e.target ).closest( '.oo-ui-widget' ),
6158 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6159 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[0] === $closestWidgetToToolbar[0] ) {
6160 return false;
6161 }
6162 };
6163
6164 /**
6165 * Sets up handles and preloads required information for the toolbar to work.
6166 * This must be called after it is attached to a visible document and before doing anything else.
6167 */
6168 OO.ui.Toolbar.prototype.initialize = function () {
6169 this.initialized = true;
6170 };
6171
6172 /**
6173 * Setup toolbar.
6174 *
6175 * Tools can be specified in the following ways:
6176 *
6177 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6178 * - All tools in a group: `{ group: 'group-name' }`
6179 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6180 *
6181 * @param {Object.<string,Array>} groups List of tool group configurations
6182 * @param {Array|string} [groups.include] Tools to include
6183 * @param {Array|string} [groups.exclude] Tools to exclude
6184 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6185 * @param {Array|string} [groups.demote] Tools to demote to the end
6186 */
6187 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6188 var i, len, type, group,
6189 items = [],
6190 defaultType = 'bar';
6191
6192 // Cleanup previous groups
6193 this.reset();
6194
6195 // Build out new groups
6196 for ( i = 0, len = groups.length; i < len; i++ ) {
6197 group = groups[i];
6198 if ( group.include === '*' ) {
6199 // Apply defaults to catch-all groups
6200 if ( group.type === undefined ) {
6201 group.type = 'list';
6202 }
6203 if ( group.label === undefined ) {
6204 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6205 }
6206 }
6207 // Check type has been registered
6208 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6209 items.push(
6210 this.getToolGroupFactory().create( type, this, $.extend( { $: this.$ }, group ) )
6211 );
6212 }
6213 this.addItems( items );
6214 };
6215
6216 /**
6217 * Remove all tools and groups from the toolbar.
6218 */
6219 OO.ui.Toolbar.prototype.reset = function () {
6220 var i, len;
6221
6222 this.groups = [];
6223 this.tools = {};
6224 for ( i = 0, len = this.items.length; i < len; i++ ) {
6225 this.items[i].destroy();
6226 }
6227 this.clearItems();
6228 };
6229
6230 /**
6231 * Destroys toolbar, removing event handlers and DOM elements.
6232 *
6233 * Call this whenever you are done using a toolbar.
6234 */
6235 OO.ui.Toolbar.prototype.destroy = function () {
6236 this.reset();
6237 this.$element.remove();
6238 };
6239
6240 /**
6241 * Check if tool has not been used yet.
6242 *
6243 * @param {string} name Symbolic name of tool
6244 * @return {boolean} Tool is available
6245 */
6246 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6247 return !this.tools[name];
6248 };
6249
6250 /**
6251 * Prevent tool from being used again.
6252 *
6253 * @param {OO.ui.Tool} tool Tool to reserve
6254 */
6255 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6256 this.tools[tool.getName()] = tool;
6257 };
6258
6259 /**
6260 * Allow tool to be used again.
6261 *
6262 * @param {OO.ui.Tool} tool Tool to release
6263 */
6264 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6265 delete this.tools[tool.getName()];
6266 };
6267
6268 /**
6269 * Get accelerator label for tool.
6270 *
6271 * This is a stub that should be overridden to provide access to accelerator information.
6272 *
6273 * @param {string} name Symbolic name of tool
6274 * @return {string|undefined} Tool accelerator label if available
6275 */
6276 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6277 return undefined;
6278 };
6279
6280 /**
6281 * Collection of tools.
6282 *
6283 * Tools can be specified in the following ways:
6284 *
6285 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6286 * - All tools in a group: `{ group: 'group-name' }`
6287 * - All tools: `'*'`
6288 *
6289 * @abstract
6290 * @class
6291 * @extends OO.ui.Widget
6292 * @mixins OO.ui.GroupElement
6293 *
6294 * @constructor
6295 * @param {OO.ui.Toolbar} toolbar
6296 * @param {Object} [config] Configuration options
6297 * @cfg {Array|string} [include=[]] List of tools to include
6298 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6299 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6300 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6301 */
6302 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6303 // Configuration initialization
6304 config = config || {};
6305
6306 // Parent constructor
6307 OO.ui.ToolGroup.super.call( this, config );
6308
6309 // Mixin constructors
6310 OO.ui.GroupElement.call( this, config );
6311
6312 // Properties
6313 this.toolbar = toolbar;
6314 this.tools = {};
6315 this.pressed = null;
6316 this.autoDisabled = false;
6317 this.include = config.include || [];
6318 this.exclude = config.exclude || [];
6319 this.promote = config.promote || [];
6320 this.demote = config.demote || [];
6321 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6322
6323 // Events
6324 this.$element.on( {
6325 'mousedown touchstart': this.onPointerDown.bind( this ),
6326 'mouseup touchend': this.onPointerUp.bind( this ),
6327 mouseover: this.onMouseOver.bind( this ),
6328 mouseout: this.onMouseOut.bind( this )
6329 } );
6330 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6331 this.aggregate( { disable: 'itemDisable' } );
6332 this.connect( this, { itemDisable: 'updateDisabled' } );
6333
6334 // Initialization
6335 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6336 this.$element
6337 .addClass( 'oo-ui-toolGroup' )
6338 .append( this.$group );
6339 this.populate();
6340 };
6341
6342 /* Setup */
6343
6344 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6345 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6346
6347 /* Events */
6348
6349 /**
6350 * @event update
6351 */
6352
6353 /* Static Properties */
6354
6355 /**
6356 * Show labels in tooltips.
6357 *
6358 * @static
6359 * @inheritable
6360 * @property {boolean}
6361 */
6362 OO.ui.ToolGroup.static.titleTooltips = false;
6363
6364 /**
6365 * Show acceleration labels in tooltips.
6366 *
6367 * @static
6368 * @inheritable
6369 * @property {boolean}
6370 */
6371 OO.ui.ToolGroup.static.accelTooltips = false;
6372
6373 /**
6374 * Automatically disable the toolgroup when all tools are disabled
6375 *
6376 * @static
6377 * @inheritable
6378 * @property {boolean}
6379 */
6380 OO.ui.ToolGroup.static.autoDisable = true;
6381
6382 /* Methods */
6383
6384 /**
6385 * @inheritdoc
6386 */
6387 OO.ui.ToolGroup.prototype.isDisabled = function () {
6388 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6389 };
6390
6391 /**
6392 * @inheritdoc
6393 */
6394 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6395 var i, item, allDisabled = true;
6396
6397 if ( this.constructor.static.autoDisable ) {
6398 for ( i = this.items.length - 1; i >= 0; i-- ) {
6399 item = this.items[i];
6400 if ( !item.isDisabled() ) {
6401 allDisabled = false;
6402 break;
6403 }
6404 }
6405 this.autoDisabled = allDisabled;
6406 }
6407 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6408 };
6409
6410 /**
6411 * Handle mouse down events.
6412 *
6413 * @param {jQuery.Event} e Mouse down event
6414 */
6415 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6416 // e.which is 0 for touch events, 1 for left mouse button
6417 if ( !this.isDisabled() && e.which <= 1 ) {
6418 this.pressed = this.getTargetTool( e );
6419 if ( this.pressed ) {
6420 this.pressed.setActive( true );
6421 this.getElementDocument().addEventListener(
6422 'mouseup', this.onCapturedMouseUpHandler, true
6423 );
6424 }
6425 }
6426 return false;
6427 };
6428
6429 /**
6430 * Handle captured mouse up events.
6431 *
6432 * @param {Event} e Mouse up event
6433 */
6434 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6435 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6436 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6437 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6438 this.onPointerUp( e );
6439 };
6440
6441 /**
6442 * Handle mouse up events.
6443 *
6444 * @param {jQuery.Event} e Mouse up event
6445 */
6446 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
6447 var tool = this.getTargetTool( e );
6448
6449 // e.which is 0 for touch events, 1 for left mouse button
6450 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === tool ) {
6451 this.pressed.onSelect();
6452 }
6453
6454 this.pressed = null;
6455 return false;
6456 };
6457
6458 /**
6459 * Handle mouse over events.
6460 *
6461 * @param {jQuery.Event} e Mouse over event
6462 */
6463 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
6464 var tool = this.getTargetTool( e );
6465
6466 if ( this.pressed && this.pressed === tool ) {
6467 this.pressed.setActive( true );
6468 }
6469 };
6470
6471 /**
6472 * Handle mouse out events.
6473 *
6474 * @param {jQuery.Event} e Mouse out event
6475 */
6476 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
6477 var tool = this.getTargetTool( e );
6478
6479 if ( this.pressed && this.pressed === tool ) {
6480 this.pressed.setActive( false );
6481 }
6482 };
6483
6484 /**
6485 * Get the closest tool to a jQuery.Event.
6486 *
6487 * Only tool links are considered, which prevents other elements in the tool such as popups from
6488 * triggering tool group interactions.
6489 *
6490 * @private
6491 * @param {jQuery.Event} e
6492 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6493 */
6494 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
6495 var tool,
6496 $item = this.$( e.target ).closest( '.oo-ui-tool-link' );
6497
6498 if ( $item.length ) {
6499 tool = $item.parent().data( 'oo-ui-tool' );
6500 }
6501
6502 return tool && !tool.isDisabled() ? tool : null;
6503 };
6504
6505 /**
6506 * Handle tool registry register events.
6507 *
6508 * If a tool is registered after the group is created, we must repopulate the list to account for:
6509 *
6510 * - a tool being added that may be included
6511 * - a tool already included being overridden
6512 *
6513 * @param {string} name Symbolic name of tool
6514 */
6515 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
6516 this.populate();
6517 };
6518
6519 /**
6520 * Get the toolbar this group is in.
6521 *
6522 * @return {OO.ui.Toolbar} Toolbar of group
6523 */
6524 OO.ui.ToolGroup.prototype.getToolbar = function () {
6525 return this.toolbar;
6526 };
6527
6528 /**
6529 * Add and remove tools based on configuration.
6530 */
6531 OO.ui.ToolGroup.prototype.populate = function () {
6532 var i, len, name, tool,
6533 toolFactory = this.toolbar.getToolFactory(),
6534 names = {},
6535 add = [],
6536 remove = [],
6537 list = this.toolbar.getToolFactory().getTools(
6538 this.include, this.exclude, this.promote, this.demote
6539 );
6540
6541 // Build a list of needed tools
6542 for ( i = 0, len = list.length; i < len; i++ ) {
6543 name = list[i];
6544 if (
6545 // Tool exists
6546 toolFactory.lookup( name ) &&
6547 // Tool is available or is already in this group
6548 ( this.toolbar.isToolAvailable( name ) || this.tools[name] )
6549 ) {
6550 tool = this.tools[name];
6551 if ( !tool ) {
6552 // Auto-initialize tools on first use
6553 this.tools[name] = tool = toolFactory.create( name, this );
6554 tool.updateTitle();
6555 }
6556 this.toolbar.reserveTool( tool );
6557 add.push( tool );
6558 names[name] = true;
6559 }
6560 }
6561 // Remove tools that are no longer needed
6562 for ( name in this.tools ) {
6563 if ( !names[name] ) {
6564 this.tools[name].destroy();
6565 this.toolbar.releaseTool( this.tools[name] );
6566 remove.push( this.tools[name] );
6567 delete this.tools[name];
6568 }
6569 }
6570 if ( remove.length ) {
6571 this.removeItems( remove );
6572 }
6573 // Update emptiness state
6574 if ( add.length ) {
6575 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
6576 } else {
6577 this.$element.addClass( 'oo-ui-toolGroup-empty' );
6578 }
6579 // Re-add tools (moving existing ones to new locations)
6580 this.addItems( add );
6581 // Disabled state may depend on items
6582 this.updateDisabled();
6583 };
6584
6585 /**
6586 * Destroy tool group.
6587 */
6588 OO.ui.ToolGroup.prototype.destroy = function () {
6589 var name;
6590
6591 this.clearItems();
6592 this.toolbar.getToolFactory().disconnect( this );
6593 for ( name in this.tools ) {
6594 this.toolbar.releaseTool( this.tools[name] );
6595 this.tools[name].disconnect( this ).destroy();
6596 delete this.tools[name];
6597 }
6598 this.$element.remove();
6599 };
6600
6601 /**
6602 * Dialog for showing a message.
6603 *
6604 * User interface:
6605 * - Registers two actions by default (safe and primary).
6606 * - Renders action widgets in the footer.
6607 *
6608 * @class
6609 * @extends OO.ui.Dialog
6610 *
6611 * @constructor
6612 * @param {Object} [config] Configuration options
6613 */
6614 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
6615 // Parent constructor
6616 OO.ui.MessageDialog.super.call( this, config );
6617
6618 // Properties
6619 this.verticalActionLayout = null;
6620
6621 // Initialization
6622 this.$element.addClass( 'oo-ui-messageDialog' );
6623 };
6624
6625 /* Inheritance */
6626
6627 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
6628
6629 /* Static Properties */
6630
6631 OO.ui.MessageDialog.static.name = 'message';
6632
6633 OO.ui.MessageDialog.static.size = 'small';
6634
6635 OO.ui.MessageDialog.static.verbose = false;
6636
6637 /**
6638 * Dialog title.
6639 *
6640 * A confirmation dialog's title should describe what the progressive action will do. An alert
6641 * dialog's title should describe what event occurred.
6642 *
6643 * @static
6644 * inheritable
6645 * @property {jQuery|string|Function|null}
6646 */
6647 OO.ui.MessageDialog.static.title = null;
6648
6649 /**
6650 * A confirmation dialog's message should describe the consequences of the progressive action. An
6651 * alert dialog's message should describe why the event occurred.
6652 *
6653 * @static
6654 * inheritable
6655 * @property {jQuery|string|Function|null}
6656 */
6657 OO.ui.MessageDialog.static.message = null;
6658
6659 OO.ui.MessageDialog.static.actions = [
6660 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
6661 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
6662 ];
6663
6664 /* Methods */
6665
6666 /**
6667 * @inheritdoc
6668 */
6669 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
6670 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
6671
6672 // Events
6673 this.manager.connect( this, {
6674 resize: 'onResize'
6675 } );
6676
6677 return this;
6678 };
6679
6680 /**
6681 * @inheritdoc
6682 */
6683 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
6684 this.fitActions();
6685 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
6686 };
6687
6688 /**
6689 * Handle window resized events.
6690 */
6691 OO.ui.MessageDialog.prototype.onResize = function () {
6692 var dialog = this;
6693 dialog.fitActions();
6694 // Wait for CSS transition to finish and do it again :(
6695 setTimeout( function () {
6696 dialog.fitActions();
6697 }, 300 );
6698 };
6699
6700 /**
6701 * Toggle action layout between vertical and horizontal.
6702 *
6703 * @param {boolean} [value] Layout actions vertically, omit to toggle
6704 * @chainable
6705 */
6706 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
6707 value = value === undefined ? !this.verticalActionLayout : !!value;
6708
6709 if ( value !== this.verticalActionLayout ) {
6710 this.verticalActionLayout = value;
6711 this.$actions
6712 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
6713 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
6714 }
6715
6716 return this;
6717 };
6718
6719 /**
6720 * @inheritdoc
6721 */
6722 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
6723 if ( action ) {
6724 return new OO.ui.Process( function () {
6725 this.close( { action: action } );
6726 }, this );
6727 }
6728 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
6729 };
6730
6731 /**
6732 * @inheritdoc
6733 *
6734 * @param {Object} [data] Dialog opening data
6735 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
6736 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
6737 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
6738 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
6739 * action item
6740 */
6741 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
6742 data = data || {};
6743
6744 // Parent method
6745 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
6746 .next( function () {
6747 this.title.setLabel(
6748 data.title !== undefined ? data.title : this.constructor.static.title
6749 );
6750 this.message.setLabel(
6751 data.message !== undefined ? data.message : this.constructor.static.message
6752 );
6753 this.message.$element.toggleClass(
6754 'oo-ui-messageDialog-message-verbose',
6755 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
6756 );
6757 }, this );
6758 };
6759
6760 /**
6761 * @inheritdoc
6762 */
6763 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
6764 var bodyHeight, oldOverflow,
6765 $scrollable = this.container.$element;
6766
6767 oldOverflow = $scrollable[0].style.overflow;
6768 $scrollable[0].style.overflow = 'hidden';
6769
6770 // Force… ugh… something to happen
6771 $scrollable.contents().hide();
6772 $scrollable.height();
6773 $scrollable.contents().show();
6774
6775 bodyHeight = this.text.$element.outerHeight( true );
6776 $scrollable[0].style.overflow = oldOverflow;
6777
6778 return bodyHeight;
6779 };
6780
6781 /**
6782 * @inheritdoc
6783 */
6784 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
6785 var $scrollable = this.container.$element;
6786 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
6787
6788 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
6789 // Need to do it after transition completes (250ms), add 50ms just in case.
6790 setTimeout( function () {
6791 var oldOverflow = $scrollable[0].style.overflow;
6792 $scrollable[0].style.overflow = 'hidden';
6793
6794 // Force… ugh… something to happen
6795 $scrollable.contents().hide();
6796 $scrollable.height();
6797 $scrollable.contents().show();
6798
6799 $scrollable[0].style.overflow = oldOverflow;
6800 }, 300 );
6801
6802 return this;
6803 };
6804
6805 /**
6806 * @inheritdoc
6807 */
6808 OO.ui.MessageDialog.prototype.initialize = function () {
6809 // Parent method
6810 OO.ui.MessageDialog.super.prototype.initialize.call( this );
6811
6812 // Properties
6813 this.$actions = this.$( '<div>' );
6814 this.container = new OO.ui.PanelLayout( {
6815 $: this.$, scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
6816 } );
6817 this.text = new OO.ui.PanelLayout( {
6818 $: this.$, padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
6819 } );
6820 this.message = new OO.ui.LabelWidget( {
6821 $: this.$, classes: [ 'oo-ui-messageDialog-message' ]
6822 } );
6823
6824 // Initialization
6825 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
6826 this.$content.addClass( 'oo-ui-messageDialog-content' );
6827 this.container.$element.append( this.text.$element );
6828 this.text.$element.append( this.title.$element, this.message.$element );
6829 this.$body.append( this.container.$element );
6830 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
6831 this.$foot.append( this.$actions );
6832 };
6833
6834 /**
6835 * @inheritdoc
6836 */
6837 OO.ui.MessageDialog.prototype.attachActions = function () {
6838 var i, len, other, special, others;
6839
6840 // Parent method
6841 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
6842
6843 special = this.actions.getSpecial();
6844 others = this.actions.getOthers();
6845 if ( special.safe ) {
6846 this.$actions.append( special.safe.$element );
6847 special.safe.toggleFramed( false );
6848 }
6849 if ( others.length ) {
6850 for ( i = 0, len = others.length; i < len; i++ ) {
6851 other = others[i];
6852 this.$actions.append( other.$element );
6853 other.toggleFramed( false );
6854 }
6855 }
6856 if ( special.primary ) {
6857 this.$actions.append( special.primary.$element );
6858 special.primary.toggleFramed( false );
6859 }
6860
6861 if ( !this.isOpening() ) {
6862 // If the dialog is currently opening, this will be called automatically soon.
6863 // This also calls #fitActions.
6864 this.manager.updateWindowSize( this );
6865 }
6866 };
6867
6868 /**
6869 * Fit action actions into columns or rows.
6870 *
6871 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
6872 */
6873 OO.ui.MessageDialog.prototype.fitActions = function () {
6874 var i, len, action,
6875 previous = this.verticalActionLayout,
6876 actions = this.actions.get();
6877
6878 // Detect clipping
6879 this.toggleVerticalActionLayout( false );
6880 for ( i = 0, len = actions.length; i < len; i++ ) {
6881 action = actions[i];
6882 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
6883 this.toggleVerticalActionLayout( true );
6884 break;
6885 }
6886 }
6887
6888 if ( this.verticalActionLayout !== previous ) {
6889 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
6890 // We changed the layout, window height might need to be updated.
6891 this.manager.updateWindowSize( this );
6892 }
6893 };
6894
6895 /**
6896 * Navigation dialog window.
6897 *
6898 * Logic:
6899 * - Show and hide errors.
6900 * - Retry an action.
6901 *
6902 * User interface:
6903 * - Renders header with dialog title and one action widget on either side
6904 * (a 'safe' button on the left, and a 'primary' button on the right, both of
6905 * which close the dialog).
6906 * - Displays any action widgets in the footer (none by default).
6907 * - Ability to dismiss errors.
6908 *
6909 * Subclass responsibilities:
6910 * - Register a 'safe' action.
6911 * - Register a 'primary' action.
6912 * - Add content to the dialog.
6913 *
6914 * @abstract
6915 * @class
6916 * @extends OO.ui.Dialog
6917 *
6918 * @constructor
6919 * @param {Object} [config] Configuration options
6920 */
6921 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
6922 // Parent constructor
6923 OO.ui.ProcessDialog.super.call( this, config );
6924
6925 // Initialization
6926 this.$element.addClass( 'oo-ui-processDialog' );
6927 };
6928
6929 /* Setup */
6930
6931 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
6932
6933 /* Methods */
6934
6935 /**
6936 * Handle dismiss button click events.
6937 *
6938 * Hides errors.
6939 */
6940 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
6941 this.hideErrors();
6942 };
6943
6944 /**
6945 * Handle retry button click events.
6946 *
6947 * Hides errors and then tries again.
6948 */
6949 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
6950 this.hideErrors();
6951 this.executeAction( this.currentAction.getAction() );
6952 };
6953
6954 /**
6955 * @inheritdoc
6956 */
6957 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
6958 if ( this.actions.isSpecial( action ) ) {
6959 this.fitLabel();
6960 }
6961 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
6962 };
6963
6964 /**
6965 * @inheritdoc
6966 */
6967 OO.ui.ProcessDialog.prototype.initialize = function () {
6968 // Parent method
6969 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
6970
6971 // Properties
6972 this.$navigation = this.$( '<div>' );
6973 this.$location = this.$( '<div>' );
6974 this.$safeActions = this.$( '<div>' );
6975 this.$primaryActions = this.$( '<div>' );
6976 this.$otherActions = this.$( '<div>' );
6977 this.dismissButton = new OO.ui.ButtonWidget( {
6978 $: this.$,
6979 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
6980 } );
6981 this.retryButton = new OO.ui.ButtonWidget( { $: this.$ } );
6982 this.$errors = this.$( '<div>' );
6983 this.$errorsTitle = this.$( '<div>' );
6984
6985 // Events
6986 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
6987 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
6988
6989 // Initialization
6990 this.title.$element.addClass( 'oo-ui-processDialog-title' );
6991 this.$location
6992 .append( this.title.$element )
6993 .addClass( 'oo-ui-processDialog-location' );
6994 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
6995 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
6996 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
6997 this.$errorsTitle
6998 .addClass( 'oo-ui-processDialog-errors-title' )
6999 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7000 this.$errors
7001 .addClass( 'oo-ui-processDialog-errors' )
7002 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7003 this.$content
7004 .addClass( 'oo-ui-processDialog-content' )
7005 .append( this.$errors );
7006 this.$navigation
7007 .addClass( 'oo-ui-processDialog-navigation' )
7008 .append( this.$safeActions, this.$location, this.$primaryActions );
7009 this.$head.append( this.$navigation );
7010 this.$foot.append( this.$otherActions );
7011 };
7012
7013 /**
7014 * @inheritdoc
7015 */
7016 OO.ui.ProcessDialog.prototype.attachActions = function () {
7017 var i, len, other, special, others;
7018
7019 // Parent method
7020 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7021
7022 special = this.actions.getSpecial();
7023 others = this.actions.getOthers();
7024 if ( special.primary ) {
7025 this.$primaryActions.append( special.primary.$element );
7026 special.primary.toggleFramed( true );
7027 }
7028 if ( others.length ) {
7029 for ( i = 0, len = others.length; i < len; i++ ) {
7030 other = others[i];
7031 this.$otherActions.append( other.$element );
7032 other.toggleFramed( true );
7033 }
7034 }
7035 if ( special.safe ) {
7036 this.$safeActions.append( special.safe.$element );
7037 special.safe.toggleFramed( true );
7038 }
7039
7040 this.fitLabel();
7041 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7042 };
7043
7044 /**
7045 * @inheritdoc
7046 */
7047 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7048 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7049 .fail( this.showErrors.bind( this ) );
7050 };
7051
7052 /**
7053 * Fit label between actions.
7054 *
7055 * @chainable
7056 */
7057 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7058 var width = Math.max(
7059 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7060 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7061 );
7062 this.$location.css( { paddingLeft: width, paddingRight: width } );
7063
7064 return this;
7065 };
7066
7067 /**
7068 * Handle errors that occurred during accept or reject processes.
7069 *
7070 * @param {OO.ui.Error[]} errors Errors to be handled
7071 */
7072 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7073 var i, len, $item,
7074 items = [],
7075 recoverable = true,
7076 warning = false;
7077
7078 for ( i = 0, len = errors.length; i < len; i++ ) {
7079 if ( !errors[i].isRecoverable() ) {
7080 recoverable = false;
7081 }
7082 if ( errors[i].isWarning() ) {
7083 warning = true;
7084 }
7085 $item = this.$( '<div>' )
7086 .addClass( 'oo-ui-processDialog-error' )
7087 .append( errors[i].getMessage() );
7088 items.push( $item[0] );
7089 }
7090 this.$errorItems = this.$( items );
7091 if ( recoverable ) {
7092 this.retryButton.clearFlags().setFlags( this.currentAction.getFlags() );
7093 } else {
7094 this.currentAction.setDisabled( true );
7095 }
7096 if ( warning ) {
7097 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7098 } else {
7099 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7100 }
7101 this.retryButton.toggle( recoverable );
7102 this.$errorsTitle.after( this.$errorItems );
7103 this.$errors.show().scrollTop( 0 );
7104 };
7105
7106 /**
7107 * Hide errors.
7108 */
7109 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7110 this.$errors.hide();
7111 this.$errorItems.remove();
7112 this.$errorItems = null;
7113 };
7114
7115 /**
7116 * Layout containing a series of pages.
7117 *
7118 * @class
7119 * @extends OO.ui.Layout
7120 *
7121 * @constructor
7122 * @param {Object} [config] Configuration options
7123 * @cfg {boolean} [continuous=false] Show all pages, one after another
7124 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
7125 * @cfg {boolean} [outlined=false] Show an outline
7126 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
7127 */
7128 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
7129 // Configuration initialization
7130 config = config || {};
7131
7132 // Parent constructor
7133 OO.ui.BookletLayout.super.call( this, config );
7134
7135 // Properties
7136 this.currentPageName = null;
7137 this.pages = {};
7138 this.ignoreFocus = false;
7139 this.stackLayout = new OO.ui.StackLayout( { $: this.$, continuous: !!config.continuous } );
7140 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
7141 this.outlineVisible = false;
7142 this.outlined = !!config.outlined;
7143 if ( this.outlined ) {
7144 this.editable = !!config.editable;
7145 this.outlineControlsWidget = null;
7146 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget( { $: this.$ } );
7147 this.outlinePanel = new OO.ui.PanelLayout( { $: this.$, scrollable: true } );
7148 this.gridLayout = new OO.ui.GridLayout(
7149 [ this.outlinePanel, this.stackLayout ],
7150 { $: this.$, widths: [ 1, 2 ] }
7151 );
7152 this.outlineVisible = true;
7153 if ( this.editable ) {
7154 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
7155 this.outlineSelectWidget, { $: this.$ }
7156 );
7157 }
7158 }
7159
7160 // Events
7161 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
7162 if ( this.outlined ) {
7163 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
7164 }
7165 if ( this.autoFocus ) {
7166 // Event 'focus' does not bubble, but 'focusin' does
7167 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
7168 }
7169
7170 // Initialization
7171 this.$element.addClass( 'oo-ui-bookletLayout' );
7172 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
7173 if ( this.outlined ) {
7174 this.outlinePanel.$element
7175 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
7176 .append( this.outlineSelectWidget.$element );
7177 if ( this.editable ) {
7178 this.outlinePanel.$element
7179 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
7180 .append( this.outlineControlsWidget.$element );
7181 }
7182 this.$element.append( this.gridLayout.$element );
7183 } else {
7184 this.$element.append( this.stackLayout.$element );
7185 }
7186 };
7187
7188 /* Setup */
7189
7190 OO.inheritClass( OO.ui.BookletLayout, OO.ui.Layout );
7191
7192 /* Events */
7193
7194 /**
7195 * @event set
7196 * @param {OO.ui.PageLayout} page Current page
7197 */
7198
7199 /**
7200 * @event add
7201 * @param {OO.ui.PageLayout[]} page Added pages
7202 * @param {number} index Index pages were added at
7203 */
7204
7205 /**
7206 * @event remove
7207 * @param {OO.ui.PageLayout[]} pages Removed pages
7208 */
7209
7210 /* Methods */
7211
7212 /**
7213 * Handle stack layout focus.
7214 *
7215 * @param {jQuery.Event} e Focusin event
7216 */
7217 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
7218 var name, $target;
7219
7220 // Find the page that an element was focused within
7221 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
7222 for ( name in this.pages ) {
7223 // Check for page match, exclude current page to find only page changes
7224 if ( this.pages[name].$element[0] === $target[0] && name !== this.currentPageName ) {
7225 this.setPage( name );
7226 break;
7227 }
7228 }
7229 };
7230
7231 /**
7232 * Handle stack layout set events.
7233 *
7234 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
7235 */
7236 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
7237 var layout = this;
7238 if ( page ) {
7239 page.scrollElementIntoView( { complete: function () {
7240 if ( layout.autoFocus ) {
7241 layout.focus();
7242 }
7243 } } );
7244 }
7245 };
7246
7247 /**
7248 * Focus the first input in the current page.
7249 *
7250 * If no page is selected, the first selectable page will be selected.
7251 * If the focus is already in an element on the current page, nothing will happen.
7252 */
7253 OO.ui.BookletLayout.prototype.focus = function () {
7254 var $input, page = this.stackLayout.getCurrentItem();
7255 if ( !page && this.outlined ) {
7256 this.selectFirstSelectablePage();
7257 page = this.stackLayout.getCurrentItem();
7258 if ( !page ) {
7259 return;
7260 }
7261 }
7262 // Only change the focus if is not already in the current page
7263 if ( !page.$element.find( ':focus' ).length ) {
7264 $input = page.$element.find( ':input:first' );
7265 if ( $input.length ) {
7266 $input[0].focus();
7267 }
7268 }
7269 };
7270
7271 /**
7272 * Handle outline widget select events.
7273 *
7274 * @param {OO.ui.OptionWidget|null} item Selected item
7275 */
7276 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
7277 if ( item ) {
7278 this.setPage( item.getData() );
7279 }
7280 };
7281
7282 /**
7283 * Check if booklet has an outline.
7284 *
7285 * @return {boolean}
7286 */
7287 OO.ui.BookletLayout.prototype.isOutlined = function () {
7288 return this.outlined;
7289 };
7290
7291 /**
7292 * Check if booklet has editing controls.
7293 *
7294 * @return {boolean}
7295 */
7296 OO.ui.BookletLayout.prototype.isEditable = function () {
7297 return this.editable;
7298 };
7299
7300 /**
7301 * Check if booklet has a visible outline.
7302 *
7303 * @return {boolean}
7304 */
7305 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
7306 return this.outlined && this.outlineVisible;
7307 };
7308
7309 /**
7310 * Hide or show the outline.
7311 *
7312 * @param {boolean} [show] Show outline, omit to invert current state
7313 * @chainable
7314 */
7315 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
7316 if ( this.outlined ) {
7317 show = show === undefined ? !this.outlineVisible : !!show;
7318 this.outlineVisible = show;
7319 this.gridLayout.layout( show ? [ 1, 2 ] : [ 0, 1 ], [ 1 ] );
7320 }
7321
7322 return this;
7323 };
7324
7325 /**
7326 * Get the outline widget.
7327 *
7328 * @param {OO.ui.PageLayout} page Page to be selected
7329 * @return {OO.ui.PageLayout|null} Closest page to another
7330 */
7331 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
7332 var next, prev, level,
7333 pages = this.stackLayout.getItems(),
7334 index = $.inArray( page, pages );
7335
7336 if ( index !== -1 ) {
7337 next = pages[index + 1];
7338 prev = pages[index - 1];
7339 // Prefer adjacent pages at the same level
7340 if ( this.outlined ) {
7341 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
7342 if (
7343 prev &&
7344 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
7345 ) {
7346 return prev;
7347 }
7348 if (
7349 next &&
7350 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
7351 ) {
7352 return next;
7353 }
7354 }
7355 }
7356 return prev || next || null;
7357 };
7358
7359 /**
7360 * Get the outline widget.
7361 *
7362 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
7363 */
7364 OO.ui.BookletLayout.prototype.getOutline = function () {
7365 return this.outlineSelectWidget;
7366 };
7367
7368 /**
7369 * Get the outline controls widget. If the outline is not editable, null is returned.
7370 *
7371 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
7372 */
7373 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
7374 return this.outlineControlsWidget;
7375 };
7376
7377 /**
7378 * Get a page by name.
7379 *
7380 * @param {string} name Symbolic name of page
7381 * @return {OO.ui.PageLayout|undefined} Page, if found
7382 */
7383 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
7384 return this.pages[name];
7385 };
7386
7387 /**
7388 * Get the current page name.
7389 *
7390 * @return {string|null} Current page name
7391 */
7392 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
7393 return this.currentPageName;
7394 };
7395
7396 /**
7397 * Add a page to the layout.
7398 *
7399 * When pages are added with the same names as existing pages, the existing pages will be
7400 * automatically removed before the new pages are added.
7401 *
7402 * @param {OO.ui.PageLayout[]} pages Pages to add
7403 * @param {number} index Index to insert pages after
7404 * @fires add
7405 * @chainable
7406 */
7407 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
7408 var i, len, name, page, item, currentIndex,
7409 stackLayoutPages = this.stackLayout.getItems(),
7410 remove = [],
7411 items = [];
7412
7413 // Remove pages with same names
7414 for ( i = 0, len = pages.length; i < len; i++ ) {
7415 page = pages[i];
7416 name = page.getName();
7417
7418 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
7419 // Correct the insertion index
7420 currentIndex = $.inArray( this.pages[name], stackLayoutPages );
7421 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
7422 index--;
7423 }
7424 remove.push( this.pages[name] );
7425 }
7426 }
7427 if ( remove.length ) {
7428 this.removePages( remove );
7429 }
7430
7431 // Add new pages
7432 for ( i = 0, len = pages.length; i < len; i++ ) {
7433 page = pages[i];
7434 name = page.getName();
7435 this.pages[page.getName()] = page;
7436 if ( this.outlined ) {
7437 item = new OO.ui.OutlineOptionWidget( { $: this.$, data: name } );
7438 page.setOutlineItem( item );
7439 items.push( item );
7440 }
7441 }
7442
7443 if ( this.outlined && items.length ) {
7444 this.outlineSelectWidget.addItems( items, index );
7445 this.selectFirstSelectablePage();
7446 }
7447 this.stackLayout.addItems( pages, index );
7448 this.emit( 'add', pages, index );
7449
7450 return this;
7451 };
7452
7453 /**
7454 * Remove a page from the layout.
7455 *
7456 * @fires remove
7457 * @chainable
7458 */
7459 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
7460 var i, len, name, page,
7461 items = [];
7462
7463 for ( i = 0, len = pages.length; i < len; i++ ) {
7464 page = pages[i];
7465 name = page.getName();
7466 delete this.pages[name];
7467 if ( this.outlined ) {
7468 items.push( this.outlineSelectWidget.getItemFromData( name ) );
7469 page.setOutlineItem( null );
7470 }
7471 }
7472 if ( this.outlined && items.length ) {
7473 this.outlineSelectWidget.removeItems( items );
7474 this.selectFirstSelectablePage();
7475 }
7476 this.stackLayout.removeItems( pages );
7477 this.emit( 'remove', pages );
7478
7479 return this;
7480 };
7481
7482 /**
7483 * Clear all pages from the layout.
7484 *
7485 * @fires remove
7486 * @chainable
7487 */
7488 OO.ui.BookletLayout.prototype.clearPages = function () {
7489 var i, len,
7490 pages = this.stackLayout.getItems();
7491
7492 this.pages = {};
7493 this.currentPageName = null;
7494 if ( this.outlined ) {
7495 this.outlineSelectWidget.clearItems();
7496 for ( i = 0, len = pages.length; i < len; i++ ) {
7497 pages[i].setOutlineItem( null );
7498 }
7499 }
7500 this.stackLayout.clearItems();
7501
7502 this.emit( 'remove', pages );
7503
7504 return this;
7505 };
7506
7507 /**
7508 * Set the current page by name.
7509 *
7510 * @fires set
7511 * @param {string} name Symbolic name of page
7512 */
7513 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
7514 var selectedItem,
7515 $focused,
7516 page = this.pages[name];
7517
7518 if ( name !== this.currentPageName ) {
7519 if ( this.outlined ) {
7520 selectedItem = this.outlineSelectWidget.getSelectedItem();
7521 if ( selectedItem && selectedItem.getData() !== name ) {
7522 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
7523 }
7524 }
7525 if ( page ) {
7526 if ( this.currentPageName && this.pages[this.currentPageName] ) {
7527 this.pages[this.currentPageName].setActive( false );
7528 // Blur anything focused if the next page doesn't have anything focusable - this
7529 // is not needed if the next page has something focusable because once it is focused
7530 // this blur happens automatically
7531 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
7532 $focused = this.pages[this.currentPageName].$element.find( ':focus' );
7533 if ( $focused.length ) {
7534 $focused[0].blur();
7535 }
7536 }
7537 }
7538 this.currentPageName = name;
7539 this.stackLayout.setItem( page );
7540 page.setActive( true );
7541 this.emit( 'set', page );
7542 }
7543 }
7544 };
7545
7546 /**
7547 * Select the first selectable page.
7548 *
7549 * @chainable
7550 */
7551 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
7552 if ( !this.outlineSelectWidget.getSelectedItem() ) {
7553 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
7554 }
7555
7556 return this;
7557 };
7558
7559 /**
7560 * Layout made of a field and optional label.
7561 *
7562 * Available label alignment modes include:
7563 * - left: Label is before the field and aligned away from it, best for when the user will be
7564 * scanning for a specific label in a form with many fields
7565 * - right: Label is before the field and aligned toward it, best for forms the user is very
7566 * familiar with and will tab through field checking quickly to verify which field they are in
7567 * - top: Label is before the field and above it, best for when the user will need to fill out all
7568 * fields from top to bottom in a form with few fields
7569 * - inline: Label is after the field and aligned toward it, best for small boolean fields like
7570 * checkboxes or radio buttons
7571 *
7572 * @class
7573 * @extends OO.ui.Layout
7574 * @mixins OO.ui.LabelElement
7575 *
7576 * @constructor
7577 * @param {OO.ui.Widget} fieldWidget Field widget
7578 * @param {Object} [config] Configuration options
7579 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7580 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7581 */
7582 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7583 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7584
7585 // Configuration initialization
7586 config = $.extend( { align: 'left' }, config );
7587
7588 // Properties (must be set before parent constructor, which calls #getTagName)
7589 this.fieldWidget = fieldWidget;
7590
7591 // Parent constructor
7592 OO.ui.FieldLayout.super.call( this, config );
7593
7594 // Mixin constructors
7595 OO.ui.LabelElement.call( this, config );
7596
7597 // Properties
7598 this.$field = this.$( '<div>' );
7599 this.$body = this.$( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7600 this.align = null;
7601 if ( config.help ) {
7602 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7603 $: this.$,
7604 classes: [ 'oo-ui-fieldLayout-help' ],
7605 framed: false,
7606 icon: 'info'
7607 } );
7608
7609 this.popupButtonWidget.getPopup().$body.append(
7610 this.$( '<div>' )
7611 .text( config.help )
7612 .addClass( 'oo-ui-fieldLayout-help-content' )
7613 );
7614 this.$help = this.popupButtonWidget.$element;
7615 } else {
7616 this.$help = this.$( [] );
7617 }
7618
7619 // Events
7620 if ( hasInputWidget ) {
7621 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7622 }
7623 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7624
7625 // Initialization
7626 this.$element
7627 .addClass( 'oo-ui-fieldLayout' )
7628 .append( this.$help, this.$body );
7629 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7630 this.$field
7631 .addClass( 'oo-ui-fieldLayout-field' )
7632 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7633 .append( this.fieldWidget.$element );
7634
7635 this.setAlignment( config.align );
7636 };
7637
7638 /* Setup */
7639
7640 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7641 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7642
7643 /* Methods */
7644
7645 /**
7646 * Handle field disable events.
7647 *
7648 * @param {boolean} value Field is disabled
7649 */
7650 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7651 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7652 };
7653
7654 /**
7655 * Handle label mouse click events.
7656 *
7657 * @param {jQuery.Event} e Mouse click event
7658 */
7659 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7660 this.fieldWidget.simulateLabelClick();
7661 return false;
7662 };
7663
7664 /**
7665 * Get the field.
7666 *
7667 * @return {OO.ui.Widget} Field widget
7668 */
7669 OO.ui.FieldLayout.prototype.getField = function () {
7670 return this.fieldWidget;
7671 };
7672
7673 /**
7674 * Set the field alignment mode.
7675 *
7676 * @private
7677 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7678 * @chainable
7679 */
7680 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7681 if ( value !== this.align ) {
7682 // Default to 'left'
7683 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7684 value = 'left';
7685 }
7686 // Reorder elements
7687 if ( value === 'inline' ) {
7688 this.$body.append( this.$field, this.$label );
7689 } else {
7690 this.$body.append( this.$label, this.$field );
7691 }
7692 // Set classes. The following classes can be used here:
7693 // * oo-ui-fieldLayout-align-left
7694 // * oo-ui-fieldLayout-align-right
7695 // * oo-ui-fieldLayout-align-top
7696 // * oo-ui-fieldLayout-align-inline
7697 if ( this.align ) {
7698 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7699 }
7700 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7701 this.align = value;
7702 }
7703
7704 return this;
7705 };
7706
7707 /**
7708 * Layout made of a field, a button, and an optional label.
7709 *
7710 * @class
7711 * @extends OO.ui.FieldLayout
7712 *
7713 * @constructor
7714 * @param {OO.ui.Widget} fieldWidget Field widget
7715 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7716 * @param {Object} [config] Configuration options
7717 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7718 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7719 */
7720 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7721 // Configuration initialization
7722 config = $.extend( { align: 'left' }, config );
7723
7724 // Properties (must be set before parent constructor, which calls #getTagName)
7725 this.fieldWidget = fieldWidget;
7726 this.buttonWidget = buttonWidget;
7727
7728 // Parent constructor
7729 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7730
7731 // Mixin constructors
7732 OO.ui.LabelElement.call( this, config );
7733
7734 // Properties
7735 this.$button = this.$( '<div>' )
7736 .addClass( 'oo-ui-actionFieldLayout-button' )
7737 .append( this.buttonWidget.$element );
7738
7739 this.$input = this.$( '<div>' )
7740 .addClass( 'oo-ui-actionFieldLayout-input' )
7741 .append( this.fieldWidget.$element );
7742
7743 this.$field
7744 .addClass( 'oo-ui-actionFieldLayout' )
7745 .append( this.$input, this.$button );
7746 };
7747
7748 /* Setup */
7749
7750 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7751
7752 /**
7753 * Layout made of a fieldset and optional legend.
7754 *
7755 * Just add OO.ui.FieldLayout items.
7756 *
7757 * @class
7758 * @extends OO.ui.Layout
7759 * @mixins OO.ui.IconElement
7760 * @mixins OO.ui.LabelElement
7761 * @mixins OO.ui.GroupElement
7762 *
7763 * @constructor
7764 * @param {Object} [config] Configuration options
7765 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7766 */
7767 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7768 // Configuration initialization
7769 config = config || {};
7770
7771 // Parent constructor
7772 OO.ui.FieldsetLayout.super.call( this, config );
7773
7774 // Mixin constructors
7775 OO.ui.IconElement.call( this, config );
7776 OO.ui.LabelElement.call( this, config );
7777 OO.ui.GroupElement.call( this, config );
7778
7779 // Initialization
7780 this.$element
7781 .addClass( 'oo-ui-fieldsetLayout' )
7782 .prepend( this.$icon, this.$label, this.$group );
7783 if ( $.isArray( config.items ) ) {
7784 this.addItems( config.items );
7785 }
7786 };
7787
7788 /* Setup */
7789
7790 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7791 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7792 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7793 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7794
7795 /**
7796 * Layout with an HTML form.
7797 *
7798 * @class
7799 * @extends OO.ui.Layout
7800 *
7801 * @constructor
7802 * @param {Object} [config] Configuration options
7803 * @cfg {string} [method] HTML form `method` attribute
7804 * @cfg {string} [action] HTML form `action` attribute
7805 * @cfg {string} [enctype] HTML form `enctype` attribute
7806 */
7807 OO.ui.FormLayout = function OoUiFormLayout( config ) {
7808 // Configuration initialization
7809 config = config || {};
7810
7811 // Parent constructor
7812 OO.ui.FormLayout.super.call( this, config );
7813
7814 // Events
7815 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
7816
7817 // Initialization
7818 this.$element
7819 .addClass( 'oo-ui-formLayout' )
7820 .attr( {
7821 method: config.method,
7822 action: config.action,
7823 enctype: config.enctype
7824 } );
7825 };
7826
7827 /* Setup */
7828
7829 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
7830
7831 /* Events */
7832
7833 /**
7834 * @event submit
7835 */
7836
7837 /* Static Properties */
7838
7839 OO.ui.FormLayout.static.tagName = 'form';
7840
7841 /* Methods */
7842
7843 /**
7844 * Handle form submit events.
7845 *
7846 * @param {jQuery.Event} e Submit event
7847 * @fires submit
7848 */
7849 OO.ui.FormLayout.prototype.onFormSubmit = function () {
7850 this.emit( 'submit' );
7851 return false;
7852 };
7853
7854 /**
7855 * Layout made of proportionally sized columns and rows.
7856 *
7857 * @class
7858 * @extends OO.ui.Layout
7859 *
7860 * @constructor
7861 * @param {OO.ui.PanelLayout[]} panels Panels in the grid
7862 * @param {Object} [config] Configuration options
7863 * @cfg {number[]} [widths] Widths of columns as ratios
7864 * @cfg {number[]} [heights] Heights of rows as ratios
7865 */
7866 OO.ui.GridLayout = function OoUiGridLayout( panels, config ) {
7867 var i, len, widths;
7868
7869 // Configuration initialization
7870 config = config || {};
7871
7872 // Parent constructor
7873 OO.ui.GridLayout.super.call( this, config );
7874
7875 // Properties
7876 this.panels = [];
7877 this.widths = [];
7878 this.heights = [];
7879
7880 // Initialization
7881 this.$element.addClass( 'oo-ui-gridLayout' );
7882 for ( i = 0, len = panels.length; i < len; i++ ) {
7883 this.panels.push( panels[i] );
7884 this.$element.append( panels[i].$element );
7885 }
7886 if ( config.widths || config.heights ) {
7887 this.layout( config.widths || [ 1 ], config.heights || [ 1 ] );
7888 } else {
7889 // Arrange in columns by default
7890 widths = this.panels.map( function () { return 1; } );
7891 this.layout( widths, [ 1 ] );
7892 }
7893 };
7894
7895 /* Setup */
7896
7897 OO.inheritClass( OO.ui.GridLayout, OO.ui.Layout );
7898
7899 /* Events */
7900
7901 /**
7902 * @event layout
7903 */
7904
7905 /**
7906 * @event update
7907 */
7908
7909 /* Methods */
7910
7911 /**
7912 * Set grid dimensions.
7913 *
7914 * @param {number[]} widths Widths of columns as ratios
7915 * @param {number[]} heights Heights of rows as ratios
7916 * @fires layout
7917 * @throws {Error} If grid is not large enough to fit all panels
7918 */
7919 OO.ui.GridLayout.prototype.layout = function ( widths, heights ) {
7920 var x, y,
7921 xd = 0,
7922 yd = 0,
7923 cols = widths.length,
7924 rows = heights.length;
7925
7926 // Verify grid is big enough to fit panels
7927 if ( cols * rows < this.panels.length ) {
7928 throw new Error( 'Grid is not large enough to fit ' + this.panels.length + 'panels' );
7929 }
7930
7931 // Sum up denominators
7932 for ( x = 0; x < cols; x++ ) {
7933 xd += widths[x];
7934 }
7935 for ( y = 0; y < rows; y++ ) {
7936 yd += heights[y];
7937 }
7938 // Store factors
7939 this.widths = [];
7940 this.heights = [];
7941 for ( x = 0; x < cols; x++ ) {
7942 this.widths[x] = widths[x] / xd;
7943 }
7944 for ( y = 0; y < rows; y++ ) {
7945 this.heights[y] = heights[y] / yd;
7946 }
7947 // Synchronize view
7948 this.update();
7949 this.emit( 'layout' );
7950 };
7951
7952 /**
7953 * Update panel positions and sizes.
7954 *
7955 * @fires update
7956 */
7957 OO.ui.GridLayout.prototype.update = function () {
7958 var x, y, panel, width, height, dimensions,
7959 i = 0,
7960 top = 0,
7961 left = 0,
7962 cols = this.widths.length,
7963 rows = this.heights.length;
7964
7965 for ( y = 0; y < rows; y++ ) {
7966 height = this.heights[y];
7967 for ( x = 0; x < cols; x++ ) {
7968 width = this.widths[x];
7969 panel = this.panels[i];
7970 dimensions = {
7971 width: ( width * 100 ) + '%',
7972 height: ( height * 100 ) + '%',
7973 top: ( top * 100 ) + '%'
7974 };
7975 // If RTL, reverse:
7976 if ( OO.ui.Element.static.getDir( this.$.context ) === 'rtl' ) {
7977 dimensions.right = ( left * 100 ) + '%';
7978 } else {
7979 dimensions.left = ( left * 100 ) + '%';
7980 }
7981 // HACK: Work around IE bug by setting visibility: hidden; if width or height is zero
7982 if ( width === 0 || height === 0 ) {
7983 dimensions.visibility = 'hidden';
7984 } else {
7985 dimensions.visibility = '';
7986 }
7987 panel.$element.css( dimensions );
7988 i++;
7989 left += width;
7990 }
7991 top += height;
7992 left = 0;
7993 }
7994
7995 this.emit( 'update' );
7996 };
7997
7998 /**
7999 * Get a panel at a given position.
8000 *
8001 * The x and y position is affected by the current grid layout.
8002 *
8003 * @param {number} x Horizontal position
8004 * @param {number} y Vertical position
8005 * @return {OO.ui.PanelLayout} The panel at the given position
8006 */
8007 OO.ui.GridLayout.prototype.getPanel = function ( x, y ) {
8008 return this.panels[ ( x * this.widths.length ) + y ];
8009 };
8010
8011 /**
8012 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8013 *
8014 * @class
8015 * @extends OO.ui.Layout
8016 *
8017 * @constructor
8018 * @param {Object} [config] Configuration options
8019 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8020 * @cfg {boolean} [padded=false] Pad the content from the edges
8021 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8022 */
8023 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8024 // Configuration initialization
8025 config = $.extend( {
8026 scrollable: false,
8027 padded: false,
8028 expanded: true
8029 }, config );
8030
8031 // Parent constructor
8032 OO.ui.PanelLayout.super.call( this, config );
8033
8034 // Initialization
8035 this.$element.addClass( 'oo-ui-panelLayout' );
8036 if ( config.scrollable ) {
8037 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8038 }
8039 if ( config.padded ) {
8040 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8041 }
8042 if ( config.expanded ) {
8043 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8044 }
8045 };
8046
8047 /* Setup */
8048
8049 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8050
8051 /**
8052 * Page within an booklet layout.
8053 *
8054 * @class
8055 * @extends OO.ui.PanelLayout
8056 *
8057 * @constructor
8058 * @param {string} name Unique symbolic name of page
8059 * @param {Object} [config] Configuration options
8060 */
8061 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8062 // Configuration initialization
8063 config = $.extend( { scrollable: true }, config );
8064
8065 // Parent constructor
8066 OO.ui.PageLayout.super.call( this, config );
8067
8068 // Properties
8069 this.name = name;
8070 this.outlineItem = null;
8071 this.active = false;
8072
8073 // Initialization
8074 this.$element.addClass( 'oo-ui-pageLayout' );
8075 };
8076
8077 /* Setup */
8078
8079 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8080
8081 /* Events */
8082
8083 /**
8084 * @event active
8085 * @param {boolean} active Page is active
8086 */
8087
8088 /* Methods */
8089
8090 /**
8091 * Get page name.
8092 *
8093 * @return {string} Symbolic name of page
8094 */
8095 OO.ui.PageLayout.prototype.getName = function () {
8096 return this.name;
8097 };
8098
8099 /**
8100 * Check if page is active.
8101 *
8102 * @return {boolean} Page is active
8103 */
8104 OO.ui.PageLayout.prototype.isActive = function () {
8105 return this.active;
8106 };
8107
8108 /**
8109 * Get outline item.
8110 *
8111 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8112 */
8113 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8114 return this.outlineItem;
8115 };
8116
8117 /**
8118 * Set outline item.
8119 *
8120 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8121 * outline item as desired; this method is called for setting (with an object) and unsetting
8122 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8123 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8124 *
8125 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8126 * @chainable
8127 */
8128 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8129 this.outlineItem = outlineItem || null;
8130 if ( outlineItem ) {
8131 this.setupOutlineItem();
8132 }
8133 return this;
8134 };
8135
8136 /**
8137 * Setup outline item.
8138 *
8139 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8140 *
8141 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8142 * @chainable
8143 */
8144 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8145 return this;
8146 };
8147
8148 /**
8149 * Set page active state.
8150 *
8151 * @param {boolean} Page is active
8152 * @fires active
8153 */
8154 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8155 active = !!active;
8156
8157 if ( active !== this.active ) {
8158 this.active = active;
8159 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8160 this.emit( 'active', this.active );
8161 }
8162 };
8163
8164 /**
8165 * Layout containing a series of mutually exclusive pages.
8166 *
8167 * @class
8168 * @extends OO.ui.PanelLayout
8169 * @mixins OO.ui.GroupElement
8170 *
8171 * @constructor
8172 * @param {Object} [config] Configuration options
8173 * @cfg {boolean} [continuous=false] Show all pages, one after another
8174 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8175 */
8176 OO.ui.StackLayout = function OoUiStackLayout( config ) {
8177 // Configuration initialization
8178 config = $.extend( { scrollable: true }, config );
8179
8180 // Parent constructor
8181 OO.ui.StackLayout.super.call( this, config );
8182
8183 // Mixin constructors
8184 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8185
8186 // Properties
8187 this.currentItem = null;
8188 this.continuous = !!config.continuous;
8189
8190 // Initialization
8191 this.$element.addClass( 'oo-ui-stackLayout' );
8192 if ( this.continuous ) {
8193 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
8194 }
8195 if ( $.isArray( config.items ) ) {
8196 this.addItems( config.items );
8197 }
8198 };
8199
8200 /* Setup */
8201
8202 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
8203 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
8204
8205 /* Events */
8206
8207 /**
8208 * @event set
8209 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8210 */
8211
8212 /* Methods */
8213
8214 /**
8215 * Get the current item.
8216 *
8217 * @return {OO.ui.Layout|null}
8218 */
8219 OO.ui.StackLayout.prototype.getCurrentItem = function () {
8220 return this.currentItem;
8221 };
8222
8223 /**
8224 * Unset the current item.
8225 *
8226 * @private
8227 * @param {OO.ui.StackLayout} layout
8228 * @fires set
8229 */
8230 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
8231 var prevItem = this.currentItem;
8232 if ( prevItem === null ) {
8233 return;
8234 }
8235
8236 this.currentItem = null;
8237 this.emit( 'set', null );
8238 };
8239
8240 /**
8241 * Add items.
8242 *
8243 * Adding an existing item (by value) will move it.
8244 *
8245 * @param {OO.ui.Layout[]} items Items to add
8246 * @param {number} [index] Index to insert items after
8247 * @chainable
8248 */
8249 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
8250 // Mixin method
8251 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
8252
8253 if ( !this.currentItem && items.length ) {
8254 this.setItem( items[0] );
8255 }
8256
8257 return this;
8258 };
8259
8260 /**
8261 * Remove items.
8262 *
8263 * Items will be detached, not removed, so they can be used later.
8264 *
8265 * @param {OO.ui.Layout[]} items Items to remove
8266 * @chainable
8267 * @fires set
8268 */
8269 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
8270 // Mixin method
8271 OO.ui.GroupElement.prototype.removeItems.call( this, items );
8272
8273 if ( $.inArray( this.currentItem, items ) !== -1 ) {
8274 if ( this.items.length ) {
8275 this.setItem( this.items[0] );
8276 } else {
8277 this.unsetCurrentItem();
8278 }
8279 }
8280
8281 return this;
8282 };
8283
8284 /**
8285 * Clear all items.
8286 *
8287 * Items will be detached, not removed, so they can be used later.
8288 *
8289 * @chainable
8290 * @fires set
8291 */
8292 OO.ui.StackLayout.prototype.clearItems = function () {
8293 this.unsetCurrentItem();
8294 OO.ui.GroupElement.prototype.clearItems.call( this );
8295
8296 return this;
8297 };
8298
8299 /**
8300 * Show item.
8301 *
8302 * Any currently shown item will be hidden.
8303 *
8304 * FIXME: If the passed item to show has not been added in the items list, then
8305 * this method drops it and unsets the current item.
8306 *
8307 * @param {OO.ui.Layout} item Item to show
8308 * @chainable
8309 * @fires set
8310 */
8311 OO.ui.StackLayout.prototype.setItem = function ( item ) {
8312 var i, len;
8313
8314 if ( item !== this.currentItem ) {
8315 if ( !this.continuous ) {
8316 for ( i = 0, len = this.items.length; i < len; i++ ) {
8317 this.items[i].$element.css( 'display', '' );
8318 }
8319 }
8320 if ( $.inArray( item, this.items ) !== -1 ) {
8321 if ( !this.continuous ) {
8322 item.$element.css( 'display', 'block' );
8323 }
8324 this.currentItem = item;
8325 this.emit( 'set', item );
8326 } else {
8327 this.unsetCurrentItem();
8328 }
8329 }
8330
8331 return this;
8332 };
8333
8334 /**
8335 * Horizontal bar layout of tools as icon buttons.
8336 *
8337 * @class
8338 * @extends OO.ui.ToolGroup
8339 *
8340 * @constructor
8341 * @param {OO.ui.Toolbar} toolbar
8342 * @param {Object} [config] Configuration options
8343 */
8344 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
8345 // Parent constructor
8346 OO.ui.BarToolGroup.super.call( this, toolbar, config );
8347
8348 // Initialization
8349 this.$element.addClass( 'oo-ui-barToolGroup' );
8350 };
8351
8352 /* Setup */
8353
8354 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
8355
8356 /* Static Properties */
8357
8358 OO.ui.BarToolGroup.static.titleTooltips = true;
8359
8360 OO.ui.BarToolGroup.static.accelTooltips = true;
8361
8362 OO.ui.BarToolGroup.static.name = 'bar';
8363
8364 /**
8365 * Popup list of tools with an icon and optional label.
8366 *
8367 * @abstract
8368 * @class
8369 * @extends OO.ui.ToolGroup
8370 * @mixins OO.ui.IconElement
8371 * @mixins OO.ui.IndicatorElement
8372 * @mixins OO.ui.LabelElement
8373 * @mixins OO.ui.TitledElement
8374 * @mixins OO.ui.ClippableElement
8375 *
8376 * @constructor
8377 * @param {OO.ui.Toolbar} toolbar
8378 * @param {Object} [config] Configuration options
8379 * @cfg {string} [header] Text to display at the top of the pop-up
8380 */
8381 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
8382 // Configuration initialization
8383 config = config || {};
8384
8385 // Parent constructor
8386 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
8387
8388 // Mixin constructors
8389 OO.ui.IconElement.call( this, config );
8390 OO.ui.IndicatorElement.call( this, config );
8391 OO.ui.LabelElement.call( this, config );
8392 OO.ui.TitledElement.call( this, config );
8393 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
8394
8395 // Properties
8396 this.active = false;
8397 this.dragging = false;
8398 this.onBlurHandler = this.onBlur.bind( this );
8399 this.$handle = this.$( '<span>' );
8400
8401 // Events
8402 this.$handle.on( {
8403 'mousedown touchstart': this.onHandlePointerDown.bind( this ),
8404 'mouseup touchend': this.onHandlePointerUp.bind( this )
8405 } );
8406
8407 // Initialization
8408 this.$handle
8409 .addClass( 'oo-ui-popupToolGroup-handle' )
8410 .append( this.$icon, this.$label, this.$indicator );
8411 // If the pop-up should have a header, add it to the top of the toolGroup.
8412 // Note: If this feature is useful for other widgets, we could abstract it into an
8413 // OO.ui.HeaderedElement mixin constructor.
8414 if ( config.header !== undefined ) {
8415 this.$group
8416 .prepend( this.$( '<span>' )
8417 .addClass( 'oo-ui-popupToolGroup-header' )
8418 .text( config.header )
8419 );
8420 }
8421 this.$element
8422 .addClass( 'oo-ui-popupToolGroup' )
8423 .prepend( this.$handle );
8424 };
8425
8426 /* Setup */
8427
8428 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
8429 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
8430 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
8431 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
8432 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
8433 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
8434
8435 /* Static Properties */
8436
8437 /* Methods */
8438
8439 /**
8440 * @inheritdoc
8441 */
8442 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
8443 // Parent method
8444 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
8445
8446 if ( this.isDisabled() && this.isElementAttached() ) {
8447 this.setActive( false );
8448 }
8449 };
8450
8451 /**
8452 * Handle focus being lost.
8453 *
8454 * The event is actually generated from a mouseup, so it is not a normal blur event object.
8455 *
8456 * @param {jQuery.Event} e Mouse up event
8457 */
8458 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
8459 // Only deactivate when clicking outside the dropdown element
8460 if ( this.$( e.target ).closest( '.oo-ui-popupToolGroup' )[0] !== this.$element[0] ) {
8461 this.setActive( false );
8462 }
8463 };
8464
8465 /**
8466 * @inheritdoc
8467 */
8468 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
8469 // e.which is 0 for touch events, 1 for left mouse button
8470 // Only close toolgroup when a tool was actually selected
8471 // FIXME: this duplicates logic from the parent class
8472 if ( !this.isDisabled() && e.which <= 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
8473 this.setActive( false );
8474 }
8475 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
8476 };
8477
8478 /**
8479 * Handle mouse up events.
8480 *
8481 * @param {jQuery.Event} e Mouse up event
8482 */
8483 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
8484 return false;
8485 };
8486
8487 /**
8488 * Handle mouse down events.
8489 *
8490 * @param {jQuery.Event} e Mouse down event
8491 */
8492 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
8493 // e.which is 0 for touch events, 1 for left mouse button
8494 if ( !this.isDisabled() && e.which <= 1 ) {
8495 this.setActive( !this.active );
8496 }
8497 return false;
8498 };
8499
8500 /**
8501 * Switch into active mode.
8502 *
8503 * When active, mouseup events anywhere in the document will trigger deactivation.
8504 */
8505 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
8506 value = !!value;
8507 if ( this.active !== value ) {
8508 this.active = value;
8509 if ( value ) {
8510 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
8511
8512 // Try anchoring the popup to the left first
8513 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
8514 this.toggleClipping( true );
8515 if ( this.isClippedHorizontally() ) {
8516 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
8517 this.toggleClipping( false );
8518 this.$element
8519 .removeClass( 'oo-ui-popupToolGroup-left' )
8520 .addClass( 'oo-ui-popupToolGroup-right' );
8521 this.toggleClipping( true );
8522 }
8523 } else {
8524 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
8525 this.$element.removeClass(
8526 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
8527 );
8528 this.toggleClipping( false );
8529 }
8530 }
8531 };
8532
8533 /**
8534 * Drop down list layout of tools as labeled icon buttons.
8535 *
8536 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
8537 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
8538 * may want to use the 'promote' and 'demote' configuration options to achieve this.
8539 *
8540 * @class
8541 * @extends OO.ui.PopupToolGroup
8542 *
8543 * @constructor
8544 * @param {OO.ui.Toolbar} toolbar
8545 * @param {Object} [config] Configuration options
8546 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
8547 * shown.
8548 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
8549 * allowed to be collapsed.
8550 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
8551 */
8552 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
8553 // Configuration initialization
8554 config = config || {};
8555
8556 // Properties (must be set before parent constructor, which calls #populate)
8557 this.allowCollapse = config.allowCollapse;
8558 this.forceExpand = config.forceExpand;
8559 this.expanded = config.expanded !== undefined ? config.expanded : false;
8560 this.collapsibleTools = [];
8561
8562 // Parent constructor
8563 OO.ui.ListToolGroup.super.call( this, toolbar, config );
8564
8565 // Initialization
8566 this.$element.addClass( 'oo-ui-listToolGroup' );
8567 };
8568
8569 /* Setup */
8570
8571 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
8572
8573 /* Static Properties */
8574
8575 OO.ui.ListToolGroup.static.accelTooltips = true;
8576
8577 OO.ui.ListToolGroup.static.name = 'list';
8578
8579 /* Methods */
8580
8581 /**
8582 * @inheritdoc
8583 */
8584 OO.ui.ListToolGroup.prototype.populate = function () {
8585 var i, len, allowCollapse = [];
8586
8587 OO.ui.ListToolGroup.super.prototype.populate.call( this );
8588
8589 // Update the list of collapsible tools
8590 if ( this.allowCollapse !== undefined ) {
8591 allowCollapse = this.allowCollapse;
8592 } else if ( this.forceExpand !== undefined ) {
8593 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
8594 }
8595
8596 this.collapsibleTools = [];
8597 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
8598 if ( this.tools[ allowCollapse[i] ] !== undefined ) {
8599 this.collapsibleTools.push( this.tools[ allowCollapse[i] ] );
8600 }
8601 }
8602
8603 // Keep at the end, even when tools are added
8604 this.$group.append( this.getExpandCollapseTool().$element );
8605
8606 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
8607
8608 // Calling jQuery's .hide() and then .show() on a detached element caches the default value of its
8609 // 'display' attribute and restores it, and the tool uses a <span> and can be hidden and re-shown.
8610 // Is this a jQuery bug? http://jsfiddle.net/gtj4hu3h/
8611 if ( this.getExpandCollapseTool().$element.css( 'display' ) === 'inline' ) {
8612 this.getExpandCollapseTool().$element.css( 'display', 'block' );
8613 }
8614
8615 this.updateCollapsibleState();
8616 };
8617
8618 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
8619 if ( this.expandCollapseTool === undefined ) {
8620 var ExpandCollapseTool = function () {
8621 ExpandCollapseTool.super.apply( this, arguments );
8622 };
8623
8624 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
8625
8626 ExpandCollapseTool.prototype.onSelect = function () {
8627 this.toolGroup.expanded = !this.toolGroup.expanded;
8628 this.toolGroup.updateCollapsibleState();
8629 this.setActive( false );
8630 };
8631 ExpandCollapseTool.prototype.onUpdateState = function () {
8632 // Do nothing. Tool interface requires an implementation of this function.
8633 };
8634
8635 ExpandCollapseTool.static.name = 'more-fewer';
8636
8637 this.expandCollapseTool = new ExpandCollapseTool( this );
8638 }
8639 return this.expandCollapseTool;
8640 };
8641
8642 /**
8643 * @inheritdoc
8644 */
8645 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
8646 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
8647
8648 // Do not close the popup when the user wants to show more/fewer tools
8649 if ( this.$( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
8650 // Prevent the popup list from being hidden
8651 this.setActive( true );
8652 }
8653
8654 return ret;
8655 };
8656
8657 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
8658 var i, len;
8659
8660 this.getExpandCollapseTool()
8661 .setIcon( this.expanded ? 'collapse' : 'expand' )
8662 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
8663
8664 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
8665 this.collapsibleTools[i].toggle( this.expanded );
8666 }
8667 };
8668
8669 /**
8670 * Drop down menu layout of tools as selectable menu items.
8671 *
8672 * @class
8673 * @extends OO.ui.PopupToolGroup
8674 *
8675 * @constructor
8676 * @param {OO.ui.Toolbar} toolbar
8677 * @param {Object} [config] Configuration options
8678 */
8679 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
8680 // Configuration initialization
8681 config = config || {};
8682
8683 // Parent constructor
8684 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
8685
8686 // Events
8687 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
8688
8689 // Initialization
8690 this.$element.addClass( 'oo-ui-menuToolGroup' );
8691 };
8692
8693 /* Setup */
8694
8695 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
8696
8697 /* Static Properties */
8698
8699 OO.ui.MenuToolGroup.static.accelTooltips = true;
8700
8701 OO.ui.MenuToolGroup.static.name = 'menu';
8702
8703 /* Methods */
8704
8705 /**
8706 * Handle the toolbar state being updated.
8707 *
8708 * When the state changes, the title of each active item in the menu will be joined together and
8709 * used as a label for the group. The label will be empty if none of the items are active.
8710 */
8711 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
8712 var name,
8713 labelTexts = [];
8714
8715 for ( name in this.tools ) {
8716 if ( this.tools[name].isActive() ) {
8717 labelTexts.push( this.tools[name].getTitle() );
8718 }
8719 }
8720
8721 this.setLabel( labelTexts.join( ', ' ) || ' ' );
8722 };
8723
8724 /**
8725 * Tool that shows a popup when selected.
8726 *
8727 * @abstract
8728 * @class
8729 * @extends OO.ui.Tool
8730 * @mixins OO.ui.PopupElement
8731 *
8732 * @constructor
8733 * @param {OO.ui.Toolbar} toolbar
8734 * @param {Object} [config] Configuration options
8735 */
8736 OO.ui.PopupTool = function OoUiPopupTool( toolbar, config ) {
8737 // Parent constructor
8738 OO.ui.PopupTool.super.call( this, toolbar, config );
8739
8740 // Mixin constructors
8741 OO.ui.PopupElement.call( this, config );
8742
8743 // Initialization
8744 this.$element
8745 .addClass( 'oo-ui-popupTool' )
8746 .append( this.popup.$element );
8747 };
8748
8749 /* Setup */
8750
8751 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
8752 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
8753
8754 /* Methods */
8755
8756 /**
8757 * Handle the tool being selected.
8758 *
8759 * @inheritdoc
8760 */
8761 OO.ui.PopupTool.prototype.onSelect = function () {
8762 if ( !this.isDisabled() ) {
8763 this.popup.toggle();
8764 }
8765 this.setActive( false );
8766 return false;
8767 };
8768
8769 /**
8770 * Handle the toolbar state being updated.
8771 *
8772 * @inheritdoc
8773 */
8774 OO.ui.PopupTool.prototype.onUpdateState = function () {
8775 this.setActive( false );
8776 };
8777
8778 /**
8779 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
8780 *
8781 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
8782 *
8783 * @abstract
8784 * @class
8785 * @extends OO.ui.GroupElement
8786 *
8787 * @constructor
8788 * @param {Object} [config] Configuration options
8789 */
8790 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
8791 // Parent constructor
8792 OO.ui.GroupWidget.super.call( this, config );
8793 };
8794
8795 /* Setup */
8796
8797 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
8798
8799 /* Methods */
8800
8801 /**
8802 * Set the disabled state of the widget.
8803 *
8804 * This will also update the disabled state of child widgets.
8805 *
8806 * @param {boolean} disabled Disable widget
8807 * @chainable
8808 */
8809 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
8810 var i, len;
8811
8812 // Parent method
8813 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
8814 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
8815
8816 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
8817 if ( this.items ) {
8818 for ( i = 0, len = this.items.length; i < len; i++ ) {
8819 this.items[i].updateDisabled();
8820 }
8821 }
8822
8823 return this;
8824 };
8825
8826 /**
8827 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
8828 *
8829 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
8830 * allows bidirectional communication.
8831 *
8832 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
8833 *
8834 * @abstract
8835 * @class
8836 *
8837 * @constructor
8838 */
8839 OO.ui.ItemWidget = function OoUiItemWidget() {
8840 //
8841 };
8842
8843 /* Methods */
8844
8845 /**
8846 * Check if widget is disabled.
8847 *
8848 * Checks parent if present, making disabled state inheritable.
8849 *
8850 * @return {boolean} Widget is disabled
8851 */
8852 OO.ui.ItemWidget.prototype.isDisabled = function () {
8853 return this.disabled ||
8854 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
8855 };
8856
8857 /**
8858 * Set group element is in.
8859 *
8860 * @param {OO.ui.GroupElement|null} group Group element, null if none
8861 * @chainable
8862 */
8863 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
8864 // Parent method
8865 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
8866 OO.ui.Element.prototype.setElementGroup.call( this, group );
8867
8868 // Initialize item disabled states
8869 this.updateDisabled();
8870
8871 return this;
8872 };
8873
8874 /**
8875 * Mixin that adds a menu showing suggested values for a text input.
8876 *
8877 * Subclasses must handle `select` and `choose` events on #lookupMenu to make use of selections.
8878 *
8879 * Subclasses that set the value of #lookupInput from their `choose` or `select` handler should
8880 * be aware that this will cause new suggestions to be looked up for the new value. If this is
8881 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
8882 *
8883 * @class
8884 * @abstract
8885 * @deprecated Use LookupElement instead.
8886 *
8887 * @constructor
8888 * @param {OO.ui.TextInputWidget} input Input widget
8889 * @param {Object} [config] Configuration options
8890 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
8891 * @cfg {jQuery} [$container=input.$element] Element to render menu under
8892 */
8893 OO.ui.LookupInputWidget = function OoUiLookupInputWidget( input, config ) {
8894 // Configuration initialization
8895 config = config || {};
8896
8897 // Properties
8898 this.lookupInput = input;
8899 this.$overlay = config.$overlay || this.$element;
8900 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
8901 $: OO.ui.Element.static.getJQuery( this.$overlay ),
8902 input: this.lookupInput,
8903 $container: config.$container
8904 } );
8905 this.lookupCache = {};
8906 this.lookupQuery = null;
8907 this.lookupRequest = null;
8908 this.lookupsDisabled = false;
8909 this.lookupInputFocused = false;
8910
8911 // Events
8912 this.lookupInput.$input.on( {
8913 focus: this.onLookupInputFocus.bind( this ),
8914 blur: this.onLookupInputBlur.bind( this ),
8915 mousedown: this.onLookupInputMouseDown.bind( this )
8916 } );
8917 this.lookupInput.connect( this, { change: 'onLookupInputChange' } );
8918 this.lookupMenu.connect( this, { toggle: 'onLookupMenuToggle' } );
8919
8920 // Initialization
8921 this.$element.addClass( 'oo-ui-lookupWidget' );
8922 this.lookupMenu.$element.addClass( 'oo-ui-lookupWidget-menu' );
8923 this.$overlay.append( this.lookupMenu.$element );
8924 };
8925
8926 /* Methods */
8927
8928 /**
8929 * Handle input focus event.
8930 *
8931 * @param {jQuery.Event} e Input focus event
8932 */
8933 OO.ui.LookupInputWidget.prototype.onLookupInputFocus = function () {
8934 this.lookupInputFocused = true;
8935 this.populateLookupMenu();
8936 };
8937
8938 /**
8939 * Handle input blur event.
8940 *
8941 * @param {jQuery.Event} e Input blur event
8942 */
8943 OO.ui.LookupInputWidget.prototype.onLookupInputBlur = function () {
8944 this.closeLookupMenu();
8945 this.lookupInputFocused = false;
8946 };
8947
8948 /**
8949 * Handle input mouse down event.
8950 *
8951 * @param {jQuery.Event} e Input mouse down event
8952 */
8953 OO.ui.LookupInputWidget.prototype.onLookupInputMouseDown = function () {
8954 // Only open the menu if the input was already focused.
8955 // This way we allow the user to open the menu again after closing it with Esc
8956 // by clicking in the input. Opening (and populating) the menu when initially
8957 // clicking into the input is handled by the focus handler.
8958 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
8959 this.populateLookupMenu();
8960 }
8961 };
8962
8963 /**
8964 * Handle input change event.
8965 *
8966 * @param {string} value New input value
8967 */
8968 OO.ui.LookupInputWidget.prototype.onLookupInputChange = function () {
8969 if ( this.lookupInputFocused ) {
8970 this.populateLookupMenu();
8971 }
8972 };
8973
8974 /**
8975 * Handle the lookup menu being shown/hidden.
8976 * @param {boolean} visible Whether the lookup menu is now visible.
8977 */
8978 OO.ui.LookupInputWidget.prototype.onLookupMenuToggle = function ( visible ) {
8979 if ( !visible ) {
8980 // When the menu is hidden, abort any active request and clear the menu.
8981 // This has to be done here in addition to closeLookupMenu(), because
8982 // MenuSelectWidget will close itself when the user presses Esc.
8983 this.abortLookupRequest();
8984 this.lookupMenu.clearItems();
8985 }
8986 };
8987
8988 /**
8989 * Get lookup menu.
8990 *
8991 * @return {OO.ui.TextInputMenuSelectWidget}
8992 */
8993 OO.ui.LookupInputWidget.prototype.getLookupMenu = function () {
8994 return this.lookupMenu;
8995 };
8996
8997 /**
8998 * Disable or re-enable lookups.
8999 *
9000 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
9001 *
9002 * @param {boolean} disabled Disable lookups
9003 */
9004 OO.ui.LookupInputWidget.prototype.setLookupsDisabled = function ( disabled ) {
9005 this.lookupsDisabled = !!disabled;
9006 };
9007
9008 /**
9009 * Open the menu. If there are no entries in the menu, this does nothing.
9010 *
9011 * @chainable
9012 */
9013 OO.ui.LookupInputWidget.prototype.openLookupMenu = function () {
9014 if ( !this.lookupMenu.isEmpty() ) {
9015 this.lookupMenu.toggle( true );
9016 }
9017 return this;
9018 };
9019
9020 /**
9021 * Close the menu, empty it, and abort any pending request.
9022 *
9023 * @chainable
9024 */
9025 OO.ui.LookupInputWidget.prototype.closeLookupMenu = function () {
9026 this.lookupMenu.toggle( false );
9027 this.abortLookupRequest();
9028 this.lookupMenu.clearItems();
9029 return this;
9030 };
9031
9032 /**
9033 * Request menu items based on the input's current value, and when they arrive,
9034 * populate the menu with these items and show the menu.
9035 *
9036 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
9037 *
9038 * @chainable
9039 */
9040 OO.ui.LookupInputWidget.prototype.populateLookupMenu = function () {
9041 var widget = this,
9042 value = this.lookupInput.getValue();
9043
9044 if ( this.lookupsDisabled ) {
9045 return;
9046 }
9047
9048 // If the input is empty, clear the menu
9049 if ( value === '' ) {
9050 this.closeLookupMenu();
9051 // Skip population if there is already a request pending for the current value
9052 } else if ( value !== this.lookupQuery ) {
9053 this.getLookupMenuItems()
9054 .done( function ( items ) {
9055 widget.lookupMenu.clearItems();
9056 if ( items.length ) {
9057 widget.lookupMenu
9058 .addItems( items )
9059 .toggle( true );
9060 widget.initializeLookupMenuSelection();
9061 } else {
9062 widget.lookupMenu.toggle( false );
9063 }
9064 } )
9065 .fail( function () {
9066 widget.lookupMenu.clearItems();
9067 } );
9068 }
9069
9070 return this;
9071 };
9072
9073 /**
9074 * Select and highlight the first selectable item in the menu.
9075 *
9076 * @chainable
9077 */
9078 OO.ui.LookupInputWidget.prototype.initializeLookupMenuSelection = function () {
9079 if ( !this.lookupMenu.getSelectedItem() ) {
9080 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
9081 }
9082 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
9083 };
9084
9085 /**
9086 * Get lookup menu items for the current query.
9087 *
9088 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument
9089 * of the done event. If the request was aborted to make way for a subsequent request,
9090 * this promise will not be rejected: it will remain pending forever.
9091 */
9092 OO.ui.LookupInputWidget.prototype.getLookupMenuItems = function () {
9093 var widget = this,
9094 value = this.lookupInput.getValue(),
9095 deferred = $.Deferred(),
9096 ourRequest;
9097
9098 this.abortLookupRequest();
9099 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
9100 deferred.resolve( this.getLookupMenuItemsFromData( this.lookupCache[value] ) );
9101 } else {
9102 this.lookupInput.pushPending();
9103 this.lookupQuery = value;
9104 ourRequest = this.lookupRequest = this.getLookupRequest();
9105 ourRequest
9106 .always( function () {
9107 // We need to pop pending even if this is an old request, otherwise
9108 // the widget will remain pending forever.
9109 // TODO: this assumes that an aborted request will fail or succeed soon after
9110 // being aborted, or at least eventually. It would be nice if we could popPending()
9111 // at abort time, but only if we knew that we hadn't already called popPending()
9112 // for that request.
9113 widget.lookupInput.popPending();
9114 } )
9115 .done( function ( data ) {
9116 // If this is an old request (and aborting it somehow caused it to still succeed),
9117 // ignore its success completely
9118 if ( ourRequest === widget.lookupRequest ) {
9119 widget.lookupQuery = null;
9120 widget.lookupRequest = null;
9121 widget.lookupCache[value] = widget.getLookupCacheItemFromData( data );
9122 deferred.resolve( widget.getLookupMenuItemsFromData( widget.lookupCache[value] ) );
9123 }
9124 } )
9125 .fail( function () {
9126 // If this is an old request (or a request failing because it's being aborted),
9127 // ignore its failure completely
9128 if ( ourRequest === widget.lookupRequest ) {
9129 widget.lookupQuery = null;
9130 widget.lookupRequest = null;
9131 deferred.reject();
9132 }
9133 } );
9134 }
9135 return deferred.promise();
9136 };
9137
9138 /**
9139 * Abort the currently pending lookup request, if any.
9140 */
9141 OO.ui.LookupInputWidget.prototype.abortLookupRequest = function () {
9142 var oldRequest = this.lookupRequest;
9143 if ( oldRequest ) {
9144 // First unset this.lookupRequest to the fail handler will notice
9145 // that the request is no longer current
9146 this.lookupRequest = null;
9147 this.lookupQuery = null;
9148 oldRequest.abort();
9149 }
9150 };
9151
9152 /**
9153 * Get a new request object of the current lookup query value.
9154 *
9155 * @abstract
9156 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
9157 */
9158 OO.ui.LookupInputWidget.prototype.getLookupRequest = function () {
9159 // Stub, implemented in subclass
9160 return null;
9161 };
9162
9163 /**
9164 * Get a list of menu item widgets from the data stored by the lookup request's done handler.
9165 *
9166 * @abstract
9167 * @param {Mixed} data Cached result data, usually an array
9168 * @return {OO.ui.MenuOptionWidget[]} Menu items
9169 */
9170 OO.ui.LookupInputWidget.prototype.getLookupMenuItemsFromData = function () {
9171 // Stub, implemented in subclass
9172 return [];
9173 };
9174
9175 /**
9176 * Get lookup cache item from server response data.
9177 *
9178 * @abstract
9179 * @param {Mixed} data Response from server
9180 * @return {Mixed} Cached result data
9181 */
9182 OO.ui.LookupInputWidget.prototype.getLookupCacheItemFromData = function () {
9183 // Stub, implemented in subclass
9184 return [];
9185 };
9186
9187 /**
9188 * Set of controls for an OO.ui.OutlineSelectWidget.
9189 *
9190 * Controls include moving items up and down, removing items, and adding different kinds of items.
9191 *
9192 * @class
9193 * @extends OO.ui.Widget
9194 * @mixins OO.ui.GroupElement
9195 * @mixins OO.ui.IconElement
9196 *
9197 * @constructor
9198 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9199 * @param {Object} [config] Configuration options
9200 */
9201 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9202 // Configuration initialization
9203 config = $.extend( { icon: 'add' }, config );
9204
9205 // Parent constructor
9206 OO.ui.OutlineControlsWidget.super.call( this, config );
9207
9208 // Mixin constructors
9209 OO.ui.GroupElement.call( this, config );
9210 OO.ui.IconElement.call( this, config );
9211
9212 // Properties
9213 this.outline = outline;
9214 this.$movers = this.$( '<div>' );
9215 this.upButton = new OO.ui.ButtonWidget( {
9216 $: this.$,
9217 framed: false,
9218 icon: 'collapse',
9219 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9220 } );
9221 this.downButton = new OO.ui.ButtonWidget( {
9222 $: this.$,
9223 framed: false,
9224 icon: 'expand',
9225 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9226 } );
9227 this.removeButton = new OO.ui.ButtonWidget( {
9228 $: this.$,
9229 framed: false,
9230 icon: 'remove',
9231 title: OO.ui.msg( 'ooui-outline-control-remove' )
9232 } );
9233
9234 // Events
9235 outline.connect( this, {
9236 select: 'onOutlineChange',
9237 add: 'onOutlineChange',
9238 remove: 'onOutlineChange'
9239 } );
9240 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9241 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9242 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9243
9244 // Initialization
9245 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9246 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9247 this.$movers
9248 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9249 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9250 this.$element.append( this.$icon, this.$group, this.$movers );
9251 };
9252
9253 /* Setup */
9254
9255 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9256 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9257 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9258
9259 /* Events */
9260
9261 /**
9262 * @event move
9263 * @param {number} places Number of places to move
9264 */
9265
9266 /**
9267 * @event remove
9268 */
9269
9270 /* Methods */
9271
9272 /**
9273 * Handle outline change events.
9274 */
9275 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9276 var i, len, firstMovable, lastMovable,
9277 items = this.outline.getItems(),
9278 selectedItem = this.outline.getSelectedItem(),
9279 movable = selectedItem && selectedItem.isMovable(),
9280 removable = selectedItem && selectedItem.isRemovable();
9281
9282 if ( movable ) {
9283 i = -1;
9284 len = items.length;
9285 while ( ++i < len ) {
9286 if ( items[i].isMovable() ) {
9287 firstMovable = items[i];
9288 break;
9289 }
9290 }
9291 i = len;
9292 while ( i-- ) {
9293 if ( items[i].isMovable() ) {
9294 lastMovable = items[i];
9295 break;
9296 }
9297 }
9298 }
9299 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9300 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9301 this.removeButton.setDisabled( !removable );
9302 };
9303
9304 /**
9305 * Mixin for widgets with a boolean on/off state.
9306 *
9307 * @abstract
9308 * @class
9309 *
9310 * @constructor
9311 * @param {Object} [config] Configuration options
9312 * @cfg {boolean} [value=false] Initial value
9313 */
9314 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9315 // Configuration initialization
9316 config = config || {};
9317
9318 // Properties
9319 this.value = null;
9320
9321 // Initialization
9322 this.$element.addClass( 'oo-ui-toggleWidget' );
9323 this.setValue( !!config.value );
9324 };
9325
9326 /* Events */
9327
9328 /**
9329 * @event change
9330 * @param {boolean} value Changed value
9331 */
9332
9333 /* Methods */
9334
9335 /**
9336 * Get the value of the toggle.
9337 *
9338 * @return {boolean}
9339 */
9340 OO.ui.ToggleWidget.prototype.getValue = function () {
9341 return this.value;
9342 };
9343
9344 /**
9345 * Set the value of the toggle.
9346 *
9347 * @param {boolean} value New value
9348 * @fires change
9349 * @chainable
9350 */
9351 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
9352 value = !!value;
9353 if ( this.value !== value ) {
9354 this.value = value;
9355 this.emit( 'change', value );
9356 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
9357 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
9358 }
9359 return this;
9360 };
9361
9362 /**
9363 * Group widget for multiple related buttons.
9364 *
9365 * Use together with OO.ui.ButtonWidget.
9366 *
9367 * @class
9368 * @extends OO.ui.Widget
9369 * @mixins OO.ui.GroupElement
9370 *
9371 * @constructor
9372 * @param {Object} [config] Configuration options
9373 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9374 */
9375 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
9376 // Configuration initialization
9377 config = config || {};
9378
9379 // Parent constructor
9380 OO.ui.ButtonGroupWidget.super.call( this, config );
9381
9382 // Mixin constructors
9383 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9384
9385 // Initialization
9386 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
9387 if ( $.isArray( config.items ) ) {
9388 this.addItems( config.items );
9389 }
9390 };
9391
9392 /* Setup */
9393
9394 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
9395 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
9396
9397 /**
9398 * Generic widget for buttons.
9399 *
9400 * @class
9401 * @extends OO.ui.Widget
9402 * @mixins OO.ui.ButtonElement
9403 * @mixins OO.ui.IconElement
9404 * @mixins OO.ui.IndicatorElement
9405 * @mixins OO.ui.LabelElement
9406 * @mixins OO.ui.TitledElement
9407 * @mixins OO.ui.FlaggedElement
9408 *
9409 * @constructor
9410 * @param {Object} [config] Configuration options
9411 * @cfg {string} [href] Hyperlink to visit when clicked
9412 * @cfg {string} [target] Target to open hyperlink in
9413 */
9414 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
9415 // Configuration initialization
9416 config = config || {};
9417
9418 // Parent constructor
9419 OO.ui.ButtonWidget.super.call( this, config );
9420
9421 // Mixin constructors
9422 OO.ui.ButtonElement.call( this, config );
9423 OO.ui.IconElement.call( this, config );
9424 OO.ui.IndicatorElement.call( this, config );
9425 OO.ui.LabelElement.call( this, config );
9426 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
9427 OO.ui.FlaggedElement.call( this, config );
9428
9429 // Properties
9430 this.href = null;
9431 this.target = null;
9432 this.isHyperlink = false;
9433
9434 // Events
9435 this.$button.on( {
9436 click: this.onClick.bind( this ),
9437 keypress: this.onKeyPress.bind( this )
9438 } );
9439
9440 // Initialization
9441 this.$button.append( this.$icon, this.$label, this.$indicator );
9442 this.$element
9443 .addClass( 'oo-ui-buttonWidget' )
9444 .append( this.$button );
9445 this.setHref( config.href );
9446 this.setTarget( config.target );
9447 };
9448
9449 /* Setup */
9450
9451 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
9452 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
9453 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
9454 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
9455 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
9456 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
9457 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
9458
9459 /* Events */
9460
9461 /**
9462 * @event click
9463 */
9464
9465 /* Methods */
9466
9467 /**
9468 * Handles mouse click events.
9469 *
9470 * @param {jQuery.Event} e Mouse click event
9471 * @fires click
9472 */
9473 OO.ui.ButtonWidget.prototype.onClick = function () {
9474 if ( !this.isDisabled() ) {
9475 this.emit( 'click' );
9476 if ( this.isHyperlink ) {
9477 return true;
9478 }
9479 }
9480 return false;
9481 };
9482
9483 /**
9484 * Handles keypress events.
9485 *
9486 * @param {jQuery.Event} e Keypress event
9487 * @fires click
9488 */
9489 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
9490 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
9491 this.emit( 'click' );
9492 if ( this.isHyperlink ) {
9493 return true;
9494 }
9495 }
9496 return false;
9497 };
9498
9499 /**
9500 * Get hyperlink location.
9501 *
9502 * @return {string} Hyperlink location
9503 */
9504 OO.ui.ButtonWidget.prototype.getHref = function () {
9505 return this.href;
9506 };
9507
9508 /**
9509 * Get hyperlink target.
9510 *
9511 * @return {string} Hyperlink target
9512 */
9513 OO.ui.ButtonWidget.prototype.getTarget = function () {
9514 return this.target;
9515 };
9516
9517 /**
9518 * Set hyperlink location.
9519 *
9520 * @param {string|null} href Hyperlink location, null to remove
9521 */
9522 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
9523 href = typeof href === 'string' ? href : null;
9524
9525 if ( href !== this.href ) {
9526 this.href = href;
9527 if ( href !== null ) {
9528 this.$button.attr( 'href', href );
9529 this.isHyperlink = true;
9530 } else {
9531 this.$button.removeAttr( 'href' );
9532 this.isHyperlink = false;
9533 }
9534 }
9535
9536 return this;
9537 };
9538
9539 /**
9540 * Set hyperlink target.
9541 *
9542 * @param {string|null} target Hyperlink target, null to remove
9543 */
9544 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
9545 target = typeof target === 'string' ? target : null;
9546
9547 if ( target !== this.target ) {
9548 this.target = target;
9549 if ( target !== null ) {
9550 this.$button.attr( 'target', target );
9551 } else {
9552 this.$button.removeAttr( 'target' );
9553 }
9554 }
9555
9556 return this;
9557 };
9558
9559 /**
9560 * Button widget that executes an action and is managed by an OO.ui.ActionSet.
9561 *
9562 * @class
9563 * @extends OO.ui.ButtonWidget
9564 * @mixins OO.ui.PendingElement
9565 *
9566 * @constructor
9567 * @param {Object} [config] Configuration options
9568 * @cfg {string} [action] Symbolic action name
9569 * @cfg {string[]} [modes] Symbolic mode names
9570 * @cfg {boolean} [framed=false] Render button with a frame
9571 */
9572 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
9573 // Configuration initialization
9574 config = $.extend( { framed: false }, config );
9575
9576 // Parent constructor
9577 OO.ui.ActionWidget.super.call( this, config );
9578
9579 // Mixin constructors
9580 OO.ui.PendingElement.call( this, config );
9581
9582 // Properties
9583 this.action = config.action || '';
9584 this.modes = config.modes || [];
9585 this.width = 0;
9586 this.height = 0;
9587
9588 // Initialization
9589 this.$element.addClass( 'oo-ui-actionWidget' );
9590 };
9591
9592 /* Setup */
9593
9594 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
9595 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
9596
9597 /* Events */
9598
9599 /**
9600 * @event resize
9601 */
9602
9603 /* Methods */
9604
9605 /**
9606 * Check if action is available in a certain mode.
9607 *
9608 * @param {string} mode Name of mode
9609 * @return {boolean} Has mode
9610 */
9611 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
9612 return this.modes.indexOf( mode ) !== -1;
9613 };
9614
9615 /**
9616 * Get symbolic action name.
9617 *
9618 * @return {string}
9619 */
9620 OO.ui.ActionWidget.prototype.getAction = function () {
9621 return this.action;
9622 };
9623
9624 /**
9625 * Get symbolic action name.
9626 *
9627 * @return {string}
9628 */
9629 OO.ui.ActionWidget.prototype.getModes = function () {
9630 return this.modes.slice();
9631 };
9632
9633 /**
9634 * Emit a resize event if the size has changed.
9635 *
9636 * @chainable
9637 */
9638 OO.ui.ActionWidget.prototype.propagateResize = function () {
9639 var width, height;
9640
9641 if ( this.isElementAttached() ) {
9642 width = this.$element.width();
9643 height = this.$element.height();
9644
9645 if ( width !== this.width || height !== this.height ) {
9646 this.width = width;
9647 this.height = height;
9648 this.emit( 'resize' );
9649 }
9650 }
9651
9652 return this;
9653 };
9654
9655 /**
9656 * @inheritdoc
9657 */
9658 OO.ui.ActionWidget.prototype.setIcon = function () {
9659 // Mixin method
9660 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
9661 this.propagateResize();
9662
9663 return this;
9664 };
9665
9666 /**
9667 * @inheritdoc
9668 */
9669 OO.ui.ActionWidget.prototype.setLabel = function () {
9670 // Mixin method
9671 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
9672 this.propagateResize();
9673
9674 return this;
9675 };
9676
9677 /**
9678 * @inheritdoc
9679 */
9680 OO.ui.ActionWidget.prototype.setFlags = function () {
9681 // Mixin method
9682 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
9683 this.propagateResize();
9684
9685 return this;
9686 };
9687
9688 /**
9689 * @inheritdoc
9690 */
9691 OO.ui.ActionWidget.prototype.clearFlags = function () {
9692 // Mixin method
9693 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
9694 this.propagateResize();
9695
9696 return this;
9697 };
9698
9699 /**
9700 * Toggle visibility of button.
9701 *
9702 * @param {boolean} [show] Show button, omit to toggle visibility
9703 * @chainable
9704 */
9705 OO.ui.ActionWidget.prototype.toggle = function () {
9706 // Parent method
9707 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
9708 this.propagateResize();
9709
9710 return this;
9711 };
9712
9713 /**
9714 * Button that shows and hides a popup.
9715 *
9716 * @class
9717 * @extends OO.ui.ButtonWidget
9718 * @mixins OO.ui.PopupElement
9719 *
9720 * @constructor
9721 * @param {Object} [config] Configuration options
9722 */
9723 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
9724 // Parent constructor
9725 OO.ui.PopupButtonWidget.super.call( this, config );
9726
9727 // Mixin constructors
9728 OO.ui.PopupElement.call( this, config );
9729
9730 // Initialization
9731 this.$element
9732 .addClass( 'oo-ui-popupButtonWidget' )
9733 .append( this.popup.$element );
9734 };
9735
9736 /* Setup */
9737
9738 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
9739 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
9740
9741 /* Methods */
9742
9743 /**
9744 * Handles mouse click events.
9745 *
9746 * @param {jQuery.Event} e Mouse click event
9747 */
9748 OO.ui.PopupButtonWidget.prototype.onClick = function ( e ) {
9749 // Skip clicks within the popup
9750 if ( $.contains( this.popup.$element[0], e.target ) ) {
9751 return;
9752 }
9753
9754 if ( !this.isDisabled() ) {
9755 this.popup.toggle();
9756 // Parent method
9757 OO.ui.PopupButtonWidget.super.prototype.onClick.call( this );
9758 }
9759 return false;
9760 };
9761
9762 /**
9763 * Button that toggles on and off.
9764 *
9765 * @class
9766 * @extends OO.ui.ButtonWidget
9767 * @mixins OO.ui.ToggleWidget
9768 *
9769 * @constructor
9770 * @param {Object} [config] Configuration options
9771 * @cfg {boolean} [value=false] Initial value
9772 */
9773 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
9774 // Configuration initialization
9775 config = config || {};
9776
9777 // Parent constructor
9778 OO.ui.ToggleButtonWidget.super.call( this, config );
9779
9780 // Mixin constructors
9781 OO.ui.ToggleWidget.call( this, config );
9782
9783 // Initialization
9784 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
9785 };
9786
9787 /* Setup */
9788
9789 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
9790 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
9791
9792 /* Methods */
9793
9794 /**
9795 * @inheritdoc
9796 */
9797 OO.ui.ToggleButtonWidget.prototype.onClick = function () {
9798 if ( !this.isDisabled() ) {
9799 this.setValue( !this.value );
9800 }
9801
9802 // Parent method
9803 return OO.ui.ToggleButtonWidget.super.prototype.onClick.call( this );
9804 };
9805
9806 /**
9807 * @inheritdoc
9808 */
9809 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
9810 value = !!value;
9811 if ( value !== this.value ) {
9812 this.setActive( value );
9813 }
9814
9815 // Parent method (from mixin)
9816 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
9817
9818 return this;
9819 };
9820
9821 /**
9822 * Dropdown menu of options.
9823 *
9824 * Dropdown menus provide a control for accessing a menu and compose a menu within the widget, which
9825 * can be accessed using the #getMenu method.
9826 *
9827 * Use with OO.ui.MenuOptionWidget.
9828 *
9829 * @class
9830 * @extends OO.ui.Widget
9831 * @mixins OO.ui.IconElement
9832 * @mixins OO.ui.IndicatorElement
9833 * @mixins OO.ui.LabelElement
9834 * @mixins OO.ui.TitledElement
9835 *
9836 * @constructor
9837 * @param {Object} [config] Configuration options
9838 * @cfg {Object} [menu] Configuration options to pass to menu widget
9839 */
9840 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
9841 // Configuration initialization
9842 config = $.extend( { indicator: 'down' }, config );
9843
9844 // Parent constructor
9845 OO.ui.DropdownWidget.super.call( this, config );
9846
9847 // Mixin constructors
9848 OO.ui.IconElement.call( this, config );
9849 OO.ui.IndicatorElement.call( this, config );
9850 OO.ui.LabelElement.call( this, config );
9851 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
9852
9853 // Properties
9854 this.menu = new OO.ui.MenuSelectWidget( $.extend( { $: this.$, widget: this }, config.menu ) );
9855 this.$handle = this.$( '<span>' );
9856
9857 // Events
9858 this.$element.on( { click: this.onClick.bind( this ) } );
9859 this.menu.connect( this, { select: 'onMenuSelect' } );
9860
9861 // Initialization
9862 this.$handle
9863 .addClass( 'oo-ui-dropdownWidget-handle' )
9864 .append( this.$icon, this.$label, this.$indicator );
9865 this.$element
9866 .addClass( 'oo-ui-dropdownWidget' )
9867 .append( this.$handle, this.menu.$element );
9868 };
9869
9870 /* Setup */
9871
9872 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
9873 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
9874 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
9875 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
9876 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
9877
9878 /* Methods */
9879
9880 /**
9881 * Get the menu.
9882 *
9883 * @return {OO.ui.MenuSelectWidget} Menu of widget
9884 */
9885 OO.ui.DropdownWidget.prototype.getMenu = function () {
9886 return this.menu;
9887 };
9888
9889 /**
9890 * Handles menu select events.
9891 *
9892 * @param {OO.ui.MenuOptionWidget} item Selected menu item
9893 */
9894 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
9895 var selectedLabel;
9896
9897 if ( !item ) {
9898 return;
9899 }
9900
9901 selectedLabel = item.getLabel();
9902
9903 // If the label is a DOM element, clone it, because setLabel will append() it
9904 if ( selectedLabel instanceof jQuery ) {
9905 selectedLabel = selectedLabel.clone();
9906 }
9907
9908 this.setLabel( selectedLabel );
9909 };
9910
9911 /**
9912 * Handles mouse click events.
9913 *
9914 * @param {jQuery.Event} e Mouse click event
9915 */
9916 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
9917 // Skip clicks within the menu
9918 if ( $.contains( this.menu.$element[0], e.target ) ) {
9919 return;
9920 }
9921
9922 if ( !this.isDisabled() ) {
9923 if ( this.menu.isVisible() ) {
9924 this.menu.toggle( false );
9925 } else {
9926 this.menu.toggle( true );
9927 }
9928 }
9929 return false;
9930 };
9931
9932 /**
9933 * Icon widget.
9934 *
9935 * See OO.ui.IconElement for more information.
9936 *
9937 * @class
9938 * @extends OO.ui.Widget
9939 * @mixins OO.ui.IconElement
9940 * @mixins OO.ui.TitledElement
9941 *
9942 * @constructor
9943 * @param {Object} [config] Configuration options
9944 */
9945 OO.ui.IconWidget = function OoUiIconWidget( config ) {
9946 // Configuration initialization
9947 config = config || {};
9948
9949 // Parent constructor
9950 OO.ui.IconWidget.super.call( this, config );
9951
9952 // Mixin constructors
9953 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
9954 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
9955
9956 // Initialization
9957 this.$element.addClass( 'oo-ui-iconWidget' );
9958 };
9959
9960 /* Setup */
9961
9962 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
9963 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
9964 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
9965
9966 /* Static Properties */
9967
9968 OO.ui.IconWidget.static.tagName = 'span';
9969
9970 /**
9971 * Indicator widget.
9972 *
9973 * See OO.ui.IndicatorElement for more information.
9974 *
9975 * @class
9976 * @extends OO.ui.Widget
9977 * @mixins OO.ui.IndicatorElement
9978 * @mixins OO.ui.TitledElement
9979 *
9980 * @constructor
9981 * @param {Object} [config] Configuration options
9982 */
9983 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
9984 // Configuration initialization
9985 config = config || {};
9986
9987 // Parent constructor
9988 OO.ui.IndicatorWidget.super.call( this, config );
9989
9990 // Mixin constructors
9991 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
9992 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
9993
9994 // Initialization
9995 this.$element.addClass( 'oo-ui-indicatorWidget' );
9996 };
9997
9998 /* Setup */
9999
10000 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10001 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10002 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10003
10004 /* Static Properties */
10005
10006 OO.ui.IndicatorWidget.static.tagName = 'span';
10007
10008 /**
10009 * Base class for input widgets.
10010 *
10011 * @abstract
10012 * @class
10013 * @extends OO.ui.Widget
10014 * @mixins OO.ui.FlaggedElement
10015 *
10016 * @constructor
10017 * @param {Object} [config] Configuration options
10018 * @cfg {string} [name=''] HTML input name
10019 * @cfg {string} [value=''] Input value
10020 * @cfg {Function} [inputFilter] Filter function to apply to the input. Takes a string argument and returns a string.
10021 */
10022 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10023 // Configuration initialization
10024 config = config || {};
10025
10026 // Parent constructor
10027 OO.ui.InputWidget.super.call( this, config );
10028
10029 // Mixin constructors
10030 OO.ui.FlaggedElement.call( this, config );
10031
10032 // Properties
10033 this.$input = this.getInputElement( config );
10034 this.value = '';
10035 this.inputFilter = config.inputFilter;
10036
10037 // Events
10038 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10039
10040 // Initialization
10041 this.$input
10042 .attr( 'name', config.name )
10043 .prop( 'disabled', this.isDisabled() );
10044 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10045 this.setValue( config.value );
10046 };
10047
10048 /* Setup */
10049
10050 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10051 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10052
10053 /* Events */
10054
10055 /**
10056 * @event change
10057 * @param {string} value
10058 */
10059
10060 /* Methods */
10061
10062 /**
10063 * Get input element.
10064 *
10065 * @private
10066 * @param {Object} [config] Configuration options
10067 * @return {jQuery} Input element
10068 */
10069 OO.ui.InputWidget.prototype.getInputElement = function () {
10070 return this.$( '<input>' );
10071 };
10072
10073 /**
10074 * Handle potentially value-changing events.
10075 *
10076 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10077 */
10078 OO.ui.InputWidget.prototype.onEdit = function () {
10079 var widget = this;
10080 if ( !this.isDisabled() ) {
10081 // Allow the stack to clear so the value will be updated
10082 setTimeout( function () {
10083 widget.setValue( widget.$input.val() );
10084 } );
10085 }
10086 };
10087
10088 /**
10089 * Get the value of the input.
10090 *
10091 * @return {string} Input value
10092 */
10093 OO.ui.InputWidget.prototype.getValue = function () {
10094 return this.value;
10095 };
10096
10097 /**
10098 * Sets the direction of the current input, either RTL or LTR
10099 *
10100 * @param {boolean} isRTL
10101 */
10102 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10103 if ( isRTL ) {
10104 this.$input.removeClass( 'oo-ui-ltr' );
10105 this.$input.addClass( 'oo-ui-rtl' );
10106 } else {
10107 this.$input.removeClass( 'oo-ui-rtl' );
10108 this.$input.addClass( 'oo-ui-ltr' );
10109 }
10110 };
10111
10112 /**
10113 * Set the value of the input.
10114 *
10115 * @param {string} value New value
10116 * @fires change
10117 * @chainable
10118 */
10119 OO.ui.InputWidget.prototype.setValue = function ( value ) {
10120 value = this.cleanUpValue( value );
10121 // Update the DOM if it has changed. Note that with cleanUpValue, it
10122 // is possible for the DOM value to change without this.value changing.
10123 if ( this.$input.val() !== value ) {
10124 this.$input.val( value );
10125 }
10126 if ( this.value !== value ) {
10127 this.value = value;
10128 this.emit( 'change', this.value );
10129 }
10130 return this;
10131 };
10132
10133 /**
10134 * Clean up incoming value.
10135 *
10136 * Ensures value is a string, and converts undefined and null to empty string.
10137 *
10138 * @private
10139 * @param {string} value Original value
10140 * @return {string} Cleaned up value
10141 */
10142 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
10143 if ( value === undefined || value === null ) {
10144 return '';
10145 } else if ( this.inputFilter ) {
10146 return this.inputFilter( String( value ) );
10147 } else {
10148 return String( value );
10149 }
10150 };
10151
10152 /**
10153 * Simulate the behavior of clicking on a label bound to this input.
10154 */
10155 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
10156 if ( !this.isDisabled() ) {
10157 if ( this.$input.is( ':checkbox,:radio' ) ) {
10158 this.$input.click();
10159 } else if ( this.$input.is( ':input' ) ) {
10160 this.$input[0].focus();
10161 }
10162 }
10163 };
10164
10165 /**
10166 * @inheritdoc
10167 */
10168 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
10169 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
10170 if ( this.$input ) {
10171 this.$input.prop( 'disabled', this.isDisabled() );
10172 }
10173 return this;
10174 };
10175
10176 /**
10177 * Focus the input.
10178 *
10179 * @chainable
10180 */
10181 OO.ui.InputWidget.prototype.focus = function () {
10182 this.$input[0].focus();
10183 return this;
10184 };
10185
10186 /**
10187 * Blur the input.
10188 *
10189 * @chainable
10190 */
10191 OO.ui.InputWidget.prototype.blur = function () {
10192 this.$input[0].blur();
10193 return this;
10194 };
10195
10196 /**
10197 * A button that is an input widget. Intended to be used within a OO.ui.FormLayout.
10198 *
10199 * @class
10200 * @extends OO.ui.InputWidget
10201 * @mixins OO.ui.ButtonElement
10202 * @mixins OO.ui.IconElement
10203 * @mixins OO.ui.IndicatorElement
10204 * @mixins OO.ui.LabelElement
10205 * @mixins OO.ui.TitledElement
10206 * @mixins OO.ui.FlaggedElement
10207 *
10208 * @constructor
10209 * @param {Object} [config] Configuration options
10210 * @cfg {string} [type='button'] HTML tag `type` attribute, may be 'button', 'submit' or 'reset'
10211 * @cfg {boolean} [useInputTag=false] Whether to use `<input/>` rather than `<button/>`. Only useful
10212 * if you need IE 6 support in a form with multiple buttons. If you use this option, icons and
10213 * indicators will not be displayed, it won't be possible to have a non-plaintext label, and it
10214 * won't be possible to set a value (which will internally become identical to the label).
10215 */
10216 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
10217 // Configuration initialization
10218 config = $.extend( { type: 'button', useInputTag: false }, config );
10219
10220 // Properties (must be set before parent constructor, which calls #setValue)
10221 this.useInputTag = config.useInputTag;
10222
10223 // Parent constructor
10224 OO.ui.ButtonInputWidget.super.call( this, config );
10225
10226 // Mixin constructors
10227 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
10228 OO.ui.IconElement.call( this, config );
10229 OO.ui.IndicatorElement.call( this, config );
10230 OO.ui.LabelElement.call( this, config );
10231 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
10232 OO.ui.FlaggedElement.call( this, config );
10233
10234 // Events
10235 this.$input.on( {
10236 click: this.onClick.bind( this ),
10237 keypress: this.onKeyPress.bind( this )
10238 } );
10239
10240 // Initialization
10241 if ( !config.useInputTag ) {
10242 this.$input.append( this.$icon, this.$label, this.$indicator );
10243 }
10244 this.$element.addClass( 'oo-ui-buttonInputWidget' );
10245 };
10246
10247 /* Setup */
10248
10249 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
10250 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
10251 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
10252 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
10253 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
10254 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
10255 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
10256
10257 /* Events */
10258
10259 /**
10260 * @event click
10261 */
10262
10263 /* Methods */
10264
10265 /**
10266 * Get input element.
10267 *
10268 * @private
10269 * @param {Object} [config] Configuration options
10270 * @return {jQuery} Input element
10271 */
10272 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
10273 // Configuration initialization
10274 config = config || {};
10275
10276 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
10277
10278 return this.$( html );
10279 };
10280
10281 /**
10282 * Set label value.
10283 *
10284 * Overridden to support setting the 'value' of `<input/>` elements.
10285 *
10286 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
10287 * text; or null for no label
10288 * @chainable
10289 */
10290 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
10291 OO.ui.LabelElement.prototype.setLabel.call( this, label );
10292
10293 if ( this.useInputTag ) {
10294 if ( typeof label === 'function' ) {
10295 label = OO.ui.resolveMsg( label );
10296 }
10297 if ( label instanceof jQuery ) {
10298 label = label.text();
10299 }
10300 if ( !label ) {
10301 label = '';
10302 }
10303 this.$input.val( label );
10304 }
10305
10306 return this;
10307 };
10308
10309 /**
10310 * Set the value of the input.
10311 *
10312 * Overridden to disable for `<input/>` elements, which have value identical to the label.
10313 *
10314 * @param {string} value New value
10315 * @chainable
10316 */
10317 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
10318 if ( !this.useInputTag ) {
10319 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
10320 }
10321 return this;
10322 };
10323
10324 /**
10325 * Handles mouse click events.
10326 *
10327 * @param {jQuery.Event} e Mouse click event
10328 * @fires click
10329 */
10330 OO.ui.ButtonInputWidget.prototype.onClick = function () {
10331 if ( !this.isDisabled() ) {
10332 this.emit( 'click' );
10333 }
10334 return false;
10335 };
10336
10337 /**
10338 * Handles keypress events.
10339 *
10340 * @param {jQuery.Event} e Keypress event
10341 * @fires click
10342 */
10343 OO.ui.ButtonInputWidget.prototype.onKeyPress = function ( e ) {
10344 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10345 this.emit( 'click' );
10346 }
10347 return false;
10348 };
10349
10350 /**
10351 * Checkbox input widget.
10352 *
10353 * @class
10354 * @extends OO.ui.InputWidget
10355 *
10356 * @constructor
10357 * @param {Object} [config] Configuration options
10358 * @cfg {boolean} [selected=false] Whether the checkbox is initially selected
10359 */
10360 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
10361 // Parent constructor
10362 OO.ui.CheckboxInputWidget.super.call( this, config );
10363
10364 // Initialization
10365 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
10366 this.setSelected( config.selected !== undefined ? config.selected : false );
10367 };
10368
10369 /* Setup */
10370
10371 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
10372
10373 /* Methods */
10374
10375 /**
10376 * Get input element.
10377 *
10378 * @private
10379 * @return {jQuery} Input element
10380 */
10381 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
10382 return this.$( '<input type="checkbox" />' );
10383 };
10384
10385 /**
10386 * @inheritdoc
10387 */
10388 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
10389 var widget = this;
10390 if ( !this.isDisabled() ) {
10391 // Allow the stack to clear so the value will be updated
10392 setTimeout( function () {
10393 widget.setSelected( widget.$input.prop( 'checked' ) );
10394 } );
10395 }
10396 };
10397
10398 /**
10399 * Set selection state of this checkbox.
10400 *
10401 * @param {boolean} state Whether the checkbox is selected
10402 * @chainable
10403 */
10404 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
10405 state = !!state;
10406 if ( this.selected !== state ) {
10407 this.selected = state;
10408 this.$input.prop( 'checked', this.selected );
10409 this.emit( 'change', this.selected );
10410 }
10411 return this;
10412 };
10413
10414 /**
10415 * Check if this checkbox is selected.
10416 *
10417 * @return {boolean} Checkbox is selected
10418 */
10419 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
10420 return this.selected;
10421 };
10422
10423 /**
10424 * Radio input widget.
10425 *
10426 * Radio buttons only make sense as a set, and you probably want to use the OO.ui.RadioSelectWidget
10427 * class instead of using this class directly.
10428 *
10429 * @class
10430 * @extends OO.ui.InputWidget
10431 *
10432 * @constructor
10433 * @param {Object} [config] Configuration options
10434 * @cfg {boolean} [selected=false] Whether the radio button is initially selected
10435 */
10436 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
10437 // Parent constructor
10438 OO.ui.RadioInputWidget.super.call( this, config );
10439
10440 // Initialization
10441 this.$element.addClass( 'oo-ui-radioInputWidget' );
10442 this.setSelected( config.selected !== undefined ? config.selected : false );
10443 };
10444
10445 /* Setup */
10446
10447 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
10448
10449 /* Methods */
10450
10451 /**
10452 * Get input element.
10453 *
10454 * @private
10455 * @return {jQuery} Input element
10456 */
10457 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
10458 return this.$( '<input type="radio" />' );
10459 };
10460
10461 /**
10462 * @inheritdoc
10463 */
10464 OO.ui.RadioInputWidget.prototype.onEdit = function () {
10465 // RadioInputWidget doesn't track its state.
10466 };
10467
10468 /**
10469 * Set selection state of this radio button.
10470 *
10471 * @param {boolean} state Whether the button is selected
10472 * @chainable
10473 */
10474 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
10475 // RadioInputWidget doesn't track its state.
10476 this.$input.prop( 'checked', state );
10477 return this;
10478 };
10479
10480 /**
10481 * Check if this radio button is selected.
10482 *
10483 * @return {boolean} Radio is selected
10484 */
10485 OO.ui.RadioInputWidget.prototype.isSelected = function () {
10486 return this.$input.prop( 'checked' );
10487 };
10488
10489 /**
10490 * Input widget with a text field.
10491 *
10492 * @class
10493 * @extends OO.ui.InputWidget
10494 * @mixins OO.ui.IconElement
10495 * @mixins OO.ui.IndicatorElement
10496 * @mixins OO.ui.PendingElement
10497 *
10498 * @constructor
10499 * @param {Object} [config] Configuration options
10500 * @cfg {string} [type='text'] HTML tag `type` attribute
10501 * @cfg {string} [placeholder] Placeholder text
10502 * @cfg {boolean} [autofocus=false] Ask the browser to focus this widget, using the 'autofocus' HTML
10503 * attribute
10504 * @cfg {boolean} [readOnly=false] Prevent changes
10505 * @cfg {boolean} [multiline=false] Allow multiple lines of text
10506 * @cfg {boolean} [autosize=false] Automatically resize to fit content
10507 * @cfg {boolean} [maxRows=10] Maximum number of rows to make visible when autosizing
10508 * @cfg {RegExp|string} [validate] Regular expression (or symbolic name referencing
10509 * one, see #static-validationPatterns)
10510 */
10511 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
10512 // Configuration initialization
10513 config = $.extend( { readOnly: false }, config );
10514
10515 // Parent constructor
10516 OO.ui.TextInputWidget.super.call( this, config );
10517
10518 // Mixin constructors
10519 OO.ui.IconElement.call( this, config );
10520 OO.ui.IndicatorElement.call( this, config );
10521 OO.ui.PendingElement.call( this, config );
10522
10523 // Properties
10524 this.readOnly = false;
10525 this.multiline = !!config.multiline;
10526 this.autosize = !!config.autosize;
10527 this.maxRows = config.maxRows !== undefined ? config.maxRows : 10;
10528 this.validate = null;
10529
10530 // Clone for resizing
10531 if ( this.autosize ) {
10532 this.$clone = this.$input
10533 .clone()
10534 .insertAfter( this.$input )
10535 .hide();
10536 }
10537
10538 this.setValidation( config.validate );
10539
10540 // Events
10541 this.$input.on( {
10542 keypress: this.onKeyPress.bind( this ),
10543 blur: this.setValidityFlag.bind( this )
10544 } );
10545 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
10546 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
10547 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
10548
10549 // Initialization
10550 this.$element
10551 .addClass( 'oo-ui-textInputWidget' )
10552 .append( this.$icon, this.$indicator );
10553 this.setReadOnly( config.readOnly );
10554 if ( config.placeholder ) {
10555 this.$input.attr( 'placeholder', config.placeholder );
10556 }
10557 if ( config.autofocus ) {
10558 this.$input.attr( 'autofocus', 'autofocus' );
10559 }
10560 this.$element.attr( 'role', 'textbox' );
10561 };
10562
10563 /* Setup */
10564
10565 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
10566 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
10567 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
10568 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
10569
10570 /* Static properties */
10571
10572 OO.ui.TextInputWidget.static.validationPatterns = {
10573 'non-empty': /.+/,
10574 integer: /^\d+$/
10575 };
10576
10577 /* Events */
10578
10579 /**
10580 * User presses enter inside the text box.
10581 *
10582 * Not called if input is multiline.
10583 *
10584 * @event enter
10585 */
10586
10587 /**
10588 * User clicks the icon.
10589 *
10590 * @event icon
10591 */
10592
10593 /**
10594 * User clicks the indicator.
10595 *
10596 * @event indicator
10597 */
10598
10599 /* Methods */
10600
10601 /**
10602 * Handle icon mouse down events.
10603 *
10604 * @param {jQuery.Event} e Mouse down event
10605 * @fires icon
10606 */
10607 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
10608 if ( e.which === 1 ) {
10609 this.$input[0].focus();
10610 this.emit( 'icon' );
10611 return false;
10612 }
10613 };
10614
10615 /**
10616 * Handle indicator mouse down events.
10617 *
10618 * @param {jQuery.Event} e Mouse down event
10619 * @fires indicator
10620 */
10621 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
10622 if ( e.which === 1 ) {
10623 this.$input[0].focus();
10624 this.emit( 'indicator' );
10625 return false;
10626 }
10627 };
10628
10629 /**
10630 * Handle key press events.
10631 *
10632 * @param {jQuery.Event} e Key press event
10633 * @fires enter If enter key is pressed and input is not multiline
10634 */
10635 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
10636 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
10637 this.emit( 'enter', e );
10638 }
10639 };
10640
10641 /**
10642 * Handle element attach events.
10643 *
10644 * @param {jQuery.Event} e Element attach event
10645 */
10646 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
10647 this.adjustSize();
10648 };
10649
10650 /**
10651 * @inheritdoc
10652 */
10653 OO.ui.TextInputWidget.prototype.onEdit = function () {
10654 this.adjustSize();
10655
10656 // Parent method
10657 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
10658 };
10659
10660 /**
10661 * @inheritdoc
10662 */
10663 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
10664 // Parent method
10665 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
10666
10667 this.setValidityFlag();
10668 this.adjustSize();
10669 return this;
10670 };
10671
10672 /**
10673 * Check if the widget is read-only.
10674 *
10675 * @return {boolean}
10676 */
10677 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
10678 return this.readOnly;
10679 };
10680
10681 /**
10682 * Set the read-only state of the widget.
10683 *
10684 * This should probably change the widget's appearance and prevent it from being used.
10685 *
10686 * @param {boolean} state Make input read-only
10687 * @chainable
10688 */
10689 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
10690 this.readOnly = !!state;
10691 this.$input.prop( 'readOnly', this.readOnly );
10692 return this;
10693 };
10694
10695 /**
10696 * Automatically adjust the size of the text input.
10697 *
10698 * This only affects multi-line inputs that are auto-sized.
10699 *
10700 * @chainable
10701 */
10702 OO.ui.TextInputWidget.prototype.adjustSize = function () {
10703 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
10704
10705 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
10706 this.$clone
10707 .val( this.$input.val() )
10708 .attr( 'rows', '' )
10709 // Set inline height property to 0 to measure scroll height
10710 .css( 'height', 0 );
10711
10712 this.$clone[0].style.display = 'block';
10713
10714 this.valCache = this.$input.val();
10715
10716 scrollHeight = this.$clone[0].scrollHeight;
10717
10718 // Remove inline height property to measure natural heights
10719 this.$clone.css( 'height', '' );
10720 innerHeight = this.$clone.innerHeight();
10721 outerHeight = this.$clone.outerHeight();
10722
10723 // Measure max rows height
10724 this.$clone
10725 .attr( 'rows', this.maxRows )
10726 .css( 'height', 'auto' )
10727 .val( '' );
10728 maxInnerHeight = this.$clone.innerHeight();
10729
10730 // Difference between reported innerHeight and scrollHeight with no scrollbars present
10731 // Equals 1 on Blink-based browsers and 0 everywhere else
10732 measurementError = maxInnerHeight - this.$clone[0].scrollHeight;
10733 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
10734
10735 this.$clone[0].style.display = 'none';
10736
10737 // Only apply inline height when expansion beyond natural height is needed
10738 if ( idealHeight > innerHeight ) {
10739 // Use the difference between the inner and outer height as a buffer
10740 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
10741 } else {
10742 this.$input.css( 'height', '' );
10743 }
10744 }
10745 return this;
10746 };
10747
10748 /**
10749 * Get input element.
10750 *
10751 * @private
10752 * @param {Object} [config] Configuration options
10753 * @return {jQuery} Input element
10754 */
10755 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
10756 // Configuration initialization
10757 config = config || {};
10758
10759 var type = config.type || 'text';
10760
10761 return config.multiline ? this.$( '<textarea>' ) : this.$( '<input type="' + type + '" />' );
10762 };
10763
10764 /**
10765 * Check if input supports multiple lines.
10766 *
10767 * @return {boolean}
10768 */
10769 OO.ui.TextInputWidget.prototype.isMultiline = function () {
10770 return !!this.multiline;
10771 };
10772
10773 /**
10774 * Check if input automatically adjusts its size.
10775 *
10776 * @return {boolean}
10777 */
10778 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
10779 return !!this.autosize;
10780 };
10781
10782 /**
10783 * Select the contents of the input.
10784 *
10785 * @chainable
10786 */
10787 OO.ui.TextInputWidget.prototype.select = function () {
10788 this.$input.select();
10789 return this;
10790 };
10791
10792 /**
10793 * Sets the validation pattern to use.
10794 * @param {RegExp|string|null} validate Regular expression (or symbolic name referencing
10795 * one, see #static-validationPatterns)
10796 */
10797 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
10798 if ( validate instanceof RegExp ) {
10799 this.validate = validate;
10800 } else {
10801 this.validate = this.constructor.static.validationPatterns[validate] || /.*/;
10802 }
10803 };
10804
10805 /**
10806 * Sets the 'invalid' flag appropriately.
10807 */
10808 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
10809 var widget = this;
10810 this.isValid().done( function ( valid ) {
10811 widget.setFlags( { invalid: !valid } );
10812 } );
10813 };
10814
10815 /**
10816 * Returns whether or not the current value is considered valid, according to the
10817 * supplied validation pattern.
10818 *
10819 * @return {jQuery.Deferred}
10820 */
10821 OO.ui.TextInputWidget.prototype.isValid = function () {
10822 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
10823 };
10824
10825 /**
10826 * Text input with a menu of optional values.
10827 *
10828 * @class
10829 * @extends OO.ui.Widget
10830 *
10831 * @constructor
10832 * @param {Object} [config] Configuration options
10833 * @cfg {Object} [menu] Configuration options to pass to menu widget
10834 * @cfg {Object} [input] Configuration options to pass to input widget
10835 * @cfg {jQuery} [$overlay] Overlay layer; defaults to relative positioning
10836 */
10837 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
10838 // Configuration initialization
10839 config = config || {};
10840
10841 // Parent constructor
10842 OO.ui.ComboBoxWidget.super.call( this, config );
10843
10844 // Properties
10845 this.$overlay = config.$overlay || this.$element;
10846 this.input = new OO.ui.TextInputWidget( $.extend(
10847 { $: this.$, indicator: 'down', disabled: this.isDisabled() },
10848 config.input
10849 ) );
10850 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
10851 {
10852 $: OO.ui.Element.static.getJQuery( this.$overlay ),
10853 widget: this,
10854 input: this.input,
10855 disabled: this.isDisabled()
10856 },
10857 config.menu
10858 ) );
10859
10860 // Events
10861 this.input.connect( this, {
10862 change: 'onInputChange',
10863 indicator: 'onInputIndicator',
10864 enter: 'onInputEnter'
10865 } );
10866 this.menu.connect( this, {
10867 choose: 'onMenuChoose',
10868 add: 'onMenuItemsChange',
10869 remove: 'onMenuItemsChange'
10870 } );
10871
10872 // Initialization
10873 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
10874 this.$overlay.append( this.menu.$element );
10875 this.onMenuItemsChange();
10876 };
10877
10878 /* Setup */
10879
10880 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
10881
10882 /* Methods */
10883
10884 /**
10885 * Get the combobox's menu.
10886 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
10887 */
10888 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
10889 return this.menu;
10890 };
10891
10892 /**
10893 * Handle input change events.
10894 *
10895 * @param {string} value New value
10896 */
10897 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
10898 var match = this.menu.getItemFromData( value );
10899
10900 this.menu.selectItem( match );
10901
10902 if ( !this.isDisabled() ) {
10903 this.menu.toggle( true );
10904 }
10905 };
10906
10907 /**
10908 * Handle input indicator events.
10909 */
10910 OO.ui.ComboBoxWidget.prototype.onInputIndicator = function () {
10911 if ( !this.isDisabled() ) {
10912 this.menu.toggle();
10913 }
10914 };
10915
10916 /**
10917 * Handle input enter events.
10918 */
10919 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
10920 if ( !this.isDisabled() ) {
10921 this.menu.toggle( false );
10922 }
10923 };
10924
10925 /**
10926 * Handle menu choose events.
10927 *
10928 * @param {OO.ui.OptionWidget} item Chosen item
10929 */
10930 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
10931 if ( item ) {
10932 this.input.setValue( item.getData() );
10933 }
10934 };
10935
10936 /**
10937 * Handle menu item change events.
10938 */
10939 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
10940 var match = this.menu.getItemFromData( this.input.getValue() );
10941 this.menu.selectItem( match );
10942 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
10943 };
10944
10945 /**
10946 * @inheritdoc
10947 */
10948 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
10949 // Parent method
10950 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
10951
10952 if ( this.input ) {
10953 this.input.setDisabled( this.isDisabled() );
10954 }
10955 if ( this.menu ) {
10956 this.menu.setDisabled( this.isDisabled() );
10957 }
10958
10959 return this;
10960 };
10961
10962 /**
10963 * Label widget.
10964 *
10965 * @class
10966 * @extends OO.ui.Widget
10967 * @mixins OO.ui.LabelElement
10968 *
10969 * @constructor
10970 * @param {Object} [config] Configuration options
10971 * @cfg {OO.ui.InputWidget} [input] Input widget this label is for
10972 */
10973 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
10974 // Configuration initialization
10975 config = config || {};
10976
10977 // Parent constructor
10978 OO.ui.LabelWidget.super.call( this, config );
10979
10980 // Mixin constructors
10981 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
10982 OO.ui.TitledElement.call( this, config );
10983
10984 // Properties
10985 this.input = config.input;
10986
10987 // Events
10988 if ( this.input instanceof OO.ui.InputWidget ) {
10989 this.$element.on( 'click', this.onClick.bind( this ) );
10990 }
10991
10992 // Initialization
10993 this.$element.addClass( 'oo-ui-labelWidget' );
10994 };
10995
10996 /* Setup */
10997
10998 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
10999 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
11000 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
11001
11002 /* Static Properties */
11003
11004 OO.ui.LabelWidget.static.tagName = 'span';
11005
11006 /* Methods */
11007
11008 /**
11009 * Handles label mouse click events.
11010 *
11011 * @param {jQuery.Event} e Mouse click event
11012 */
11013 OO.ui.LabelWidget.prototype.onClick = function () {
11014 this.input.simulateLabelClick();
11015 return false;
11016 };
11017
11018 /**
11019 * Generic option widget for use with OO.ui.SelectWidget.
11020 *
11021 * @class
11022 * @extends OO.ui.Widget
11023 * @mixins OO.ui.LabelElement
11024 * @mixins OO.ui.FlaggedElement
11025 *
11026 * @constructor
11027 * @param {Object} [config] Configuration options
11028 */
11029 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
11030 // Configuration initialization
11031 config = config || {};
11032
11033 // Parent constructor
11034 OO.ui.OptionWidget.super.call( this, config );
11035
11036 // Mixin constructors
11037 OO.ui.ItemWidget.call( this );
11038 OO.ui.LabelElement.call( this, config );
11039 OO.ui.FlaggedElement.call( this, config );
11040
11041 // Properties
11042 this.selected = false;
11043 this.highlighted = false;
11044 this.pressed = false;
11045
11046 // Initialization
11047 this.$element
11048 .data( 'oo-ui-optionWidget', this )
11049 .attr( 'role', 'option' )
11050 .addClass( 'oo-ui-optionWidget' )
11051 .append( this.$label );
11052 };
11053
11054 /* Setup */
11055
11056 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
11057 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
11058 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
11059 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
11060
11061 /* Static Properties */
11062
11063 OO.ui.OptionWidget.static.selectable = true;
11064
11065 OO.ui.OptionWidget.static.highlightable = true;
11066
11067 OO.ui.OptionWidget.static.pressable = true;
11068
11069 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
11070
11071 /* Methods */
11072
11073 /**
11074 * Check if option can be selected.
11075 *
11076 * @return {boolean} Item is selectable
11077 */
11078 OO.ui.OptionWidget.prototype.isSelectable = function () {
11079 return this.constructor.static.selectable && !this.isDisabled();
11080 };
11081
11082 /**
11083 * Check if option can be highlighted.
11084 *
11085 * @return {boolean} Item is highlightable
11086 */
11087 OO.ui.OptionWidget.prototype.isHighlightable = function () {
11088 return this.constructor.static.highlightable && !this.isDisabled();
11089 };
11090
11091 /**
11092 * Check if option can be pressed.
11093 *
11094 * @return {boolean} Item is pressable
11095 */
11096 OO.ui.OptionWidget.prototype.isPressable = function () {
11097 return this.constructor.static.pressable && !this.isDisabled();
11098 };
11099
11100 /**
11101 * Check if option is selected.
11102 *
11103 * @return {boolean} Item is selected
11104 */
11105 OO.ui.OptionWidget.prototype.isSelected = function () {
11106 return this.selected;
11107 };
11108
11109 /**
11110 * Check if option is highlighted.
11111 *
11112 * @return {boolean} Item is highlighted
11113 */
11114 OO.ui.OptionWidget.prototype.isHighlighted = function () {
11115 return this.highlighted;
11116 };
11117
11118 /**
11119 * Check if option is pressed.
11120 *
11121 * @return {boolean} Item is pressed
11122 */
11123 OO.ui.OptionWidget.prototype.isPressed = function () {
11124 return this.pressed;
11125 };
11126
11127 /**
11128 * Set selected state.
11129 *
11130 * @param {boolean} [state=false] Select option
11131 * @chainable
11132 */
11133 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
11134 if ( this.constructor.static.selectable ) {
11135 this.selected = !!state;
11136 this.$element.toggleClass( 'oo-ui-optionWidget-selected', state );
11137 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
11138 this.scrollElementIntoView();
11139 }
11140 this.updateThemeClasses();
11141 }
11142 return this;
11143 };
11144
11145 /**
11146 * Set highlighted state.
11147 *
11148 * @param {boolean} [state=false] Highlight option
11149 * @chainable
11150 */
11151 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
11152 if ( this.constructor.static.highlightable ) {
11153 this.highlighted = !!state;
11154 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
11155 this.updateThemeClasses();
11156 }
11157 return this;
11158 };
11159
11160 /**
11161 * Set pressed state.
11162 *
11163 * @param {boolean} [state=false] Press option
11164 * @chainable
11165 */
11166 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
11167 if ( this.constructor.static.pressable ) {
11168 this.pressed = !!state;
11169 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
11170 this.updateThemeClasses();
11171 }
11172 return this;
11173 };
11174
11175 /**
11176 * Make the option's highlight flash.
11177 *
11178 * While flashing, the visual style of the pressed state is removed if present.
11179 *
11180 * @return {jQuery.Promise} Promise resolved when flashing is done
11181 */
11182 OO.ui.OptionWidget.prototype.flash = function () {
11183 var widget = this,
11184 $element = this.$element,
11185 deferred = $.Deferred();
11186
11187 if ( !this.isDisabled() && this.constructor.static.pressable ) {
11188 $element.removeClass( 'oo-ui-optionWidget-highlighted oo-ui-optionWidget-pressed' );
11189 setTimeout( function () {
11190 // Restore original classes
11191 $element
11192 .toggleClass( 'oo-ui-optionWidget-highlighted', widget.highlighted )
11193 .toggleClass( 'oo-ui-optionWidget-pressed', widget.pressed );
11194
11195 setTimeout( function () {
11196 deferred.resolve();
11197 }, 100 );
11198
11199 }, 100 );
11200 }
11201
11202 return deferred.promise();
11203 };
11204
11205 /**
11206 * Option widget with an option icon and indicator.
11207 *
11208 * Use together with OO.ui.SelectWidget.
11209 *
11210 * @class
11211 * @extends OO.ui.OptionWidget
11212 * @mixins OO.ui.IconElement
11213 * @mixins OO.ui.IndicatorElement
11214 *
11215 * @constructor
11216 * @param {Object} [config] Configuration options
11217 */
11218 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
11219 // Parent constructor
11220 OO.ui.DecoratedOptionWidget.super.call( this, config );
11221
11222 // Mixin constructors
11223 OO.ui.IconElement.call( this, config );
11224 OO.ui.IndicatorElement.call( this, config );
11225
11226 // Initialization
11227 this.$element
11228 .addClass( 'oo-ui-decoratedOptionWidget' )
11229 .prepend( this.$icon )
11230 .append( this.$indicator );
11231 };
11232
11233 /* Setup */
11234
11235 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
11236 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
11237 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
11238
11239 /**
11240 * Option widget that looks like a button.
11241 *
11242 * Use together with OO.ui.ButtonSelectWidget.
11243 *
11244 * @class
11245 * @extends OO.ui.DecoratedOptionWidget
11246 * @mixins OO.ui.ButtonElement
11247 *
11248 * @constructor
11249 * @param {Object} [config] Configuration options
11250 */
11251 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
11252 // Parent constructor
11253 OO.ui.ButtonOptionWidget.super.call( this, config );
11254
11255 // Mixin constructors
11256 OO.ui.ButtonElement.call( this, config );
11257
11258 // Initialization
11259 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
11260 this.$button.append( this.$element.contents() );
11261 this.$element.append( this.$button );
11262 };
11263
11264 /* Setup */
11265
11266 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
11267 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
11268
11269 /* Static Properties */
11270
11271 // Allow button mouse down events to pass through so they can be handled by the parent select widget
11272 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
11273
11274 /* Methods */
11275
11276 /**
11277 * @inheritdoc
11278 */
11279 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
11280 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
11281
11282 if ( this.constructor.static.selectable ) {
11283 this.setActive( state );
11284 }
11285
11286 return this;
11287 };
11288
11289 /**
11290 * Option widget that looks like a radio button.
11291 *
11292 * Use together with OO.ui.RadioSelectWidget.
11293 *
11294 * @class
11295 * @extends OO.ui.OptionWidget
11296 *
11297 * @constructor
11298 * @param {Object} [config] Configuration options
11299 */
11300 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
11301 // Parent constructor
11302 OO.ui.RadioOptionWidget.super.call( this, config );
11303
11304 // Properties
11305 this.radio = new OO.ui.RadioInputWidget( { value: config.data } );
11306
11307 // Initialization
11308 this.$element
11309 .addClass( 'oo-ui-radioOptionWidget' )
11310 .prepend( this.radio.$element );
11311 };
11312
11313 /* Setup */
11314
11315 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
11316
11317 /* Static Properties */
11318
11319 OO.ui.RadioOptionWidget.static.highlightable = false;
11320
11321 OO.ui.RadioOptionWidget.static.pressable = false;
11322
11323 /* Methods */
11324
11325 /**
11326 * @inheritdoc
11327 */
11328 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
11329 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
11330
11331 this.radio.setSelected( state );
11332
11333 return this;
11334 };
11335
11336 /**
11337 * Item of an OO.ui.MenuSelectWidget.
11338 *
11339 * @class
11340 * @extends OO.ui.DecoratedOptionWidget
11341 *
11342 * @constructor
11343 * @param {Object} [config] Configuration options
11344 */
11345 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
11346 // Configuration initialization
11347 config = $.extend( { icon: 'check' }, config );
11348
11349 // Parent constructor
11350 OO.ui.MenuOptionWidget.super.call( this, config );
11351
11352 // Initialization
11353 this.$element
11354 .attr( 'role', 'menuitem' )
11355 .addClass( 'oo-ui-menuOptionWidget' );
11356 };
11357
11358 /* Setup */
11359
11360 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
11361
11362 /**
11363 * Section to group one or more items in a OO.ui.MenuSelectWidget.
11364 *
11365 * @class
11366 * @extends OO.ui.DecoratedOptionWidget
11367 *
11368 * @constructor
11369 * @param {Object} [config] Configuration options
11370 */
11371 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
11372 // Parent constructor
11373 OO.ui.MenuSectionOptionWidget.super.call( this, config );
11374
11375 // Initialization
11376 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
11377 };
11378
11379 /* Setup */
11380
11381 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
11382
11383 /* Static Properties */
11384
11385 OO.ui.MenuSectionOptionWidget.static.selectable = false;
11386
11387 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
11388
11389 /**
11390 * Items for an OO.ui.OutlineSelectWidget.
11391 *
11392 * @class
11393 * @extends OO.ui.DecoratedOptionWidget
11394 *
11395 * @constructor
11396 * @param {Object} [config] Configuration options
11397 * @cfg {number} [level] Indentation level
11398 * @cfg {boolean} [movable] Allow modification from outline controls
11399 */
11400 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
11401 // Configuration initialization
11402 config = config || {};
11403
11404 // Parent constructor
11405 OO.ui.OutlineOptionWidget.super.call( this, config );
11406
11407 // Properties
11408 this.level = 0;
11409 this.movable = !!config.movable;
11410 this.removable = !!config.removable;
11411
11412 // Initialization
11413 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
11414 this.setLevel( config.level );
11415 };
11416
11417 /* Setup */
11418
11419 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
11420
11421 /* Static Properties */
11422
11423 OO.ui.OutlineOptionWidget.static.highlightable = false;
11424
11425 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
11426
11427 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
11428
11429 OO.ui.OutlineOptionWidget.static.levels = 3;
11430
11431 /* Methods */
11432
11433 /**
11434 * Check if item is movable.
11435 *
11436 * Movability is used by outline controls.
11437 *
11438 * @return {boolean} Item is movable
11439 */
11440 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
11441 return this.movable;
11442 };
11443
11444 /**
11445 * Check if item is removable.
11446 *
11447 * Removability is used by outline controls.
11448 *
11449 * @return {boolean} Item is removable
11450 */
11451 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
11452 return this.removable;
11453 };
11454
11455 /**
11456 * Get indentation level.
11457 *
11458 * @return {number} Indentation level
11459 */
11460 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
11461 return this.level;
11462 };
11463
11464 /**
11465 * Set movability.
11466 *
11467 * Movability is used by outline controls.
11468 *
11469 * @param {boolean} movable Item is movable
11470 * @chainable
11471 */
11472 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
11473 this.movable = !!movable;
11474 this.updateThemeClasses();
11475 return this;
11476 };
11477
11478 /**
11479 * Set removability.
11480 *
11481 * Removability is used by outline controls.
11482 *
11483 * @param {boolean} movable Item is removable
11484 * @chainable
11485 */
11486 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
11487 this.removable = !!removable;
11488 this.updateThemeClasses();
11489 return this;
11490 };
11491
11492 /**
11493 * Set indentation level.
11494 *
11495 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
11496 * @chainable
11497 */
11498 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
11499 var levels = this.constructor.static.levels,
11500 levelClass = this.constructor.static.levelClass,
11501 i = levels;
11502
11503 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
11504 while ( i-- ) {
11505 if ( this.level === i ) {
11506 this.$element.addClass( levelClass + i );
11507 } else {
11508 this.$element.removeClass( levelClass + i );
11509 }
11510 }
11511 this.updateThemeClasses();
11512
11513 return this;
11514 };
11515
11516 /**
11517 * Container for content that is overlaid and positioned absolutely.
11518 *
11519 * @class
11520 * @extends OO.ui.Widget
11521 * @mixins OO.ui.LabelElement
11522 *
11523 * @constructor
11524 * @param {Object} [config] Configuration options
11525 * @cfg {number} [width=320] Width of popup in pixels
11526 * @cfg {number} [height] Height of popup, omit to use automatic height
11527 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
11528 * @cfg {string} [align='center'] Alignment of popup to origin
11529 * @cfg {jQuery} [$container] Container to prevent popup from rendering outside of
11530 * @cfg {number} [containerPadding=10] How much padding to keep between popup and container
11531 * @cfg {jQuery} [$content] Content to append to the popup's body
11532 * @cfg {boolean} [autoClose=false] Popup auto-closes when it loses focus
11533 * @cfg {jQuery} [$autoCloseIgnore] Elements to not auto close when clicked
11534 * @cfg {boolean} [head] Show label and close button at the top
11535 * @cfg {boolean} [padded] Add padding to the body
11536 */
11537 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
11538 // Configuration initialization
11539 config = config || {};
11540
11541 // Parent constructor
11542 OO.ui.PopupWidget.super.call( this, config );
11543
11544 // Mixin constructors
11545 OO.ui.LabelElement.call( this, config );
11546 OO.ui.ClippableElement.call( this, config );
11547
11548 // Properties
11549 this.visible = false;
11550 this.$popup = this.$( '<div>' );
11551 this.$head = this.$( '<div>' );
11552 this.$body = this.$( '<div>' );
11553 this.$anchor = this.$( '<div>' );
11554 // If undefined, will be computed lazily in updateDimensions()
11555 this.$container = config.$container;
11556 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
11557 this.autoClose = !!config.autoClose;
11558 this.$autoCloseIgnore = config.$autoCloseIgnore;
11559 this.transitionTimeout = null;
11560 this.anchor = null;
11561 this.width = config.width !== undefined ? config.width : 320;
11562 this.height = config.height !== undefined ? config.height : null;
11563 this.align = config.align || 'center';
11564 this.closeButton = new OO.ui.ButtonWidget( { $: this.$, framed: false, icon: 'close' } );
11565 this.onMouseDownHandler = this.onMouseDown.bind( this );
11566
11567 // Events
11568 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
11569
11570 // Initialization
11571 this.toggleAnchor( config.anchor === undefined || config.anchor );
11572 this.$body.addClass( 'oo-ui-popupWidget-body' );
11573 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
11574 this.$head
11575 .addClass( 'oo-ui-popupWidget-head' )
11576 .append( this.$label, this.closeButton.$element );
11577 if ( !config.head ) {
11578 this.$head.hide();
11579 }
11580 this.$popup
11581 .addClass( 'oo-ui-popupWidget-popup' )
11582 .append( this.$head, this.$body );
11583 this.$element
11584 .hide()
11585 .addClass( 'oo-ui-popupWidget' )
11586 .append( this.$popup, this.$anchor );
11587 // Move content, which was added to #$element by OO.ui.Widget, to the body
11588 if ( config.$content instanceof jQuery ) {
11589 this.$body.append( config.$content );
11590 }
11591 if ( config.padded ) {
11592 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
11593 }
11594 this.setClippableElement( this.$body );
11595 };
11596
11597 /* Setup */
11598
11599 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
11600 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
11601 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
11602
11603 /* Methods */
11604
11605 /**
11606 * Handles mouse down events.
11607 *
11608 * @param {jQuery.Event} e Mouse down event
11609 */
11610 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
11611 if (
11612 this.isVisible() &&
11613 !$.contains( this.$element[0], e.target ) &&
11614 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
11615 ) {
11616 this.toggle( false );
11617 }
11618 };
11619
11620 /**
11621 * Bind mouse down listener.
11622 */
11623 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
11624 // Capture clicks outside popup
11625 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
11626 };
11627
11628 /**
11629 * Handles close button click events.
11630 */
11631 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
11632 if ( this.isVisible() ) {
11633 this.toggle( false );
11634 }
11635 };
11636
11637 /**
11638 * Unbind mouse down listener.
11639 */
11640 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
11641 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
11642 };
11643
11644 /**
11645 * Set whether to show a anchor.
11646 *
11647 * @param {boolean} [show] Show anchor, omit to toggle
11648 */
11649 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
11650 show = show === undefined ? !this.anchored : !!show;
11651
11652 if ( this.anchored !== show ) {
11653 if ( show ) {
11654 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
11655 } else {
11656 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
11657 }
11658 this.anchored = show;
11659 }
11660 };
11661
11662 /**
11663 * Check if showing a anchor.
11664 *
11665 * @return {boolean} anchor is visible
11666 */
11667 OO.ui.PopupWidget.prototype.hasAnchor = function () {
11668 return this.anchor;
11669 };
11670
11671 /**
11672 * @inheritdoc
11673 */
11674 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
11675 show = show === undefined ? !this.isVisible() : !!show;
11676
11677 var change = show !== this.isVisible();
11678
11679 // Parent method
11680 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
11681
11682 if ( change ) {
11683 if ( show ) {
11684 if ( this.autoClose ) {
11685 this.bindMouseDownListener();
11686 }
11687 this.updateDimensions();
11688 this.toggleClipping( true );
11689 } else {
11690 this.toggleClipping( false );
11691 if ( this.autoClose ) {
11692 this.unbindMouseDownListener();
11693 }
11694 }
11695 }
11696
11697 return this;
11698 };
11699
11700 /**
11701 * Set the size of the popup.
11702 *
11703 * Changing the size may also change the popup's position depending on the alignment.
11704 *
11705 * @param {number} width Width
11706 * @param {number} height Height
11707 * @param {boolean} [transition=false] Use a smooth transition
11708 * @chainable
11709 */
11710 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
11711 this.width = width;
11712 this.height = height !== undefined ? height : null;
11713 if ( this.isVisible() ) {
11714 this.updateDimensions( transition );
11715 }
11716 };
11717
11718 /**
11719 * Update the size and position.
11720 *
11721 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
11722 * be called automatically.
11723 *
11724 * @param {boolean} [transition=false] Use a smooth transition
11725 * @chainable
11726 */
11727 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
11728 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
11729 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
11730 widget = this;
11731
11732 if ( !this.$container ) {
11733 // Lazy-initialize $container if not specified in constructor
11734 this.$container = this.$( this.getClosestScrollableElementContainer() );
11735 }
11736
11737 // Set height and width before measuring things, since it might cause our measurements
11738 // to change (e.g. due to scrollbars appearing or disappearing)
11739 this.$popup.css( {
11740 width: this.width,
11741 height: this.height !== null ? this.height : 'auto'
11742 } );
11743
11744 // Compute initial popupOffset based on alignment
11745 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[this.align];
11746
11747 // Figure out if this will cause the popup to go beyond the edge of the container
11748 originOffset = this.$element.offset().left;
11749 containerLeft = this.$container.offset().left;
11750 containerWidth = this.$container.innerWidth();
11751 containerRight = containerLeft + containerWidth;
11752 popupLeft = popupOffset - this.containerPadding;
11753 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
11754 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
11755 overlapRight = containerRight - ( originOffset + popupRight );
11756
11757 // Adjust offset to make the popup not go beyond the edge, if needed
11758 if ( overlapRight < 0 ) {
11759 popupOffset += overlapRight;
11760 } else if ( overlapLeft < 0 ) {
11761 popupOffset -= overlapLeft;
11762 }
11763
11764 // Adjust offset to avoid anchor being rendered too close to the edge
11765 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
11766 // TODO: Find a measurement that works for CSS anchors and image anchors
11767 anchorWidth = this.$anchor[0].scrollWidth * 2;
11768 if ( popupOffset + this.width < anchorWidth ) {
11769 popupOffset = anchorWidth - this.width;
11770 } else if ( -popupOffset < anchorWidth ) {
11771 popupOffset = -anchorWidth;
11772 }
11773
11774 // Prevent transition from being interrupted
11775 clearTimeout( this.transitionTimeout );
11776 if ( transition ) {
11777 // Enable transition
11778 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
11779 }
11780
11781 // Position body relative to anchor
11782 this.$popup.css( 'margin-left', popupOffset );
11783
11784 if ( transition ) {
11785 // Prevent transitioning after transition is complete
11786 this.transitionTimeout = setTimeout( function () {
11787 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
11788 }, 200 );
11789 } else {
11790 // Prevent transitioning immediately
11791 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
11792 }
11793
11794 // Reevaluate clipping state since we've relocated and resized the popup
11795 this.clip();
11796
11797 return this;
11798 };
11799
11800 /**
11801 * Progress bar widget.
11802 *
11803 * @class
11804 * @extends OO.ui.Widget
11805 *
11806 * @constructor
11807 * @param {Object} [config] Configuration options
11808 * @cfg {number|boolean} [progress=false] Initial progress percent or false for indeterminate
11809 */
11810 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
11811 // Configuration initialization
11812 config = config || {};
11813
11814 // Parent constructor
11815 OO.ui.ProgressBarWidget.super.call( this, config );
11816
11817 // Properties
11818 this.$bar = this.$( '<div>' );
11819 this.progress = null;
11820
11821 // Initialization
11822 this.setProgress( config.progress !== undefined ? config.progress : false );
11823 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
11824 this.$element
11825 .attr( {
11826 role: 'progressbar',
11827 'aria-valuemin': 0,
11828 'aria-valuemax': 100
11829 } )
11830 .addClass( 'oo-ui-progressBarWidget' )
11831 .append( this.$bar );
11832 };
11833
11834 /* Setup */
11835
11836 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
11837
11838 /* Static Properties */
11839
11840 OO.ui.ProgressBarWidget.static.tagName = 'div';
11841
11842 /* Methods */
11843
11844 /**
11845 * Get progress percent
11846 *
11847 * @return {number} Progress percent
11848 */
11849 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
11850 return this.progress;
11851 };
11852
11853 /**
11854 * Set progress percent
11855 *
11856 * @param {number|boolean} progress Progress percent or false for indeterminate
11857 */
11858 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
11859 this.progress = progress;
11860
11861 if ( progress !== false ) {
11862 this.$bar.css( 'width', this.progress + '%' );
11863 this.$element.attr( 'aria-valuenow', this.progress );
11864 } else {
11865 this.$bar.css( 'width', '' );
11866 this.$element.removeAttr( 'aria-valuenow' );
11867 }
11868 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
11869 };
11870
11871 /**
11872 * Search widget.
11873 *
11874 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
11875 * Results are cleared and populated each time the query is changed.
11876 *
11877 * @class
11878 * @extends OO.ui.Widget
11879 *
11880 * @constructor
11881 * @param {Object} [config] Configuration options
11882 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
11883 * @cfg {string} [value] Initial query value
11884 */
11885 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
11886 // Configuration initialization
11887 config = config || {};
11888
11889 // Parent constructor
11890 OO.ui.SearchWidget.super.call( this, config );
11891
11892 // Properties
11893 this.query = new OO.ui.TextInputWidget( {
11894 $: this.$,
11895 icon: 'search',
11896 placeholder: config.placeholder,
11897 value: config.value
11898 } );
11899 this.results = new OO.ui.SelectWidget( { $: this.$ } );
11900 this.$query = this.$( '<div>' );
11901 this.$results = this.$( '<div>' );
11902
11903 // Events
11904 this.query.connect( this, {
11905 change: 'onQueryChange',
11906 enter: 'onQueryEnter'
11907 } );
11908 this.results.connect( this, {
11909 highlight: 'onResultsHighlight',
11910 select: 'onResultsSelect'
11911 } );
11912 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
11913
11914 // Initialization
11915 this.$query
11916 .addClass( 'oo-ui-searchWidget-query' )
11917 .append( this.query.$element );
11918 this.$results
11919 .addClass( 'oo-ui-searchWidget-results' )
11920 .append( this.results.$element );
11921 this.$element
11922 .addClass( 'oo-ui-searchWidget' )
11923 .append( this.$results, this.$query );
11924 };
11925
11926 /* Setup */
11927
11928 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
11929
11930 /* Events */
11931
11932 /**
11933 * @event highlight
11934 * @param {Object|null} item Item data or null if no item is highlighted
11935 */
11936
11937 /**
11938 * @event select
11939 * @param {Object|null} item Item data or null if no item is selected
11940 */
11941
11942 /* Methods */
11943
11944 /**
11945 * Handle query key down events.
11946 *
11947 * @param {jQuery.Event} e Key down event
11948 */
11949 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
11950 var highlightedItem, nextItem,
11951 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
11952
11953 if ( dir ) {
11954 highlightedItem = this.results.getHighlightedItem();
11955 if ( !highlightedItem ) {
11956 highlightedItem = this.results.getSelectedItem();
11957 }
11958 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
11959 this.results.highlightItem( nextItem );
11960 nextItem.scrollElementIntoView();
11961 }
11962 };
11963
11964 /**
11965 * Handle select widget select events.
11966 *
11967 * Clears existing results. Subclasses should repopulate items according to new query.
11968 *
11969 * @param {string} value New value
11970 */
11971 OO.ui.SearchWidget.prototype.onQueryChange = function () {
11972 // Reset
11973 this.results.clearItems();
11974 };
11975
11976 /**
11977 * Handle select widget enter key events.
11978 *
11979 * Selects highlighted item.
11980 *
11981 * @param {string} value New value
11982 */
11983 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
11984 // Reset
11985 this.results.selectItem( this.results.getHighlightedItem() );
11986 };
11987
11988 /**
11989 * Handle select widget highlight events.
11990 *
11991 * @param {OO.ui.OptionWidget} item Highlighted item
11992 * @fires highlight
11993 */
11994 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
11995 this.emit( 'highlight', item ? item.getData() : null );
11996 };
11997
11998 /**
11999 * Handle select widget select events.
12000 *
12001 * @param {OO.ui.OptionWidget} item Selected item
12002 * @fires select
12003 */
12004 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
12005 this.emit( 'select', item ? item.getData() : null );
12006 };
12007
12008 /**
12009 * Get the query input.
12010 *
12011 * @return {OO.ui.TextInputWidget} Query input
12012 */
12013 OO.ui.SearchWidget.prototype.getQuery = function () {
12014 return this.query;
12015 };
12016
12017 /**
12018 * Get the results list.
12019 *
12020 * @return {OO.ui.SelectWidget} Select list
12021 */
12022 OO.ui.SearchWidget.prototype.getResults = function () {
12023 return this.results;
12024 };
12025
12026 /**
12027 * Generic selection of options.
12028 *
12029 * Items can contain any rendering. Any widget that provides options, from which the user must
12030 * choose one, should be built on this class.
12031 *
12032 * Use together with OO.ui.OptionWidget.
12033 *
12034 * @class
12035 * @extends OO.ui.Widget
12036 * @mixins OO.ui.GroupElement
12037 *
12038 * @constructor
12039 * @param {Object} [config] Configuration options
12040 * @cfg {OO.ui.OptionWidget[]} [items] Options to add
12041 */
12042 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
12043 // Configuration initialization
12044 config = config || {};
12045
12046 // Parent constructor
12047 OO.ui.SelectWidget.super.call( this, config );
12048
12049 // Mixin constructors
12050 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
12051
12052 // Properties
12053 this.pressed = false;
12054 this.selecting = null;
12055 this.onMouseUpHandler = this.onMouseUp.bind( this );
12056 this.onMouseMoveHandler = this.onMouseMove.bind( this );
12057
12058 // Events
12059 this.$element.on( {
12060 mousedown: this.onMouseDown.bind( this ),
12061 mouseover: this.onMouseOver.bind( this ),
12062 mouseleave: this.onMouseLeave.bind( this )
12063 } );
12064
12065 // Initialization
12066 this.$element.addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' );
12067 if ( $.isArray( config.items ) ) {
12068 this.addItems( config.items );
12069 }
12070 };
12071
12072 /* Setup */
12073
12074 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
12075
12076 // Need to mixin base class as well
12077 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
12078 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
12079
12080 /* Events */
12081
12082 /**
12083 * @event highlight
12084 * @param {OO.ui.OptionWidget|null} item Highlighted item
12085 */
12086
12087 /**
12088 * @event press
12089 * @param {OO.ui.OptionWidget|null} item Pressed item
12090 */
12091
12092 /**
12093 * @event select
12094 * @param {OO.ui.OptionWidget|null} item Selected item
12095 */
12096
12097 /**
12098 * @event choose
12099 * @param {OO.ui.OptionWidget|null} item Chosen item
12100 */
12101
12102 /**
12103 * @event add
12104 * @param {OO.ui.OptionWidget[]} items Added items
12105 * @param {number} index Index items were added at
12106 */
12107
12108 /**
12109 * @event remove
12110 * @param {OO.ui.OptionWidget[]} items Removed items
12111 */
12112
12113 /* Methods */
12114
12115 /**
12116 * Handle mouse down events.
12117 *
12118 * @private
12119 * @param {jQuery.Event} e Mouse down event
12120 */
12121 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
12122 var item;
12123
12124 if ( !this.isDisabled() && e.which === 1 ) {
12125 this.togglePressed( true );
12126 item = this.getTargetItem( e );
12127 if ( item && item.isSelectable() ) {
12128 this.pressItem( item );
12129 this.selecting = item;
12130 this.getElementDocument().addEventListener(
12131 'mouseup',
12132 this.onMouseUpHandler,
12133 true
12134 );
12135 this.getElementDocument().addEventListener(
12136 'mousemove',
12137 this.onMouseMoveHandler,
12138 true
12139 );
12140 }
12141 }
12142 return false;
12143 };
12144
12145 /**
12146 * Handle mouse up events.
12147 *
12148 * @private
12149 * @param {jQuery.Event} e Mouse up event
12150 */
12151 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
12152 var item;
12153
12154 this.togglePressed( false );
12155 if ( !this.selecting ) {
12156 item = this.getTargetItem( e );
12157 if ( item && item.isSelectable() ) {
12158 this.selecting = item;
12159 }
12160 }
12161 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
12162 this.pressItem( null );
12163 this.chooseItem( this.selecting );
12164 this.selecting = null;
12165 }
12166
12167 this.getElementDocument().removeEventListener(
12168 'mouseup',
12169 this.onMouseUpHandler,
12170 true
12171 );
12172 this.getElementDocument().removeEventListener(
12173 'mousemove',
12174 this.onMouseMoveHandler,
12175 true
12176 );
12177
12178 return false;
12179 };
12180
12181 /**
12182 * Handle mouse move events.
12183 *
12184 * @private
12185 * @param {jQuery.Event} e Mouse move event
12186 */
12187 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
12188 var item;
12189
12190 if ( !this.isDisabled() && this.pressed ) {
12191 item = this.getTargetItem( e );
12192 if ( item && item !== this.selecting && item.isSelectable() ) {
12193 this.pressItem( item );
12194 this.selecting = item;
12195 }
12196 }
12197 return false;
12198 };
12199
12200 /**
12201 * Handle mouse over events.
12202 *
12203 * @private
12204 * @param {jQuery.Event} e Mouse over event
12205 */
12206 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
12207 var item;
12208
12209 if ( !this.isDisabled() ) {
12210 item = this.getTargetItem( e );
12211 this.highlightItem( item && item.isHighlightable() ? item : null );
12212 }
12213 return false;
12214 };
12215
12216 /**
12217 * Handle mouse leave events.
12218 *
12219 * @private
12220 * @param {jQuery.Event} e Mouse over event
12221 */
12222 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
12223 if ( !this.isDisabled() ) {
12224 this.highlightItem( null );
12225 }
12226 return false;
12227 };
12228
12229 /**
12230 * Get the closest item to a jQuery.Event.
12231 *
12232 * @private
12233 * @param {jQuery.Event} e
12234 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
12235 */
12236 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
12237 var $item = this.$( e.target ).closest( '.oo-ui-optionWidget' );
12238 if ( $item.length ) {
12239 return $item.data( 'oo-ui-optionWidget' );
12240 }
12241 return null;
12242 };
12243
12244 /**
12245 * Get selected item.
12246 *
12247 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
12248 */
12249 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
12250 var i, len;
12251
12252 for ( i = 0, len = this.items.length; i < len; i++ ) {
12253 if ( this.items[i].isSelected() ) {
12254 return this.items[i];
12255 }
12256 }
12257 return null;
12258 };
12259
12260 /**
12261 * Get highlighted item.
12262 *
12263 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
12264 */
12265 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
12266 var i, len;
12267
12268 for ( i = 0, len = this.items.length; i < len; i++ ) {
12269 if ( this.items[i].isHighlighted() ) {
12270 return this.items[i];
12271 }
12272 }
12273 return null;
12274 };
12275
12276 /**
12277 * Toggle pressed state.
12278 *
12279 * @param {boolean} pressed An option is being pressed
12280 */
12281 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
12282 if ( pressed === undefined ) {
12283 pressed = !this.pressed;
12284 }
12285 if ( pressed !== this.pressed ) {
12286 this.$element
12287 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
12288 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
12289 this.pressed = pressed;
12290 }
12291 };
12292
12293 /**
12294 * Highlight an item.
12295 *
12296 * Highlighting is mutually exclusive.
12297 *
12298 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit to deselect all
12299 * @fires highlight
12300 * @chainable
12301 */
12302 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
12303 var i, len, highlighted,
12304 changed = false;
12305
12306 for ( i = 0, len = this.items.length; i < len; i++ ) {
12307 highlighted = this.items[i] === item;
12308 if ( this.items[i].isHighlighted() !== highlighted ) {
12309 this.items[i].setHighlighted( highlighted );
12310 changed = true;
12311 }
12312 }
12313 if ( changed ) {
12314 this.emit( 'highlight', item );
12315 }
12316
12317 return this;
12318 };
12319
12320 /**
12321 * Select an item.
12322 *
12323 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
12324 * @fires select
12325 * @chainable
12326 */
12327 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
12328 var i, len, selected,
12329 changed = false;
12330
12331 for ( i = 0, len = this.items.length; i < len; i++ ) {
12332 selected = this.items[i] === item;
12333 if ( this.items[i].isSelected() !== selected ) {
12334 this.items[i].setSelected( selected );
12335 changed = true;
12336 }
12337 }
12338 if ( changed ) {
12339 this.emit( 'select', item );
12340 }
12341
12342 return this;
12343 };
12344
12345 /**
12346 * Press an item.
12347 *
12348 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
12349 * @fires press
12350 * @chainable
12351 */
12352 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
12353 var i, len, pressed,
12354 changed = false;
12355
12356 for ( i = 0, len = this.items.length; i < len; i++ ) {
12357 pressed = this.items[i] === item;
12358 if ( this.items[i].isPressed() !== pressed ) {
12359 this.items[i].setPressed( pressed );
12360 changed = true;
12361 }
12362 }
12363 if ( changed ) {
12364 this.emit( 'press', item );
12365 }
12366
12367 return this;
12368 };
12369
12370 /**
12371 * Choose an item.
12372 *
12373 * Identical to #selectItem, but may vary in subclasses that want to take additional action when
12374 * an item is selected using the keyboard or mouse.
12375 *
12376 * @param {OO.ui.OptionWidget} item Item to choose
12377 * @fires choose
12378 * @chainable
12379 */
12380 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
12381 this.selectItem( item );
12382 this.emit( 'choose', item );
12383
12384 return this;
12385 };
12386
12387 /**
12388 * Get an item relative to another one.
12389 *
12390 * @param {OO.ui.OptionWidget|null} item Item to start at, null to get relative to list start
12391 * @param {number} direction Direction to move in, -1 to move backward, 1 to move forward
12392 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the menu
12393 */
12394 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
12395 var currentIndex, nextIndex, i,
12396 increase = direction > 0 ? 1 : -1,
12397 len = this.items.length;
12398
12399 if ( item instanceof OO.ui.OptionWidget ) {
12400 currentIndex = $.inArray( item, this.items );
12401 nextIndex = ( currentIndex + increase + len ) % len;
12402 } else {
12403 // If no item is selected and moving forward, start at the beginning.
12404 // If moving backward, start at the end.
12405 nextIndex = direction > 0 ? 0 : len - 1;
12406 }
12407
12408 for ( i = 0; i < len; i++ ) {
12409 item = this.items[nextIndex];
12410 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12411 return item;
12412 }
12413 nextIndex = ( nextIndex + increase + len ) % len;
12414 }
12415 return null;
12416 };
12417
12418 /**
12419 * Get the next selectable item.
12420 *
12421 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
12422 */
12423 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
12424 var i, len, item;
12425
12426 for ( i = 0, len = this.items.length; i < len; i++ ) {
12427 item = this.items[i];
12428 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
12429 return item;
12430 }
12431 }
12432
12433 return null;
12434 };
12435
12436 /**
12437 * Add items.
12438 *
12439 * @param {OO.ui.OptionWidget[]} items Items to add
12440 * @param {number} [index] Index to insert items after
12441 * @fires add
12442 * @chainable
12443 */
12444 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
12445 // Mixin method
12446 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
12447
12448 // Always provide an index, even if it was omitted
12449 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
12450
12451 return this;
12452 };
12453
12454 /**
12455 * Remove items.
12456 *
12457 * Items will be detached, not removed, so they can be used later.
12458 *
12459 * @param {OO.ui.OptionWidget[]} items Items to remove
12460 * @fires remove
12461 * @chainable
12462 */
12463 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
12464 var i, len, item;
12465
12466 // Deselect items being removed
12467 for ( i = 0, len = items.length; i < len; i++ ) {
12468 item = items[i];
12469 if ( item.isSelected() ) {
12470 this.selectItem( null );
12471 }
12472 }
12473
12474 // Mixin method
12475 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
12476
12477 this.emit( 'remove', items );
12478
12479 return this;
12480 };
12481
12482 /**
12483 * Clear all items.
12484 *
12485 * Items will be detached, not removed, so they can be used later.
12486 *
12487 * @fires remove
12488 * @chainable
12489 */
12490 OO.ui.SelectWidget.prototype.clearItems = function () {
12491 var items = this.items.slice();
12492
12493 // Mixin method
12494 OO.ui.GroupWidget.prototype.clearItems.call( this );
12495
12496 // Clear selection
12497 this.selectItem( null );
12498
12499 this.emit( 'remove', items );
12500
12501 return this;
12502 };
12503
12504 /**
12505 * Select widget containing button options.
12506 *
12507 * Use together with OO.ui.ButtonOptionWidget.
12508 *
12509 * @class
12510 * @extends OO.ui.SelectWidget
12511 *
12512 * @constructor
12513 * @param {Object} [config] Configuration options
12514 */
12515 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
12516 // Parent constructor
12517 OO.ui.ButtonSelectWidget.super.call( this, config );
12518
12519 // Initialization
12520 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
12521 };
12522
12523 /* Setup */
12524
12525 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
12526
12527 /**
12528 * Select widget containing radio button options.
12529 *
12530 * Use together with OO.ui.RadioOptionWidget.
12531 *
12532 * @class
12533 * @extends OO.ui.SelectWidget
12534 *
12535 * @constructor
12536 * @param {Object} [config] Configuration options
12537 */
12538 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
12539 // Parent constructor
12540 OO.ui.RadioSelectWidget.super.call( this, config );
12541
12542 // Initialization
12543 this.$element.addClass( 'oo-ui-radioSelectWidget' );
12544 };
12545
12546 /* Setup */
12547
12548 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
12549
12550 /**
12551 * Overlaid menu of options.
12552 *
12553 * Menus are clipped to the visible viewport. They do not provide a control for opening or closing
12554 * the menu.
12555 *
12556 * Use together with OO.ui.MenuOptionWidget.
12557 *
12558 * @class
12559 * @extends OO.ui.SelectWidget
12560 * @mixins OO.ui.ClippableElement
12561 *
12562 * @constructor
12563 * @param {Object} [config] Configuration options
12564 * @cfg {OO.ui.InputWidget} [input] Input to bind keyboard handlers to
12565 * @cfg {OO.ui.Widget} [widget] Widget to bind mouse handlers to
12566 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu
12567 */
12568 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
12569 // Configuration initialization
12570 config = config || {};
12571
12572 // Parent constructor
12573 OO.ui.MenuSelectWidget.super.call( this, config );
12574
12575 // Mixin constructors
12576 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
12577
12578 // Properties
12579 this.flashing = false;
12580 this.visible = false;
12581 this.newItems = null;
12582 this.autoHide = config.autoHide === undefined || !!config.autoHide;
12583 this.$input = config.input ? config.input.$input : null;
12584 this.$widget = config.widget ? config.widget.$element : null;
12585 this.$previousFocus = null;
12586 this.isolated = !config.input;
12587 this.onKeyDownHandler = this.onKeyDown.bind( this );
12588 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
12589
12590 // Initialization
12591 this.$element
12592 .hide()
12593 .attr( 'role', 'menu' )
12594 .addClass( 'oo-ui-menuSelectWidget' );
12595 };
12596
12597 /* Setup */
12598
12599 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
12600 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
12601
12602 /* Methods */
12603
12604 /**
12605 * Handles document mouse down events.
12606 *
12607 * @param {jQuery.Event} e Key down event
12608 */
12609 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
12610 if (
12611 !OO.ui.contains( this.$element[0], e.target, true ) &&
12612 ( !this.$widget || !OO.ui.contains( this.$widget[0], e.target, true ) )
12613 ) {
12614 this.toggle( false );
12615 }
12616 };
12617
12618 /**
12619 * Handles key down events.
12620 *
12621 * @param {jQuery.Event} e Key down event
12622 */
12623 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
12624 var nextItem,
12625 handled = false,
12626 highlightItem = this.getHighlightedItem();
12627
12628 if ( !this.isDisabled() && this.isVisible() ) {
12629 if ( !highlightItem ) {
12630 highlightItem = this.getSelectedItem();
12631 }
12632 switch ( e.keyCode ) {
12633 case OO.ui.Keys.ENTER:
12634 this.chooseItem( highlightItem );
12635 handled = true;
12636 break;
12637 case OO.ui.Keys.UP:
12638 nextItem = this.getRelativeSelectableItem( highlightItem, -1 );
12639 handled = true;
12640 break;
12641 case OO.ui.Keys.DOWN:
12642 nextItem = this.getRelativeSelectableItem( highlightItem, 1 );
12643 handled = true;
12644 break;
12645 case OO.ui.Keys.ESCAPE:
12646 if ( highlightItem ) {
12647 highlightItem.setHighlighted( false );
12648 }
12649 this.toggle( false );
12650 handled = true;
12651 break;
12652 }
12653
12654 if ( nextItem ) {
12655 this.highlightItem( nextItem );
12656 nextItem.scrollElementIntoView();
12657 }
12658
12659 if ( handled ) {
12660 e.preventDefault();
12661 e.stopPropagation();
12662 return false;
12663 }
12664 }
12665 };
12666
12667 /**
12668 * Bind key down listener.
12669 */
12670 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
12671 if ( this.$input ) {
12672 this.$input.on( 'keydown', this.onKeyDownHandler );
12673 } else {
12674 // Capture menu navigation keys
12675 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
12676 }
12677 };
12678
12679 /**
12680 * Unbind key down listener.
12681 */
12682 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
12683 if ( this.$input ) {
12684 this.$input.off( 'keydown' );
12685 } else {
12686 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
12687 }
12688 };
12689
12690 /**
12691 * Choose an item.
12692 *
12693 * This will close the menu when done, unlike selectItem which only changes selection.
12694 *
12695 * @param {OO.ui.OptionWidget} item Item to choose
12696 * @chainable
12697 */
12698 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
12699 var widget = this;
12700
12701 // Parent method
12702 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
12703
12704 if ( item && !this.flashing ) {
12705 this.flashing = true;
12706 item.flash().done( function () {
12707 widget.toggle( false );
12708 widget.flashing = false;
12709 } );
12710 } else {
12711 this.toggle( false );
12712 }
12713
12714 return this;
12715 };
12716
12717 /**
12718 * @inheritdoc
12719 */
12720 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
12721 var i, len, item;
12722
12723 // Parent method
12724 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
12725
12726 // Auto-initialize
12727 if ( !this.newItems ) {
12728 this.newItems = [];
12729 }
12730
12731 for ( i = 0, len = items.length; i < len; i++ ) {
12732 item = items[i];
12733 if ( this.isVisible() ) {
12734 // Defer fitting label until item has been attached
12735 item.fitLabel();
12736 } else {
12737 this.newItems.push( item );
12738 }
12739 }
12740
12741 // Reevaluate clipping
12742 this.clip();
12743
12744 return this;
12745 };
12746
12747 /**
12748 * @inheritdoc
12749 */
12750 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
12751 // Parent method
12752 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
12753
12754 // Reevaluate clipping
12755 this.clip();
12756
12757 return this;
12758 };
12759
12760 /**
12761 * @inheritdoc
12762 */
12763 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
12764 // Parent method
12765 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
12766
12767 // Reevaluate clipping
12768 this.clip();
12769
12770 return this;
12771 };
12772
12773 /**
12774 * @inheritdoc
12775 */
12776 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
12777 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
12778
12779 var i, len,
12780 change = visible !== this.isVisible(),
12781 elementDoc = this.getElementDocument(),
12782 widgetDoc = this.$widget ? this.$widget[0].ownerDocument : null;
12783
12784 // Parent method
12785 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
12786
12787 if ( change ) {
12788 if ( visible ) {
12789 this.bindKeyDownListener();
12790
12791 // Change focus to enable keyboard navigation
12792 if ( this.isolated && this.$input && !this.$input.is( ':focus' ) ) {
12793 this.$previousFocus = this.$( ':focus' );
12794 this.$input[0].focus();
12795 }
12796 if ( this.newItems && this.newItems.length ) {
12797 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
12798 this.newItems[i].fitLabel();
12799 }
12800 this.newItems = null;
12801 }
12802 this.toggleClipping( true );
12803
12804 // Auto-hide
12805 if ( this.autoHide ) {
12806 elementDoc.addEventListener(
12807 'mousedown', this.onDocumentMouseDownHandler, true
12808 );
12809 // Support $widget being in a different document
12810 if ( widgetDoc && widgetDoc !== elementDoc ) {
12811 widgetDoc.addEventListener(
12812 'mousedown', this.onDocumentMouseDownHandler, true
12813 );
12814 }
12815 }
12816 } else {
12817 this.unbindKeyDownListener();
12818 if ( this.isolated && this.$previousFocus ) {
12819 this.$previousFocus[0].focus();
12820 this.$previousFocus = null;
12821 }
12822 elementDoc.removeEventListener(
12823 'mousedown', this.onDocumentMouseDownHandler, true
12824 );
12825 // Support $widget being in a different document
12826 if ( widgetDoc && widgetDoc !== elementDoc ) {
12827 widgetDoc.removeEventListener(
12828 'mousedown', this.onDocumentMouseDownHandler, true
12829 );
12830 }
12831 this.toggleClipping( false );
12832 }
12833 }
12834
12835 return this;
12836 };
12837
12838 /**
12839 * Menu for a text input widget.
12840 *
12841 * This menu is specially designed to be positioned beneath the text input widget. Even if the input
12842 * is in a different frame, the menu's position is automatically calculated and maintained when the
12843 * menu is toggled or the window is resized.
12844 *
12845 * @class
12846 * @extends OO.ui.MenuSelectWidget
12847 *
12848 * @constructor
12849 * @param {OO.ui.TextInputWidget} input Text input widget to provide menu for
12850 * @param {Object} [config] Configuration options
12851 * @cfg {jQuery} [$container=input.$element] Element to render menu under
12852 */
12853 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( input, config ) {
12854 // Configuration initialization
12855 config = config || {};
12856
12857 // Parent constructor
12858 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
12859
12860 // Properties
12861 this.input = input;
12862 this.$container = config.$container || this.input.$element;
12863 this.onWindowResizeHandler = this.onWindowResize.bind( this );
12864
12865 // Initialization
12866 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
12867 };
12868
12869 /* Setup */
12870
12871 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
12872
12873 /* Methods */
12874
12875 /**
12876 * Handle window resize event.
12877 *
12878 * @param {jQuery.Event} e Window resize event
12879 */
12880 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
12881 this.position();
12882 };
12883
12884 /**
12885 * @inheritdoc
12886 */
12887 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
12888 visible = visible === undefined ? !this.isVisible() : !!visible;
12889
12890 var change = visible !== this.isVisible();
12891
12892 if ( change && visible ) {
12893 // Make sure the width is set before the parent method runs.
12894 // After this we have to call this.position(); again to actually
12895 // position ourselves correctly.
12896 this.position();
12897 }
12898
12899 // Parent method
12900 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
12901
12902 if ( change ) {
12903 if ( this.isVisible() ) {
12904 this.position();
12905 this.$( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
12906 } else {
12907 this.$( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
12908 }
12909 }
12910
12911 return this;
12912 };
12913
12914 /**
12915 * Position the menu.
12916 *
12917 * @chainable
12918 */
12919 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
12920 var $container = this.$container,
12921 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
12922
12923 // Position under input
12924 pos.top += $container.height();
12925 this.$element.css( pos );
12926
12927 // Set width
12928 this.setIdealSize( $container.width() );
12929 // We updated the position, so re-evaluate the clipping state
12930 this.clip();
12931
12932 return this;
12933 };
12934
12935 /**
12936 * Structured list of items.
12937 *
12938 * Use with OO.ui.OutlineOptionWidget.
12939 *
12940 * @class
12941 * @extends OO.ui.SelectWidget
12942 *
12943 * @constructor
12944 * @param {Object} [config] Configuration options
12945 */
12946 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
12947 // Configuration initialization
12948 config = config || {};
12949
12950 // Parent constructor
12951 OO.ui.OutlineSelectWidget.super.call( this, config );
12952
12953 // Initialization
12954 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
12955 };
12956
12957 /* Setup */
12958
12959 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
12960
12961 /**
12962 * Switch that slides on and off.
12963 *
12964 * @class
12965 * @extends OO.ui.Widget
12966 * @mixins OO.ui.ToggleWidget
12967 *
12968 * @constructor
12969 * @param {Object} [config] Configuration options
12970 * @cfg {boolean} [value=false] Initial value
12971 */
12972 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
12973 // Parent constructor
12974 OO.ui.ToggleSwitchWidget.super.call( this, config );
12975
12976 // Mixin constructors
12977 OO.ui.ToggleWidget.call( this, config );
12978
12979 // Properties
12980 this.dragging = false;
12981 this.dragStart = null;
12982 this.sliding = false;
12983 this.$glow = this.$( '<span>' );
12984 this.$grip = this.$( '<span>' );
12985
12986 // Events
12987 this.$element.on( 'click', this.onClick.bind( this ) );
12988
12989 // Initialization
12990 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
12991 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
12992 this.$element
12993 .addClass( 'oo-ui-toggleSwitchWidget' )
12994 .append( this.$glow, this.$grip );
12995 };
12996
12997 /* Setup */
12998
12999 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
13000 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
13001
13002 /* Methods */
13003
13004 /**
13005 * Handle mouse down events.
13006 *
13007 * @param {jQuery.Event} e Mouse down event
13008 */
13009 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
13010 if ( !this.isDisabled() && e.which === 1 ) {
13011 this.setValue( !this.value );
13012 }
13013 };
13014
13015 }( OO ) );