Merge "Only need one check for is_dir"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.9.8
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-04-12T17:19:06Z
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 /**
121 * Reconstitute a JavaScript object corresponding to a widget created by
122 * the PHP implementation.
123 *
124 * This is an alias for `OO.ui.Element.static.infuse()`.
125 *
126 * @param {string|HTMLElement|jQuery} idOrNode
127 * A DOM id (if a string) or node for the widget to infuse.
128 * @return {OO.ui.Element}
129 * The `OO.ui.Element` corresponding to this (infusable) document node.
130 */
131 OO.ui.infuse = function ( idOrNode ) {
132 return OO.ui.Element.static.infuse( idOrNode );
133 };
134
135 ( function () {
136 /**
137 * Message store for the default implementation of OO.ui.msg
138 *
139 * Environments that provide a localization system should not use this, but should override
140 * OO.ui.msg altogether.
141 *
142 * @private
143 */
144 var messages = {
145 // Tool tip for a button that moves items in a list down one place
146 'ooui-outline-control-move-down': 'Move item down',
147 // Tool tip for a button that moves items in a list up one place
148 'ooui-outline-control-move-up': 'Move item up',
149 // Tool tip for a button that removes items from a list
150 'ooui-outline-control-remove': 'Remove item',
151 // Label for the toolbar group that contains a list of all other available tools
152 'ooui-toolbar-more': 'More',
153 // Label for the fake tool that expands the full list of tools in a toolbar group
154 'ooui-toolgroup-expand': 'More',
155 // Label for the fake tool that collapses the full list of tools in a toolbar group
156 'ooui-toolgroup-collapse': 'Fewer',
157 // Default label for the accept button of a confirmation dialog
158 'ooui-dialog-message-accept': 'OK',
159 // Default label for the reject button of a confirmation dialog
160 'ooui-dialog-message-reject': 'Cancel',
161 // Title for process dialog error description
162 'ooui-dialog-process-error': 'Something went wrong',
163 // Label for process dialog dismiss error button, visible when describing errors
164 'ooui-dialog-process-dismiss': 'Dismiss',
165 // Label for process dialog retry action button, visible when describing only recoverable errors
166 'ooui-dialog-process-retry': 'Try again',
167 // Label for process dialog retry action button, visible when describing only warnings
168 'ooui-dialog-process-continue': 'Continue'
169 };
170
171 /**
172 * Get a localized message.
173 *
174 * In environments that provide a localization system, this function should be overridden to
175 * return the message translated in the user's language. The default implementation always returns
176 * English messages.
177 *
178 * After the message key, message parameters may optionally be passed. In the default implementation,
179 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
180 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
181 * they support unnamed, ordered message parameters.
182 *
183 * @abstract
184 * @param {string} key Message key
185 * @param {Mixed...} [params] Message parameters
186 * @return {string} Translated message with parameters substituted
187 */
188 OO.ui.msg = function ( key ) {
189 var message = messages[ key ],
190 params = Array.prototype.slice.call( arguments, 1 );
191 if ( typeof message === 'string' ) {
192 // Perform $1 substitution
193 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
194 var i = parseInt( n, 10 );
195 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
196 } );
197 } else {
198 // Return placeholder if message not found
199 message = '[' + key + ']';
200 }
201 return message;
202 };
203
204 /**
205 * Package a message and arguments for deferred resolution.
206 *
207 * Use this when you are statically specifying a message and the message may not yet be present.
208 *
209 * @param {string} key Message key
210 * @param {Mixed...} [params] Message parameters
211 * @return {Function} Function that returns the resolved message when executed
212 */
213 OO.ui.deferMsg = function () {
214 var args = arguments;
215 return function () {
216 return OO.ui.msg.apply( OO.ui, args );
217 };
218 };
219
220 /**
221 * Resolve a message.
222 *
223 * If the message is a function it will be executed, otherwise it will pass through directly.
224 *
225 * @param {Function|string} msg Deferred message, or message text
226 * @return {string} Resolved message
227 */
228 OO.ui.resolveMsg = function ( msg ) {
229 if ( $.isFunction( msg ) ) {
230 return msg();
231 }
232 return msg;
233 };
234
235 } )();
236
237 /**
238 * Element that can be marked as pending.
239 *
240 * @abstract
241 * @class
242 *
243 * @constructor
244 * @param {Object} [config] Configuration options
245 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
246 */
247 OO.ui.PendingElement = function OoUiPendingElement( config ) {
248 // Configuration initialization
249 config = config || {};
250
251 // Properties
252 this.pending = 0;
253 this.$pending = null;
254
255 // Initialisation
256 this.setPendingElement( config.$pending || this.$element );
257 };
258
259 /* Setup */
260
261 OO.initClass( OO.ui.PendingElement );
262
263 /* Methods */
264
265 /**
266 * Set the pending element (and clean up any existing one).
267 *
268 * @param {jQuery} $pending The element to set to pending.
269 */
270 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
271 if ( this.$pending ) {
272 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
273 }
274
275 this.$pending = $pending;
276 if ( this.pending > 0 ) {
277 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
278 }
279 };
280
281 /**
282 * Check if input is pending.
283 *
284 * @return {boolean}
285 */
286 OO.ui.PendingElement.prototype.isPending = function () {
287 return !!this.pending;
288 };
289
290 /**
291 * Increase the pending stack.
292 *
293 * @chainable
294 */
295 OO.ui.PendingElement.prototype.pushPending = function () {
296 if ( this.pending === 0 ) {
297 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
298 this.updateThemeClasses();
299 }
300 this.pending++;
301
302 return this;
303 };
304
305 /**
306 * Reduce the pending stack.
307 *
308 * Clamped at zero.
309 *
310 * @chainable
311 */
312 OO.ui.PendingElement.prototype.popPending = function () {
313 if ( this.pending === 1 ) {
314 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
315 this.updateThemeClasses();
316 }
317 this.pending = Math.max( 0, this.pending - 1 );
318
319 return this;
320 };
321
322 /**
323 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
324 * Actions can be made available for specific contexts (modes) and circumstances
325 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
326 *
327 * ActionSets contain two types of actions:
328 *
329 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
330 * - Other: Other actions include all non-special visible actions.
331 *
332 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
333 *
334 * @example
335 * // Example: An action set used in a process dialog
336 * function MyProcessDialog( config ) {
337 * MyProcessDialog.super.call( this, config );
338 * }
339 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
340 * MyProcessDialog.static.title = 'An action set in a process dialog';
341 * // An action set that uses modes ('edit' and 'help' mode, in this example).
342 * MyProcessDialog.static.actions = [
343 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
344 * { action: 'help', modes: 'edit', label: 'Help' },
345 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
346 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
347 * ];
348 *
349 * MyProcessDialog.prototype.initialize = function () {
350 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
351 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
352 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
353 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
354 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
355 * this.stackLayout = new OO.ui.StackLayout( {
356 * items: [ this.panel1, this.panel2 ]
357 * } );
358 * this.$body.append( this.stackLayout.$element );
359 * };
360 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
361 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
362 * .next( function () {
363 * this.actions.setMode( 'edit' );
364 * }, this );
365 * };
366 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
367 * if ( action === 'help' ) {
368 * this.actions.setMode( 'help' );
369 * this.stackLayout.setItem( this.panel2 );
370 * } else if ( action === 'back' ) {
371 * this.actions.setMode( 'edit' );
372 * this.stackLayout.setItem( this.panel1 );
373 * } else if ( action === 'continue' ) {
374 * var dialog = this;
375 * return new OO.ui.Process( function () {
376 * dialog.close();
377 * } );
378 * }
379 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
380 * };
381 * MyProcessDialog.prototype.getBodyHeight = function () {
382 * return this.panel1.$element.outerHeight( true );
383 * };
384 * var windowManager = new OO.ui.WindowManager();
385 * $( 'body' ).append( windowManager.$element );
386 * var dialog = new MyProcessDialog( {
387 * size: 'medium'
388 * } );
389 * windowManager.addWindows( [ dialog ] );
390 * windowManager.openWindow( dialog );
391 *
392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
393 *
394 * @abstract
395 * @class
396 * @mixins OO.EventEmitter
397 *
398 * @constructor
399 * @param {Object} [config] Configuration options
400 */
401 OO.ui.ActionSet = function OoUiActionSet( config ) {
402 // Configuration initialization
403 config = config || {};
404
405 // Mixin constructors
406 OO.EventEmitter.call( this );
407
408 // Properties
409 this.list = [];
410 this.categories = {
411 actions: 'getAction',
412 flags: 'getFlags',
413 modes: 'getModes'
414 };
415 this.categorized = {};
416 this.special = {};
417 this.others = [];
418 this.organized = false;
419 this.changing = false;
420 this.changed = false;
421 };
422
423 /* Setup */
424
425 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
426
427 /* Static Properties */
428
429 /**
430 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
431 * header of a {@link OO.ui.ProcessDialog process dialog}.
432 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
433 *
434 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
435 *
436 * @abstract
437 * @static
438 * @inheritable
439 * @property {string}
440 */
441 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
442
443 /* Events */
444
445 /**
446 * @event click
447 *
448 * A 'click' event is emitted when an action is clicked.
449 *
450 * @param {OO.ui.ActionWidget} action Action that was clicked
451 */
452
453 /**
454 * @event resize
455 *
456 * A 'resize' event is emitted when an action widget is resized.
457 *
458 * @param {OO.ui.ActionWidget} action Action that was resized
459 */
460
461 /**
462 * @event add
463 *
464 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
465 *
466 * @param {OO.ui.ActionWidget[]} added Actions added
467 */
468
469 /**
470 * @event remove
471 *
472 * A 'remove' event is emitted when actions are {@link #method-remove removed}
473 * or {@link #clear cleared}.
474 *
475 * @param {OO.ui.ActionWidget[]} added Actions removed
476 */
477
478 /**
479 * @event change
480 *
481 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
482 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
483 *
484 */
485
486 /* Methods */
487
488 /**
489 * Handle action change events.
490 *
491 * @private
492 * @fires change
493 */
494 OO.ui.ActionSet.prototype.onActionChange = function () {
495 this.organized = false;
496 if ( this.changing ) {
497 this.changed = true;
498 } else {
499 this.emit( 'change' );
500 }
501 };
502
503 /**
504 * Check if an action is one of the special actions.
505 *
506 * @param {OO.ui.ActionWidget} action Action to check
507 * @return {boolean} Action is special
508 */
509 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
510 var flag;
511
512 for ( flag in this.special ) {
513 if ( action === this.special[ flag ] ) {
514 return true;
515 }
516 }
517
518 return false;
519 };
520
521 /**
522 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
523 * or ‘disabled’.
524 *
525 * @param {Object} [filters] Filters to use, omit to get all actions
526 * @param {string|string[]} [filters.actions] Actions that action widgets must have
527 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
528 * @param {string|string[]} [filters.modes] Modes that action widgets must have
529 * @param {boolean} [filters.visible] Action widgets must be visible
530 * @param {boolean} [filters.disabled] Action widgets must be disabled
531 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
532 */
533 OO.ui.ActionSet.prototype.get = function ( filters ) {
534 var i, len, list, category, actions, index, match, matches;
535
536 if ( filters ) {
537 this.organize();
538
539 // Collect category candidates
540 matches = [];
541 for ( category in this.categorized ) {
542 list = filters[ category ];
543 if ( list ) {
544 if ( !Array.isArray( list ) ) {
545 list = [ list ];
546 }
547 for ( i = 0, len = list.length; i < len; i++ ) {
548 actions = this.categorized[ category ][ list[ i ] ];
549 if ( Array.isArray( actions ) ) {
550 matches.push.apply( matches, actions );
551 }
552 }
553 }
554 }
555 // Remove by boolean filters
556 for ( i = 0, len = matches.length; i < len; i++ ) {
557 match = matches[ i ];
558 if (
559 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
560 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
561 ) {
562 matches.splice( i, 1 );
563 len--;
564 i--;
565 }
566 }
567 // Remove duplicates
568 for ( i = 0, len = matches.length; i < len; i++ ) {
569 match = matches[ i ];
570 index = matches.lastIndexOf( match );
571 while ( index !== i ) {
572 matches.splice( index, 1 );
573 len--;
574 index = matches.lastIndexOf( match );
575 }
576 }
577 return matches;
578 }
579 return this.list.slice();
580 };
581
582 /**
583 * Get 'special' actions.
584 *
585 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
586 * Special flags can be configured in subclasses by changing the static #specialFlags property.
587 *
588 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
589 */
590 OO.ui.ActionSet.prototype.getSpecial = function () {
591 this.organize();
592 return $.extend( {}, this.special );
593 };
594
595 /**
596 * Get 'other' actions.
597 *
598 * Other actions include all non-special visible action widgets.
599 *
600 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
601 */
602 OO.ui.ActionSet.prototype.getOthers = function () {
603 this.organize();
604 return this.others.slice();
605 };
606
607 /**
608 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
609 * to be available in the specified mode will be made visible. All other actions will be hidden.
610 *
611 * @param {string} mode The mode. Only actions configured to be available in the specified
612 * mode will be made visible.
613 * @chainable
614 * @fires toggle
615 * @fires change
616 */
617 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
618 var i, len, action;
619
620 this.changing = true;
621 for ( i = 0, len = this.list.length; i < len; i++ ) {
622 action = this.list[ i ];
623 action.toggle( action.hasMode( mode ) );
624 }
625
626 this.organized = false;
627 this.changing = false;
628 this.emit( 'change' );
629
630 return this;
631 };
632
633 /**
634 * Set the abilities of the specified actions.
635 *
636 * Action widgets that are configured with the specified actions will be enabled
637 * or disabled based on the boolean values specified in the `actions`
638 * parameter.
639 *
640 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
641 * values that indicate whether or not the action should be enabled.
642 * @chainable
643 */
644 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
645 var i, len, action, item;
646
647 for ( i = 0, len = this.list.length; i < len; i++ ) {
648 item = this.list[ i ];
649 action = item.getAction();
650 if ( actions[ action ] !== undefined ) {
651 item.setDisabled( !actions[ action ] );
652 }
653 }
654
655 return this;
656 };
657
658 /**
659 * Executes a function once per action.
660 *
661 * When making changes to multiple actions, use this method instead of iterating over the actions
662 * manually to defer emitting a #change event until after all actions have been changed.
663 *
664 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
665 * @param {Function} callback Callback to run for each action; callback is invoked with three
666 * arguments: the action, the action's index, the list of actions being iterated over
667 * @chainable
668 */
669 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
670 this.changed = false;
671 this.changing = true;
672 this.get( filter ).forEach( callback );
673 this.changing = false;
674 if ( this.changed ) {
675 this.emit( 'change' );
676 }
677
678 return this;
679 };
680
681 /**
682 * Add action widgets to the action set.
683 *
684 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
685 * @chainable
686 * @fires add
687 * @fires change
688 */
689 OO.ui.ActionSet.prototype.add = function ( actions ) {
690 var i, len, action;
691
692 this.changing = true;
693 for ( i = 0, len = actions.length; i < len; i++ ) {
694 action = actions[ i ];
695 action.connect( this, {
696 click: [ 'emit', 'click', action ],
697 resize: [ 'emit', 'resize', action ],
698 toggle: [ 'onActionChange' ]
699 } );
700 this.list.push( action );
701 }
702 this.organized = false;
703 this.emit( 'add', actions );
704 this.changing = false;
705 this.emit( 'change' );
706
707 return this;
708 };
709
710 /**
711 * Remove action widgets from the set.
712 *
713 * To remove all actions, you may wish to use the #clear method instead.
714 *
715 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
716 * @chainable
717 * @fires remove
718 * @fires change
719 */
720 OO.ui.ActionSet.prototype.remove = function ( actions ) {
721 var i, len, index, action;
722
723 this.changing = true;
724 for ( i = 0, len = actions.length; i < len; i++ ) {
725 action = actions[ i ];
726 index = this.list.indexOf( action );
727 if ( index !== -1 ) {
728 action.disconnect( this );
729 this.list.splice( index, 1 );
730 }
731 }
732 this.organized = false;
733 this.emit( 'remove', actions );
734 this.changing = false;
735 this.emit( 'change' );
736
737 return this;
738 };
739
740 /**
741 * Remove all action widets from the set.
742 *
743 * To remove only specified actions, use the {@link #method-remove remove} method instead.
744 *
745 * @chainable
746 * @fires remove
747 * @fires change
748 */
749 OO.ui.ActionSet.prototype.clear = function () {
750 var i, len, action,
751 removed = this.list.slice();
752
753 this.changing = true;
754 for ( i = 0, len = this.list.length; i < len; i++ ) {
755 action = this.list[ i ];
756 action.disconnect( this );
757 }
758
759 this.list = [];
760
761 this.organized = false;
762 this.emit( 'remove', removed );
763 this.changing = false;
764 this.emit( 'change' );
765
766 return this;
767 };
768
769 /**
770 * Organize actions.
771 *
772 * This is called whenever organized information is requested. It will only reorganize the actions
773 * if something has changed since the last time it ran.
774 *
775 * @private
776 * @chainable
777 */
778 OO.ui.ActionSet.prototype.organize = function () {
779 var i, iLen, j, jLen, flag, action, category, list, item, special,
780 specialFlags = this.constructor.static.specialFlags;
781
782 if ( !this.organized ) {
783 this.categorized = {};
784 this.special = {};
785 this.others = [];
786 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
787 action = this.list[ i ];
788 if ( action.isVisible() ) {
789 // Populate categories
790 for ( category in this.categories ) {
791 if ( !this.categorized[ category ] ) {
792 this.categorized[ category ] = {};
793 }
794 list = action[ this.categories[ category ] ]();
795 if ( !Array.isArray( list ) ) {
796 list = [ list ];
797 }
798 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
799 item = list[ j ];
800 if ( !this.categorized[ category ][ item ] ) {
801 this.categorized[ category ][ item ] = [];
802 }
803 this.categorized[ category ][ item ].push( action );
804 }
805 }
806 // Populate special/others
807 special = false;
808 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
809 flag = specialFlags[ j ];
810 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
811 this.special[ flag ] = action;
812 special = true;
813 break;
814 }
815 }
816 if ( !special ) {
817 this.others.push( action );
818 }
819 }
820 }
821 this.organized = true;
822 }
823
824 return this;
825 };
826
827 /**
828 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
829 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
830 * connected to them and can't be interacted with.
831 *
832 * @abstract
833 * @class
834 *
835 * @constructor
836 * @param {Object} [config] Configuration options
837 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
838 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
839 * for an example.
840 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
841 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
842 * @cfg {string} [text] Text to insert
843 * @cfg {Array} [content] An array of content elements to append (after #text).
844 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
845 * Instances of OO.ui.Element will have their $element appended.
846 * @cfg {jQuery} [$content] Content elements to append (after #text)
847 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
848 * Data can also be specified with the #setData method.
849 */
850 OO.ui.Element = function OoUiElement( config ) {
851 // Configuration initialization
852 config = config || {};
853
854 // Properties
855 this.$ = $;
856 this.visible = true;
857 this.data = config.data;
858 this.$element = config.$element ||
859 $( document.createElement( this.getTagName() ) );
860 this.elementGroup = null;
861 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
862 this.updateThemeClassesPending = false;
863
864 // Initialization
865 if ( Array.isArray( config.classes ) ) {
866 this.$element.addClass( config.classes.join( ' ' ) );
867 }
868 if ( config.id ) {
869 this.$element.attr( 'id', config.id );
870 }
871 if ( config.text ) {
872 this.$element.text( config.text );
873 }
874 if ( config.content ) {
875 // The `content` property treats plain strings as text; use an
876 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
877 // appropriate $element appended.
878 this.$element.append( config.content.map( function ( v ) {
879 if ( typeof v === 'string' ) {
880 // Escape string so it is properly represented in HTML.
881 return document.createTextNode( v );
882 } else if ( v instanceof OO.ui.HtmlSnippet ) {
883 // Bypass escaping.
884 return v.toString();
885 } else if ( v instanceof OO.ui.Element ) {
886 return v.$element;
887 }
888 return v;
889 } ) );
890 }
891 if ( config.$content ) {
892 // The `$content` property treats plain strings as HTML.
893 this.$element.append( config.$content );
894 }
895 };
896
897 /* Setup */
898
899 OO.initClass( OO.ui.Element );
900
901 /* Static Properties */
902
903 /**
904 * The name of the HTML tag used by the element.
905 *
906 * The static value may be ignored if the #getTagName method is overridden.
907 *
908 * @static
909 * @inheritable
910 * @property {string}
911 */
912 OO.ui.Element.static.tagName = 'div';
913
914 /* Static Methods */
915
916 /**
917 * Reconstitute a JavaScript object corresponding to a widget created
918 * by the PHP implementation.
919 *
920 * @param {string|HTMLElement|jQuery} idOrNode
921 * A DOM id (if a string) or node for the widget to infuse.
922 * @return {OO.ui.Element}
923 * The `OO.ui.Element` corresponding to this (infusable) document node.
924 * For `Tag` objects emitted on the HTML side (used occasionally for content)
925 * the value returned is a newly-created Element wrapping around the existing
926 * DOM node.
927 */
928 OO.ui.Element.static.infuse = function ( idOrNode ) {
929 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, true );
930 // Verify that the type matches up.
931 // FIXME: uncomment after T89721 is fixed (see T90929)
932 /*
933 if ( !( obj instanceof this['class'] ) ) {
934 throw new Error( 'Infusion type mismatch!' );
935 }
936 */
937 return obj;
938 };
939
940 /**
941 * Implementation helper for `infuse`; skips the type check and has an
942 * extra property so that only the top-level invocation touches the DOM.
943 * @private
944 * @param {string|HTMLElement|jQuery} idOrNode
945 * @param {boolean} top True only for top-level invocation.
946 * @return {OO.ui.Element}
947 */
948 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, top ) {
949 // look for a cached result of a previous infusion.
950 var id, $elem, data, cls, obj;
951 if ( typeof idOrNode === 'string' ) {
952 id = idOrNode;
953 $elem = $( document.getElementById( id ) );
954 } else {
955 $elem = $( idOrNode );
956 id = $elem.attr( 'id' );
957 }
958 data = $elem.data( 'ooui-infused' );
959 if ( data ) {
960 // cached!
961 if ( data === true ) {
962 throw new Error( 'Circular dependency! ' + id );
963 }
964 return data;
965 }
966 if ( !$elem.length ) {
967 throw new Error( 'Widget not found: ' + id );
968 }
969 data = $elem.attr( 'data-ooui' );
970 if ( !data ) {
971 throw new Error( 'No infusion data found: ' + id );
972 }
973 try {
974 data = $.parseJSON( data );
975 } catch ( _ ) {
976 data = null;
977 }
978 if ( !( data && data._ ) ) {
979 throw new Error( 'No valid infusion data found: ' + id );
980 }
981 if ( data._ === 'Tag' ) {
982 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
983 return new OO.ui.Element( { $element: $elem } );
984 }
985 cls = OO.ui[data._];
986 if ( !cls ) {
987 throw new Error( 'Unknown widget type: ' + id );
988 }
989 $elem.data( 'ooui-infused', true ); // prevent loops
990 data.id = id; // implicit
991 data = OO.copy( data, null, function deserialize( value ) {
992 if ( OO.isPlainObject( value ) ) {
993 if ( value.tag ) {
994 return OO.ui.Element.static.unsafeInfuse( value.tag, false );
995 }
996 if ( value.html ) {
997 return new OO.ui.HtmlSnippet( value.html );
998 }
999 }
1000 } );
1001 // jscs:disable requireCapitalizedConstructors
1002 obj = new cls( data ); // rebuild widget
1003 // now replace old DOM with this new DOM.
1004 if ( top ) {
1005 $elem.replaceWith( obj.$element );
1006 }
1007 obj.$element.data( 'ooui-infused', obj );
1008 // set the 'data-ooui' attribute so we can identify infused widgets
1009 obj.$element.attr( 'data-ooui', '' );
1010 return obj;
1011 };
1012
1013 /**
1014 * Get a jQuery function within a specific document.
1015 *
1016 * @static
1017 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1018 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1019 * not in an iframe
1020 * @return {Function} Bound jQuery function
1021 */
1022 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1023 function wrapper( selector ) {
1024 return $( selector, wrapper.context );
1025 }
1026
1027 wrapper.context = this.getDocument( context );
1028
1029 if ( $iframe ) {
1030 wrapper.$iframe = $iframe;
1031 }
1032
1033 return wrapper;
1034 };
1035
1036 /**
1037 * Get the document of an element.
1038 *
1039 * @static
1040 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1041 * @return {HTMLDocument|null} Document object
1042 */
1043 OO.ui.Element.static.getDocument = function ( obj ) {
1044 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1045 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1046 // Empty jQuery selections might have a context
1047 obj.context ||
1048 // HTMLElement
1049 obj.ownerDocument ||
1050 // Window
1051 obj.document ||
1052 // HTMLDocument
1053 ( obj.nodeType === 9 && obj ) ||
1054 null;
1055 };
1056
1057 /**
1058 * Get the window of an element or document.
1059 *
1060 * @static
1061 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1062 * @return {Window} Window object
1063 */
1064 OO.ui.Element.static.getWindow = function ( obj ) {
1065 var doc = this.getDocument( obj );
1066 return doc.parentWindow || doc.defaultView;
1067 };
1068
1069 /**
1070 * Get the direction of an element or document.
1071 *
1072 * @static
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1074 * @return {string} Text direction, either 'ltr' or 'rtl'
1075 */
1076 OO.ui.Element.static.getDir = function ( obj ) {
1077 var isDoc, isWin;
1078
1079 if ( obj instanceof jQuery ) {
1080 obj = obj[ 0 ];
1081 }
1082 isDoc = obj.nodeType === 9;
1083 isWin = obj.document !== undefined;
1084 if ( isDoc || isWin ) {
1085 if ( isWin ) {
1086 obj = obj.document;
1087 }
1088 obj = obj.body;
1089 }
1090 return $( obj ).css( 'direction' );
1091 };
1092
1093 /**
1094 * Get the offset between two frames.
1095 *
1096 * TODO: Make this function not use recursion.
1097 *
1098 * @static
1099 * @param {Window} from Window of the child frame
1100 * @param {Window} [to=window] Window of the parent frame
1101 * @param {Object} [offset] Offset to start with, used internally
1102 * @return {Object} Offset object, containing left and top properties
1103 */
1104 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1105 var i, len, frames, frame, rect;
1106
1107 if ( !to ) {
1108 to = window;
1109 }
1110 if ( !offset ) {
1111 offset = { top: 0, left: 0 };
1112 }
1113 if ( from.parent === from ) {
1114 return offset;
1115 }
1116
1117 // Get iframe element
1118 frames = from.parent.document.getElementsByTagName( 'iframe' );
1119 for ( i = 0, len = frames.length; i < len; i++ ) {
1120 if ( frames[ i ].contentWindow === from ) {
1121 frame = frames[ i ];
1122 break;
1123 }
1124 }
1125
1126 // Recursively accumulate offset values
1127 if ( frame ) {
1128 rect = frame.getBoundingClientRect();
1129 offset.left += rect.left;
1130 offset.top += rect.top;
1131 if ( from !== to ) {
1132 this.getFrameOffset( from.parent, offset );
1133 }
1134 }
1135 return offset;
1136 };
1137
1138 /**
1139 * Get the offset between two elements.
1140 *
1141 * The two elements may be in a different frame, but in that case the frame $element is in must
1142 * be contained in the frame $anchor is in.
1143 *
1144 * @static
1145 * @param {jQuery} $element Element whose position to get
1146 * @param {jQuery} $anchor Element to get $element's position relative to
1147 * @return {Object} Translated position coordinates, containing top and left properties
1148 */
1149 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1150 var iframe, iframePos,
1151 pos = $element.offset(),
1152 anchorPos = $anchor.offset(),
1153 elementDocument = this.getDocument( $element ),
1154 anchorDocument = this.getDocument( $anchor );
1155
1156 // If $element isn't in the same document as $anchor, traverse up
1157 while ( elementDocument !== anchorDocument ) {
1158 iframe = elementDocument.defaultView.frameElement;
1159 if ( !iframe ) {
1160 throw new Error( '$element frame is not contained in $anchor frame' );
1161 }
1162 iframePos = $( iframe ).offset();
1163 pos.left += iframePos.left;
1164 pos.top += iframePos.top;
1165 elementDocument = iframe.ownerDocument;
1166 }
1167 pos.left -= anchorPos.left;
1168 pos.top -= anchorPos.top;
1169 return pos;
1170 };
1171
1172 /**
1173 * Get element border sizes.
1174 *
1175 * @static
1176 * @param {HTMLElement} el Element to measure
1177 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1178 */
1179 OO.ui.Element.static.getBorders = function ( el ) {
1180 var doc = el.ownerDocument,
1181 win = doc.parentWindow || doc.defaultView,
1182 style = win && win.getComputedStyle ?
1183 win.getComputedStyle( el, null ) :
1184 el.currentStyle,
1185 $el = $( el ),
1186 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1187 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1188 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1189 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1190
1191 return {
1192 top: top,
1193 left: left,
1194 bottom: bottom,
1195 right: right
1196 };
1197 };
1198
1199 /**
1200 * Get dimensions of an element or window.
1201 *
1202 * @static
1203 * @param {HTMLElement|Window} el Element to measure
1204 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1205 */
1206 OO.ui.Element.static.getDimensions = function ( el ) {
1207 var $el, $win,
1208 doc = el.ownerDocument || el.document,
1209 win = doc.parentWindow || doc.defaultView;
1210
1211 if ( win === el || el === doc.documentElement ) {
1212 $win = $( win );
1213 return {
1214 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1215 scroll: {
1216 top: $win.scrollTop(),
1217 left: $win.scrollLeft()
1218 },
1219 scrollbar: { right: 0, bottom: 0 },
1220 rect: {
1221 top: 0,
1222 left: 0,
1223 bottom: $win.innerHeight(),
1224 right: $win.innerWidth()
1225 }
1226 };
1227 } else {
1228 $el = $( el );
1229 return {
1230 borders: this.getBorders( el ),
1231 scroll: {
1232 top: $el.scrollTop(),
1233 left: $el.scrollLeft()
1234 },
1235 scrollbar: {
1236 right: $el.innerWidth() - el.clientWidth,
1237 bottom: $el.innerHeight() - el.clientHeight
1238 },
1239 rect: el.getBoundingClientRect()
1240 };
1241 }
1242 };
1243
1244 /**
1245 * Get scrollable object parent
1246 *
1247 * documentElement can't be used to get or set the scrollTop
1248 * property on Blink. Changing and testing its value lets us
1249 * use 'body' or 'documentElement' based on what is working.
1250 *
1251 * https://code.google.com/p/chromium/issues/detail?id=303131
1252 *
1253 * @static
1254 * @param {HTMLElement} el Element to find scrollable parent for
1255 * @return {HTMLElement} Scrollable parent
1256 */
1257 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1258 var scrollTop, body;
1259
1260 if ( OO.ui.scrollableElement === undefined ) {
1261 body = el.ownerDocument.body;
1262 scrollTop = body.scrollTop;
1263 body.scrollTop = 1;
1264
1265 if ( body.scrollTop === 1 ) {
1266 body.scrollTop = scrollTop;
1267 OO.ui.scrollableElement = 'body';
1268 } else {
1269 OO.ui.scrollableElement = 'documentElement';
1270 }
1271 }
1272
1273 return el.ownerDocument[ OO.ui.scrollableElement ];
1274 };
1275
1276 /**
1277 * Get closest scrollable container.
1278 *
1279 * Traverses up until either a scrollable element or the root is reached, in which case the window
1280 * will be returned.
1281 *
1282 * @static
1283 * @param {HTMLElement} el Element to find scrollable container for
1284 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1285 * @return {HTMLElement} Closest scrollable container
1286 */
1287 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1288 var i, val,
1289 props = [ 'overflow' ],
1290 $parent = $( el ).parent();
1291
1292 if ( dimension === 'x' || dimension === 'y' ) {
1293 props.push( 'overflow-' + dimension );
1294 }
1295
1296 while ( $parent.length ) {
1297 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1298 return $parent[ 0 ];
1299 }
1300 i = props.length;
1301 while ( i-- ) {
1302 val = $parent.css( props[ i ] );
1303 if ( val === 'auto' || val === 'scroll' ) {
1304 return $parent[ 0 ];
1305 }
1306 }
1307 $parent = $parent.parent();
1308 }
1309 return this.getDocument( el ).body;
1310 };
1311
1312 /**
1313 * Scroll element into view.
1314 *
1315 * @static
1316 * @param {HTMLElement} el Element to scroll into view
1317 * @param {Object} [config] Configuration options
1318 * @param {string} [config.duration] jQuery animation duration value
1319 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1320 * to scroll in both directions
1321 * @param {Function} [config.complete] Function to call when scrolling completes
1322 */
1323 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1324 // Configuration initialization
1325 config = config || {};
1326
1327 var rel, anim = {},
1328 callback = typeof config.complete === 'function' && config.complete,
1329 sc = this.getClosestScrollableContainer( el, config.direction ),
1330 $sc = $( sc ),
1331 eld = this.getDimensions( el ),
1332 scd = this.getDimensions( sc ),
1333 $win = $( this.getWindow( el ) );
1334
1335 // Compute the distances between the edges of el and the edges of the scroll viewport
1336 if ( $sc.is( 'html, body' ) ) {
1337 // If the scrollable container is the root, this is easy
1338 rel = {
1339 top: eld.rect.top,
1340 bottom: $win.innerHeight() - eld.rect.bottom,
1341 left: eld.rect.left,
1342 right: $win.innerWidth() - eld.rect.right
1343 };
1344 } else {
1345 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1346 rel = {
1347 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1348 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1349 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1350 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1351 };
1352 }
1353
1354 if ( !config.direction || config.direction === 'y' ) {
1355 if ( rel.top < 0 ) {
1356 anim.scrollTop = scd.scroll.top + rel.top;
1357 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1358 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1359 }
1360 }
1361 if ( !config.direction || config.direction === 'x' ) {
1362 if ( rel.left < 0 ) {
1363 anim.scrollLeft = scd.scroll.left + rel.left;
1364 } else if ( rel.left > 0 && rel.right < 0 ) {
1365 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1366 }
1367 }
1368 if ( !$.isEmptyObject( anim ) ) {
1369 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1370 if ( callback ) {
1371 $sc.queue( function ( next ) {
1372 callback();
1373 next();
1374 } );
1375 }
1376 } else {
1377 if ( callback ) {
1378 callback();
1379 }
1380 }
1381 };
1382
1383 /**
1384 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1385 * and reserve space for them, because it probably doesn't.
1386 *
1387 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1388 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1389 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1390 * and then reattach (or show) them back.
1391 *
1392 * @static
1393 * @param {HTMLElement} el Element to reconsider the scrollbars on
1394 */
1395 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1396 var i, len, nodes = [];
1397 // Detach all children
1398 while ( el.firstChild ) {
1399 nodes.push( el.firstChild );
1400 el.removeChild( el.firstChild );
1401 }
1402 // Force reflow
1403 void el.offsetHeight;
1404 // Reattach all children
1405 for ( i = 0, len = nodes.length; i < len; i++ ) {
1406 el.appendChild( nodes[ i ] );
1407 }
1408 };
1409
1410 /* Methods */
1411
1412 /**
1413 * Toggle visibility of an element.
1414 *
1415 * @param {boolean} [show] Make element visible, omit to toggle visibility
1416 * @fires visible
1417 * @chainable
1418 */
1419 OO.ui.Element.prototype.toggle = function ( show ) {
1420 show = show === undefined ? !this.visible : !!show;
1421
1422 if ( show !== this.isVisible() ) {
1423 this.visible = show;
1424 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1425 this.emit( 'toggle', show );
1426 }
1427
1428 return this;
1429 };
1430
1431 /**
1432 * Check if element is visible.
1433 *
1434 * @return {boolean} element is visible
1435 */
1436 OO.ui.Element.prototype.isVisible = function () {
1437 return this.visible;
1438 };
1439
1440 /**
1441 * Get element data.
1442 *
1443 * @return {Mixed} Element data
1444 */
1445 OO.ui.Element.prototype.getData = function () {
1446 return this.data;
1447 };
1448
1449 /**
1450 * Set element data.
1451 *
1452 * @param {Mixed} Element data
1453 * @chainable
1454 */
1455 OO.ui.Element.prototype.setData = function ( data ) {
1456 this.data = data;
1457 return this;
1458 };
1459
1460 /**
1461 * Check if element supports one or more methods.
1462 *
1463 * @param {string|string[]} methods Method or list of methods to check
1464 * @return {boolean} All methods are supported
1465 */
1466 OO.ui.Element.prototype.supports = function ( methods ) {
1467 var i, len,
1468 support = 0;
1469
1470 methods = Array.isArray( methods ) ? methods : [ methods ];
1471 for ( i = 0, len = methods.length; i < len; i++ ) {
1472 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1473 support++;
1474 }
1475 }
1476
1477 return methods.length === support;
1478 };
1479
1480 /**
1481 * Update the theme-provided classes.
1482 *
1483 * @localdoc This is called in element mixins and widget classes any time state changes.
1484 * Updating is debounced, minimizing overhead of changing multiple attributes and
1485 * guaranteeing that theme updates do not occur within an element's constructor
1486 */
1487 OO.ui.Element.prototype.updateThemeClasses = function () {
1488 if ( !this.updateThemeClassesPending ) {
1489 this.updateThemeClassesPending = true;
1490 setTimeout( this.debouncedUpdateThemeClassesHandler );
1491 }
1492 };
1493
1494 /**
1495 * @private
1496 */
1497 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1498 OO.ui.theme.updateElementClasses( this );
1499 this.updateThemeClassesPending = false;
1500 };
1501
1502 /**
1503 * Get the HTML tag name.
1504 *
1505 * Override this method to base the result on instance information.
1506 *
1507 * @return {string} HTML tag name
1508 */
1509 OO.ui.Element.prototype.getTagName = function () {
1510 return this.constructor.static.tagName;
1511 };
1512
1513 /**
1514 * Check if the element is attached to the DOM
1515 * @return {boolean} The element is attached to the DOM
1516 */
1517 OO.ui.Element.prototype.isElementAttached = function () {
1518 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1519 };
1520
1521 /**
1522 * Get the DOM document.
1523 *
1524 * @return {HTMLDocument} Document object
1525 */
1526 OO.ui.Element.prototype.getElementDocument = function () {
1527 // Don't cache this in other ways either because subclasses could can change this.$element
1528 return OO.ui.Element.static.getDocument( this.$element );
1529 };
1530
1531 /**
1532 * Get the DOM window.
1533 *
1534 * @return {Window} Window object
1535 */
1536 OO.ui.Element.prototype.getElementWindow = function () {
1537 return OO.ui.Element.static.getWindow( this.$element );
1538 };
1539
1540 /**
1541 * Get closest scrollable container.
1542 */
1543 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1544 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1545 };
1546
1547 /**
1548 * Get group element is in.
1549 *
1550 * @return {OO.ui.GroupElement|null} Group element, null if none
1551 */
1552 OO.ui.Element.prototype.getElementGroup = function () {
1553 return this.elementGroup;
1554 };
1555
1556 /**
1557 * Set group element is in.
1558 *
1559 * @param {OO.ui.GroupElement|null} group Group element, null if none
1560 * @chainable
1561 */
1562 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1563 this.elementGroup = group;
1564 return this;
1565 };
1566
1567 /**
1568 * Scroll element into view.
1569 *
1570 * @param {Object} [config] Configuration options
1571 */
1572 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1573 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1574 };
1575
1576 /**
1577 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1578 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1579 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1580 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1581 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1582 *
1583 * @abstract
1584 * @class
1585 * @extends OO.ui.Element
1586 * @mixins OO.EventEmitter
1587 *
1588 * @constructor
1589 * @param {Object} [config] Configuration options
1590 */
1591 OO.ui.Layout = function OoUiLayout( config ) {
1592 // Configuration initialization
1593 config = config || {};
1594
1595 // Parent constructor
1596 OO.ui.Layout.super.call( this, config );
1597
1598 // Mixin constructors
1599 OO.EventEmitter.call( this );
1600
1601 // Initialization
1602 this.$element.addClass( 'oo-ui-layout' );
1603 };
1604
1605 /* Setup */
1606
1607 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1608 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1609
1610 /**
1611 * Widgets are compositions of one or more OOjs UI elements that users can both view
1612 * and interact with. All widgets can be configured and modified via a standard API,
1613 * and their state can change dynamically according to a model.
1614 *
1615 * @abstract
1616 * @class
1617 * @extends OO.ui.Element
1618 * @mixins OO.EventEmitter
1619 *
1620 * @constructor
1621 * @param {Object} [config] Configuration options
1622 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1623 * appearance reflects this state.
1624 */
1625 OO.ui.Widget = function OoUiWidget( config ) {
1626 // Initialize config
1627 config = $.extend( { disabled: false }, config );
1628
1629 // Parent constructor
1630 OO.ui.Widget.super.call( this, config );
1631
1632 // Mixin constructors
1633 OO.EventEmitter.call( this );
1634
1635 // Properties
1636 this.disabled = null;
1637 this.wasDisabled = null;
1638
1639 // Initialization
1640 this.$element.addClass( 'oo-ui-widget' );
1641 this.setDisabled( !!config.disabled );
1642 };
1643
1644 /* Setup */
1645
1646 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1647 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1648
1649 /* Events */
1650
1651 /**
1652 * @event disable
1653 *
1654 * A 'disable' event is emitted when a widget is disabled.
1655 *
1656 * @param {boolean} disabled Widget is disabled
1657 */
1658
1659 /**
1660 * @event toggle
1661 *
1662 * A 'toggle' event is emitted when the visibility of the widget changes.
1663 *
1664 * @param {boolean} visible Widget is visible
1665 */
1666
1667 /* Methods */
1668
1669 /**
1670 * Check if the widget is disabled.
1671 *
1672 * @return {boolean} Widget is disabled
1673 */
1674 OO.ui.Widget.prototype.isDisabled = function () {
1675 return this.disabled;
1676 };
1677
1678 /**
1679 * Set the 'disabled' state of the widget.
1680 *
1681 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1682 *
1683 * @param {boolean} disabled Disable widget
1684 * @chainable
1685 */
1686 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1687 var isDisabled;
1688
1689 this.disabled = !!disabled;
1690 isDisabled = this.isDisabled();
1691 if ( isDisabled !== this.wasDisabled ) {
1692 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1693 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1694 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1695 this.emit( 'disable', isDisabled );
1696 this.updateThemeClasses();
1697 }
1698 this.wasDisabled = isDisabled;
1699
1700 return this;
1701 };
1702
1703 /**
1704 * Update the disabled state, in case of changes in parent widget.
1705 *
1706 * @chainable
1707 */
1708 OO.ui.Widget.prototype.updateDisabled = function () {
1709 this.setDisabled( this.disabled );
1710 return this;
1711 };
1712
1713 /**
1714 * A window is a container for elements that are in a child frame. They are used with
1715 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1716 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1717 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1718 * the window manager will choose a sensible fallback.
1719 *
1720 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1721 * different processes are executed:
1722 *
1723 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1724 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1725 * the window.
1726 *
1727 * - {@link #getSetupProcess} method is called and its result executed
1728 * - {@link #getReadyProcess} method is called and its result executed
1729 *
1730 * **opened**: The window is now open
1731 *
1732 * **closing**: The closing stage begins when the window manager's
1733 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1734 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1735 *
1736 * - {@link #getHoldProcess} method is called and its result executed
1737 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1738 *
1739 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1740 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1741 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1742 * processing can complete. Always assume window processes are executed asynchronously.
1743 *
1744 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1745 *
1746 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1747 *
1748 * @abstract
1749 * @class
1750 * @extends OO.ui.Element
1751 * @mixins OO.EventEmitter
1752 *
1753 * @constructor
1754 * @param {Object} [config] Configuration options
1755 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1756 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1757 */
1758 OO.ui.Window = function OoUiWindow( config ) {
1759 // Configuration initialization
1760 config = config || {};
1761
1762 // Parent constructor
1763 OO.ui.Window.super.call( this, config );
1764
1765 // Mixin constructors
1766 OO.EventEmitter.call( this );
1767
1768 // Properties
1769 this.manager = null;
1770 this.size = config.size || this.constructor.static.size;
1771 this.$frame = $( '<div>' );
1772 this.$overlay = $( '<div>' );
1773 this.$content = $( '<div>' );
1774
1775 // Initialization
1776 this.$overlay.addClass( 'oo-ui-window-overlay' );
1777 this.$content
1778 .addClass( 'oo-ui-window-content' )
1779 .attr( 'tabIndex', 0 );
1780 this.$frame
1781 .addClass( 'oo-ui-window-frame' )
1782 .append( this.$content );
1783
1784 this.$element
1785 .addClass( 'oo-ui-window' )
1786 .append( this.$frame, this.$overlay );
1787
1788 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1789 // that reference properties not initialized at that time of parent class construction
1790 // TODO: Find a better way to handle post-constructor setup
1791 this.visible = false;
1792 this.$element.addClass( 'oo-ui-element-hidden' );
1793 };
1794
1795 /* Setup */
1796
1797 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1798 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1799
1800 /* Static Properties */
1801
1802 /**
1803 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1804 *
1805 * The static size is used if no #size is configured during construction.
1806 *
1807 * @static
1808 * @inheritable
1809 * @property {string}
1810 */
1811 OO.ui.Window.static.size = 'medium';
1812
1813 /* Methods */
1814
1815 /**
1816 * Handle mouse down events.
1817 *
1818 * @private
1819 * @param {jQuery.Event} e Mouse down event
1820 */
1821 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1822 // Prevent clicking on the click-block from stealing focus
1823 if ( e.target === this.$element[ 0 ] ) {
1824 return false;
1825 }
1826 };
1827
1828 /**
1829 * Check if the window has been initialized.
1830 *
1831 * Initialization occurs when a window is added to a manager.
1832 *
1833 * @return {boolean} Window has been initialized
1834 */
1835 OO.ui.Window.prototype.isInitialized = function () {
1836 return !!this.manager;
1837 };
1838
1839 /**
1840 * Check if the window is visible.
1841 *
1842 * @return {boolean} Window is visible
1843 */
1844 OO.ui.Window.prototype.isVisible = function () {
1845 return this.visible;
1846 };
1847
1848 /**
1849 * Check if the window is opening.
1850 *
1851 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1852 * method.
1853 *
1854 * @return {boolean} Window is opening
1855 */
1856 OO.ui.Window.prototype.isOpening = function () {
1857 return this.manager.isOpening( this );
1858 };
1859
1860 /**
1861 * Check if the window is closing.
1862 *
1863 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1864 *
1865 * @return {boolean} Window is closing
1866 */
1867 OO.ui.Window.prototype.isClosing = function () {
1868 return this.manager.isClosing( this );
1869 };
1870
1871 /**
1872 * Check if the window is opened.
1873 *
1874 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1875 *
1876 * @return {boolean} Window is opened
1877 */
1878 OO.ui.Window.prototype.isOpened = function () {
1879 return this.manager.isOpened( this );
1880 };
1881
1882 /**
1883 * Get the window manager.
1884 *
1885 * All windows must be attached to a window manager, which is used to open
1886 * and close the window and control its presentation.
1887 *
1888 * @return {OO.ui.WindowManager} Manager of window
1889 */
1890 OO.ui.Window.prototype.getManager = function () {
1891 return this.manager;
1892 };
1893
1894 /**
1895 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1896 *
1897 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1898 */
1899 OO.ui.Window.prototype.getSize = function () {
1900 return this.size;
1901 };
1902
1903 /**
1904 * Disable transitions on window's frame for the duration of the callback function, then enable them
1905 * back.
1906 *
1907 * @private
1908 * @param {Function} callback Function to call while transitions are disabled
1909 */
1910 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1911 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1912 // Disable transitions first, otherwise we'll get values from when the window was animating.
1913 var oldTransition,
1914 styleObj = this.$frame[ 0 ].style;
1915 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1916 styleObj.MozTransition || styleObj.WebkitTransition;
1917 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1918 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1919 callback();
1920 // Force reflow to make sure the style changes done inside callback really are not transitioned
1921 this.$frame.height();
1922 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1923 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1924 };
1925
1926 /**
1927 * Get the height of the full window contents (i.e., the window head, body and foot together).
1928 *
1929 * What consistitutes the head, body, and foot varies depending on the window type.
1930 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1931 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1932 * and special actions in the head, and dialog content in the body.
1933 *
1934 * To get just the height of the dialog body, use the #getBodyHeight method.
1935 *
1936 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1937 */
1938 OO.ui.Window.prototype.getContentHeight = function () {
1939 var bodyHeight,
1940 win = this,
1941 bodyStyleObj = this.$body[ 0 ].style,
1942 frameStyleObj = this.$frame[ 0 ].style;
1943
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1946 this.withoutSizeTransitions( function () {
1947 var oldHeight = frameStyleObj.height,
1948 oldPosition = bodyStyleObj.position;
1949 frameStyleObj.height = '1px';
1950 // Force body to resize to new width
1951 bodyStyleObj.position = 'relative';
1952 bodyHeight = win.getBodyHeight();
1953 frameStyleObj.height = oldHeight;
1954 bodyStyleObj.position = oldPosition;
1955 } );
1956
1957 return (
1958 // Add buffer for border
1959 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1960 // Use combined heights of children
1961 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1962 );
1963 };
1964
1965 /**
1966 * Get the height of the window body.
1967 *
1968 * To get the height of the full window contents (the window body, head, and foot together),
1969 * use #getContentHeight.
1970 *
1971 * When this function is called, the window will temporarily have been resized
1972 * to height=1px, so .scrollHeight measurements can be taken accurately.
1973 *
1974 * @return {number} Height of the window body in pixels
1975 */
1976 OO.ui.Window.prototype.getBodyHeight = function () {
1977 return this.$body[ 0 ].scrollHeight;
1978 };
1979
1980 /**
1981 * Get the directionality of the frame (right-to-left or left-to-right).
1982 *
1983 * @return {string} Directionality: `'ltr'` or `'rtl'`
1984 */
1985 OO.ui.Window.prototype.getDir = function () {
1986 return this.dir;
1987 };
1988
1989 /**
1990 * Get the 'setup' process.
1991 *
1992 * The setup process is used to set up a window for use in a particular context,
1993 * based on the `data` argument. This method is called during the opening phase of the window’s
1994 * lifecycle.
1995 *
1996 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1997 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1998 * of OO.ui.Process.
1999 *
2000 * To add window content that persists between openings, you may wish to use the #initialize method
2001 * instead.
2002 *
2003 * @abstract
2004 * @param {Object} [data] Window opening data
2005 * @return {OO.ui.Process} Setup process
2006 */
2007 OO.ui.Window.prototype.getSetupProcess = function () {
2008 return new OO.ui.Process();
2009 };
2010
2011 /**
2012 * Get the ‘ready’ process.
2013 *
2014 * The ready process is used to ready a window for use in a particular
2015 * context, based on the `data` argument. This method is called during the opening phase of
2016 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2017 *
2018 * Override this method to add additional steps to the ‘ready’ process the parent method
2019 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2020 * methods of OO.ui.Process.
2021 *
2022 * @abstract
2023 * @param {Object} [data] Window opening data
2024 * @return {OO.ui.Process} Ready process
2025 */
2026 OO.ui.Window.prototype.getReadyProcess = function () {
2027 return new OO.ui.Process();
2028 };
2029
2030 /**
2031 * Get the 'hold' process.
2032 *
2033 * The hold proccess is used to keep a window from being used in a particular context,
2034 * based on the `data` argument. This method is called during the closing phase of the window’s
2035 * lifecycle.
2036 *
2037 * Override this method to add additional steps to the 'hold' process the parent method provides
2038 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2039 * of OO.ui.Process.
2040 *
2041 * @abstract
2042 * @param {Object} [data] Window closing data
2043 * @return {OO.ui.Process} Hold process
2044 */
2045 OO.ui.Window.prototype.getHoldProcess = function () {
2046 return new OO.ui.Process();
2047 };
2048
2049 /**
2050 * Get the ‘teardown’ process.
2051 *
2052 * The teardown process is used to teardown a window after use. During teardown,
2053 * user interactions within the window are conveyed and the window is closed, based on the `data`
2054 * argument. This method is called during the closing phase of the window’s lifecycle.
2055 *
2056 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2057 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2058 * of OO.ui.Process.
2059 *
2060 * @abstract
2061 * @param {Object} [data] Window closing data
2062 * @return {OO.ui.Process} Teardown process
2063 */
2064 OO.ui.Window.prototype.getTeardownProcess = function () {
2065 return new OO.ui.Process();
2066 };
2067
2068 /**
2069 * Set the window manager.
2070 *
2071 * This will cause the window to initialize. Calling it more than once will cause an error.
2072 *
2073 * @param {OO.ui.WindowManager} manager Manager for this window
2074 * @throws {Error} An error is thrown if the method is called more than once
2075 * @chainable
2076 */
2077 OO.ui.Window.prototype.setManager = function ( manager ) {
2078 if ( this.manager ) {
2079 throw new Error( 'Cannot set window manager, window already has a manager' );
2080 }
2081
2082 this.manager = manager;
2083 this.initialize();
2084
2085 return this;
2086 };
2087
2088 /**
2089 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2090 *
2091 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2092 * `full`
2093 * @chainable
2094 */
2095 OO.ui.Window.prototype.setSize = function ( size ) {
2096 this.size = size;
2097 this.updateSize();
2098 return this;
2099 };
2100
2101 /**
2102 * Update the window size.
2103 *
2104 * @throws {Error} An error is thrown if the window is not attached to a window manager
2105 * @chainable
2106 */
2107 OO.ui.Window.prototype.updateSize = function () {
2108 if ( !this.manager ) {
2109 throw new Error( 'Cannot update window size, must be attached to a manager' );
2110 }
2111
2112 this.manager.updateWindowSize( this );
2113
2114 return this;
2115 };
2116
2117 /**
2118 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2119 * when the window is opening. In general, setDimensions should not be called directly.
2120 *
2121 * To set the size of the window, use the #setSize method.
2122 *
2123 * @param {Object} dim CSS dimension properties
2124 * @param {string|number} [dim.width] Width
2125 * @param {string|number} [dim.minWidth] Minimum width
2126 * @param {string|number} [dim.maxWidth] Maximum width
2127 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2128 * @param {string|number} [dim.minWidth] Minimum height
2129 * @param {string|number} [dim.maxWidth] Maximum height
2130 * @chainable
2131 */
2132 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2133 var height,
2134 win = this,
2135 styleObj = this.$frame[ 0 ].style;
2136
2137 // Calculate the height we need to set using the correct width
2138 if ( dim.height === undefined ) {
2139 this.withoutSizeTransitions( function () {
2140 var oldWidth = styleObj.width;
2141 win.$frame.css( 'width', dim.width || '' );
2142 height = win.getContentHeight();
2143 styleObj.width = oldWidth;
2144 } );
2145 } else {
2146 height = dim.height;
2147 }
2148
2149 this.$frame.css( {
2150 width: dim.width || '',
2151 minWidth: dim.minWidth || '',
2152 maxWidth: dim.maxWidth || '',
2153 height: height || '',
2154 minHeight: dim.minHeight || '',
2155 maxHeight: dim.maxHeight || ''
2156 } );
2157
2158 return this;
2159 };
2160
2161 /**
2162 * Initialize window contents.
2163 *
2164 * Before the window is opened for the first time, #initialize is called so that content that
2165 * persists between openings can be added to the window.
2166 *
2167 * To set up a window with new content each time the window opens, use #getSetupProcess.
2168 *
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2170 * @chainable
2171 */
2172 OO.ui.Window.prototype.initialize = function () {
2173 if ( !this.manager ) {
2174 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2175 }
2176
2177 // Properties
2178 this.$head = $( '<div>' );
2179 this.$body = $( '<div>' );
2180 this.$foot = $( '<div>' );
2181 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2182 this.$document = $( this.getElementDocument() );
2183
2184 // Events
2185 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2186
2187 // Initialization
2188 this.$head.addClass( 'oo-ui-window-head' );
2189 this.$body.addClass( 'oo-ui-window-body' );
2190 this.$foot.addClass( 'oo-ui-window-foot' );
2191 this.$content.append( this.$head, this.$body, this.$foot );
2192
2193 return this;
2194 };
2195
2196 /**
2197 * Open the window.
2198 *
2199 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2200 * method, which returns a promise resolved when the window is done opening.
2201 *
2202 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2203 *
2204 * @param {Object} [data] Window opening data
2205 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2206 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2207 * value is a new promise, which is resolved when the window begins closing.
2208 * @throws {Error} An error is thrown if the window is not attached to a window manager
2209 */
2210 OO.ui.Window.prototype.open = function ( data ) {
2211 if ( !this.manager ) {
2212 throw new Error( 'Cannot open window, must be attached to a manager' );
2213 }
2214
2215 return this.manager.openWindow( this, data );
2216 };
2217
2218 /**
2219 * Close the window.
2220 *
2221 * This method is a wrapper around a call to the window
2222 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2223 * which returns a closing promise resolved when the window is done closing.
2224 *
2225 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2226 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2227 * the window closes.
2228 *
2229 * @param {Object} [data] Window closing data
2230 * @return {jQuery.Promise} Promise resolved when window is closed
2231 * @throws {Error} An error is thrown if the window is not attached to a window manager
2232 */
2233 OO.ui.Window.prototype.close = function ( data ) {
2234 if ( !this.manager ) {
2235 throw new Error( 'Cannot close window, must be attached to a manager' );
2236 }
2237
2238 return this.manager.closeWindow( this, data );
2239 };
2240
2241 /**
2242 * Setup window.
2243 *
2244 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2245 * by other systems.
2246 *
2247 * @param {Object} [data] Window opening data
2248 * @return {jQuery.Promise} Promise resolved when window is setup
2249 */
2250 OO.ui.Window.prototype.setup = function ( data ) {
2251 var win = this,
2252 deferred = $.Deferred();
2253
2254 this.toggle( true );
2255
2256 this.getSetupProcess( data ).execute().done( function () {
2257 // Force redraw by asking the browser to measure the elements' widths
2258 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2259 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2260 deferred.resolve();
2261 } );
2262
2263 return deferred.promise();
2264 };
2265
2266 /**
2267 * Ready window.
2268 *
2269 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2270 * by other systems.
2271 *
2272 * @param {Object} [data] Window opening data
2273 * @return {jQuery.Promise} Promise resolved when window is ready
2274 */
2275 OO.ui.Window.prototype.ready = function ( data ) {
2276 var win = this,
2277 deferred = $.Deferred();
2278
2279 this.$content.focus();
2280 this.getReadyProcess( data ).execute().done( function () {
2281 // Force redraw by asking the browser to measure the elements' widths
2282 win.$element.addClass( 'oo-ui-window-ready' ).width();
2283 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2284 deferred.resolve();
2285 } );
2286
2287 return deferred.promise();
2288 };
2289
2290 /**
2291 * Hold window.
2292 *
2293 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2294 * by other systems.
2295 *
2296 * @param {Object} [data] Window closing data
2297 * @return {jQuery.Promise} Promise resolved when window is held
2298 */
2299 OO.ui.Window.prototype.hold = function ( data ) {
2300 var win = this,
2301 deferred = $.Deferred();
2302
2303 this.getHoldProcess( data ).execute().done( function () {
2304 // Get the focused element within the window's content
2305 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2306
2307 // Blur the focused element
2308 if ( $focus.length ) {
2309 $focus[ 0 ].blur();
2310 }
2311
2312 // Force redraw by asking the browser to measure the elements' widths
2313 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2314 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2315 deferred.resolve();
2316 } );
2317
2318 return deferred.promise();
2319 };
2320
2321 /**
2322 * Teardown window.
2323 *
2324 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2325 * by other systems.
2326 *
2327 * @param {Object} [data] Window closing data
2328 * @return {jQuery.Promise} Promise resolved when window is torn down
2329 */
2330 OO.ui.Window.prototype.teardown = function ( data ) {
2331 var win = this;
2332
2333 return this.getTeardownProcess( data ).execute()
2334 .done( function () {
2335 // Force redraw by asking the browser to measure the elements' widths
2336 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2337 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2338 win.toggle( false );
2339 } );
2340 };
2341
2342 /**
2343 * The Dialog class serves as the base class for the other types of dialogs.
2344 * Unless extended to include controls, the rendered dialog box is a simple window
2345 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2346 * which opens, closes, and controls the presentation of the window. See the
2347 * [OOjs UI documentation on MediaWiki] [1] for more information.
2348 *
2349 * @example
2350 * // A simple dialog window.
2351 * function MyDialog( config ) {
2352 * MyDialog.super.call( this, config );
2353 * }
2354 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2355 * MyDialog.prototype.initialize = function () {
2356 * MyDialog.super.prototype.initialize.call( this );
2357 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2358 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2359 * this.$body.append( this.content.$element );
2360 * };
2361 * MyDialog.prototype.getBodyHeight = function () {
2362 * return this.content.$element.outerHeight( true );
2363 * };
2364 * var myDialog = new MyDialog( {
2365 * size: 'medium'
2366 * } );
2367 * // Create and append a window manager, which opens and closes the window.
2368 * var windowManager = new OO.ui.WindowManager();
2369 * $( 'body' ).append( windowManager.$element );
2370 * windowManager.addWindows( [ myDialog ] );
2371 * // Open the window!
2372 * windowManager.openWindow( myDialog );
2373 *
2374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2375 *
2376 * @abstract
2377 * @class
2378 * @extends OO.ui.Window
2379 * @mixins OO.ui.PendingElement
2380 *
2381 * @constructor
2382 * @param {Object} [config] Configuration options
2383 */
2384 OO.ui.Dialog = function OoUiDialog( config ) {
2385 // Parent constructor
2386 OO.ui.Dialog.super.call( this, config );
2387
2388 // Mixin constructors
2389 OO.ui.PendingElement.call( this );
2390
2391 // Properties
2392 this.actions = new OO.ui.ActionSet();
2393 this.attachedActions = [];
2394 this.currentAction = null;
2395 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2396
2397 // Events
2398 this.actions.connect( this, {
2399 click: 'onActionClick',
2400 resize: 'onActionResize',
2401 change: 'onActionsChange'
2402 } );
2403
2404 // Initialization
2405 this.$element
2406 .addClass( 'oo-ui-dialog' )
2407 .attr( 'role', 'dialog' );
2408 };
2409
2410 /* Setup */
2411
2412 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2413 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2414
2415 /* Static Properties */
2416
2417 /**
2418 * Symbolic name of dialog.
2419 *
2420 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2421 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2422 *
2423 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2424 *
2425 * @abstract
2426 * @static
2427 * @inheritable
2428 * @property {string}
2429 */
2430 OO.ui.Dialog.static.name = '';
2431
2432 /**
2433 * The dialog title.
2434 *
2435 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2436 * that will produce a Label node or string. The title can also be specified with data passed to the
2437 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2438 *
2439 * @abstract
2440 * @static
2441 * @inheritable
2442 * @property {jQuery|string|Function}
2443 */
2444 OO.ui.Dialog.static.title = '';
2445
2446 /**
2447 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2448 *
2449 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2450 * value will be overriden.
2451 *
2452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2453 *
2454 * @static
2455 * @inheritable
2456 * @property {Object[]}
2457 */
2458 OO.ui.Dialog.static.actions = [];
2459
2460 /**
2461 * Close the dialog when the 'Esc' key is pressed.
2462 *
2463 * @static
2464 * @abstract
2465 * @inheritable
2466 * @property {boolean}
2467 */
2468 OO.ui.Dialog.static.escapable = true;
2469
2470 /* Methods */
2471
2472 /**
2473 * Handle frame document key down events.
2474 *
2475 * @private
2476 * @param {jQuery.Event} e Key down event
2477 */
2478 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2479 if ( e.which === OO.ui.Keys.ESCAPE ) {
2480 this.close();
2481 e.preventDefault();
2482 e.stopPropagation();
2483 }
2484 };
2485
2486 /**
2487 * Handle action resized events.
2488 *
2489 * @private
2490 * @param {OO.ui.ActionWidget} action Action that was resized
2491 */
2492 OO.ui.Dialog.prototype.onActionResize = function () {
2493 // Override in subclass
2494 };
2495
2496 /**
2497 * Handle action click events.
2498 *
2499 * @private
2500 * @param {OO.ui.ActionWidget} action Action that was clicked
2501 */
2502 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2503 if ( !this.isPending() ) {
2504 this.executeAction( action.getAction() );
2505 }
2506 };
2507
2508 /**
2509 * Handle actions change event.
2510 *
2511 * @private
2512 */
2513 OO.ui.Dialog.prototype.onActionsChange = function () {
2514 this.detachActions();
2515 if ( !this.isClosing() ) {
2516 this.attachActions();
2517 }
2518 };
2519
2520 /**
2521 * Get the set of actions used by the dialog.
2522 *
2523 * @return {OO.ui.ActionSet}
2524 */
2525 OO.ui.Dialog.prototype.getActions = function () {
2526 return this.actions;
2527 };
2528
2529 /**
2530 * Get a process for taking action.
2531 *
2532 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2533 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2534 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2535 *
2536 * @abstract
2537 * @param {string} [action] Symbolic name of action
2538 * @return {OO.ui.Process} Action process
2539 */
2540 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2541 return new OO.ui.Process()
2542 .next( function () {
2543 if ( !action ) {
2544 // An empty action always closes the dialog without data, which should always be
2545 // safe and make no changes
2546 this.close();
2547 }
2548 }, this );
2549 };
2550
2551 /**
2552 * @inheritdoc
2553 *
2554 * @param {Object} [data] Dialog opening data
2555 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2556 * the {@link #static-title static title}
2557 * @param {Object[]} [data.actions] List of configuration options for each
2558 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2559 */
2560 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2561 data = data || {};
2562
2563 // Parent method
2564 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2565 .next( function () {
2566 var config = this.constructor.static,
2567 actions = data.actions !== undefined ? data.actions : config.actions;
2568
2569 this.title.setLabel(
2570 data.title !== undefined ? data.title : this.constructor.static.title
2571 );
2572 this.actions.add( this.getActionWidgets( actions ) );
2573
2574 if ( this.constructor.static.escapable ) {
2575 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2576 }
2577 }, this );
2578 };
2579
2580 /**
2581 * @inheritdoc
2582 */
2583 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2584 // Parent method
2585 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2586 .first( function () {
2587 if ( this.constructor.static.escapable ) {
2588 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2589 }
2590
2591 this.actions.clear();
2592 this.currentAction = null;
2593 }, this );
2594 };
2595
2596 /**
2597 * @inheritdoc
2598 */
2599 OO.ui.Dialog.prototype.initialize = function () {
2600 // Parent method
2601 OO.ui.Dialog.super.prototype.initialize.call( this );
2602
2603 // Properties
2604 this.title = new OO.ui.LabelWidget();
2605
2606 // Initialization
2607 this.$content.addClass( 'oo-ui-dialog-content' );
2608 this.setPendingElement( this.$head );
2609 };
2610
2611 /**
2612 * Get action widgets from a list of configs
2613 *
2614 * @param {Object[]} actions Action widget configs
2615 * @return {OO.ui.ActionWidget[]} Action widgets
2616 */
2617 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2618 var i, len, widgets = [];
2619 for ( i = 0, len = actions.length; i < len; i++ ) {
2620 widgets.push(
2621 new OO.ui.ActionWidget( actions[ i ] )
2622 );
2623 }
2624 return widgets;
2625 };
2626
2627 /**
2628 * Attach action actions.
2629 *
2630 * @protected
2631 */
2632 OO.ui.Dialog.prototype.attachActions = function () {
2633 // Remember the list of potentially attached actions
2634 this.attachedActions = this.actions.get();
2635 };
2636
2637 /**
2638 * Detach action actions.
2639 *
2640 * @protected
2641 * @chainable
2642 */
2643 OO.ui.Dialog.prototype.detachActions = function () {
2644 var i, len;
2645
2646 // Detach all actions that may have been previously attached
2647 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2648 this.attachedActions[ i ].$element.detach();
2649 }
2650 this.attachedActions = [];
2651 };
2652
2653 /**
2654 * Execute an action.
2655 *
2656 * @param {string} action Symbolic name of action to execute
2657 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2658 */
2659 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2660 this.pushPending();
2661 this.currentAction = action;
2662 return this.getActionProcess( action ).execute()
2663 .always( this.popPending.bind( this ) );
2664 };
2665
2666 /**
2667 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2668 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2669 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2670 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2671 * pertinent data and reused.
2672 *
2673 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2674 * `opened`, and `closing`, which represent the primary stages of the cycle:
2675 *
2676 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2677 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2678 *
2679 * - an `opening` event is emitted with an `opening` promise
2680 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2682 * window and its result executed
2683 * - a `setup` progress notification is emitted from the `opening` promise
2684 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2685 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2686 * window and its result executed
2687 * - a `ready` progress notification is emitted from the `opening` promise
2688 * - the `opening` promise is resolved with an `opened` promise
2689 *
2690 * **Opened**: the window is now open.
2691 *
2692 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2693 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2694 * to close the window.
2695 *
2696 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2697 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2699 * window and its result executed
2700 * - a `hold` progress notification is emitted from the `closing` promise
2701 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2702 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2703 * window and its result executed
2704 * - a `teardown` progress notification is emitted from the `closing` promise
2705 * - the `closing` promise is resolved. The window is now closed
2706 *
2707 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2708 *
2709 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2710 *
2711 * @class
2712 * @extends OO.ui.Element
2713 * @mixins OO.EventEmitter
2714 *
2715 * @constructor
2716 * @param {Object} [config] Configuration options
2717 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2718 * Note that window classes that are instantiated with a factory must have
2719 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2720 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2721 */
2722 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2723 // Configuration initialization
2724 config = config || {};
2725
2726 // Parent constructor
2727 OO.ui.WindowManager.super.call( this, config );
2728
2729 // Mixin constructors
2730 OO.EventEmitter.call( this );
2731
2732 // Properties
2733 this.factory = config.factory;
2734 this.modal = config.modal === undefined || !!config.modal;
2735 this.windows = {};
2736 this.opening = null;
2737 this.opened = null;
2738 this.closing = null;
2739 this.preparingToOpen = null;
2740 this.preparingToClose = null;
2741 this.currentWindow = null;
2742 this.globalEvents = false;
2743 this.$ariaHidden = null;
2744 this.onWindowResizeTimeout = null;
2745 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2746 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2747
2748 // Initialization
2749 this.$element
2750 .addClass( 'oo-ui-windowManager' )
2751 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2752 };
2753
2754 /* Setup */
2755
2756 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2757 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2758
2759 /* Events */
2760
2761 /**
2762 * An 'opening' event is emitted when the window begins to be opened.
2763 *
2764 * @event opening
2765 * @param {OO.ui.Window} win Window that's being opened
2766 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2767 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2768 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2769 * @param {Object} data Window opening data
2770 */
2771
2772 /**
2773 * A 'closing' event is emitted when the window begins to be closed.
2774 *
2775 * @event closing
2776 * @param {OO.ui.Window} win Window that's being closed
2777 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2778 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2779 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2780 * is the closing data.
2781 * @param {Object} data Window closing data
2782 */
2783
2784 /**
2785 * A 'resize' event is emitted when a window is resized.
2786 *
2787 * @event resize
2788 * @param {OO.ui.Window} win Window that was resized
2789 */
2790
2791 /* Static Properties */
2792
2793 /**
2794 * Map of the symbolic name of each window size and its CSS properties.
2795 *
2796 * @static
2797 * @inheritable
2798 * @property {Object}
2799 */
2800 OO.ui.WindowManager.static.sizes = {
2801 small: {
2802 width: 300
2803 },
2804 medium: {
2805 width: 500
2806 },
2807 large: {
2808 width: 700
2809 },
2810 larger: {
2811 width: 900
2812 },
2813 full: {
2814 // These can be non-numeric because they are never used in calculations
2815 width: '100%',
2816 height: '100%'
2817 }
2818 };
2819
2820 /**
2821 * Symbolic name of the default window size.
2822 *
2823 * The default size is used if the window's requested size is not recognized.
2824 *
2825 * @static
2826 * @inheritable
2827 * @property {string}
2828 */
2829 OO.ui.WindowManager.static.defaultSize = 'medium';
2830
2831 /* Methods */
2832
2833 /**
2834 * Handle window resize events.
2835 *
2836 * @private
2837 * @param {jQuery.Event} e Window resize event
2838 */
2839 OO.ui.WindowManager.prototype.onWindowResize = function () {
2840 clearTimeout( this.onWindowResizeTimeout );
2841 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2842 };
2843
2844 /**
2845 * Handle window resize events.
2846 *
2847 * @private
2848 * @param {jQuery.Event} e Window resize event
2849 */
2850 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2851 if ( this.currentWindow ) {
2852 this.updateWindowSize( this.currentWindow );
2853 }
2854 };
2855
2856 /**
2857 * Check if window is opening.
2858 *
2859 * @return {boolean} Window is opening
2860 */
2861 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2862 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2863 };
2864
2865 /**
2866 * Check if window is closing.
2867 *
2868 * @return {boolean} Window is closing
2869 */
2870 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2871 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2872 };
2873
2874 /**
2875 * Check if window is opened.
2876 *
2877 * @return {boolean} Window is opened
2878 */
2879 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2880 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2881 };
2882
2883 /**
2884 * Check if a window is being managed.
2885 *
2886 * @param {OO.ui.Window} win Window to check
2887 * @return {boolean} Window is being managed
2888 */
2889 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2890 var name;
2891
2892 for ( name in this.windows ) {
2893 if ( this.windows[ name ] === win ) {
2894 return true;
2895 }
2896 }
2897
2898 return false;
2899 };
2900
2901 /**
2902 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2903 *
2904 * @param {OO.ui.Window} win Window being opened
2905 * @param {Object} [data] Window opening data
2906 * @return {number} Milliseconds to wait
2907 */
2908 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2909 return 0;
2910 };
2911
2912 /**
2913 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2914 *
2915 * @param {OO.ui.Window} win Window being opened
2916 * @param {Object} [data] Window opening data
2917 * @return {number} Milliseconds to wait
2918 */
2919 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2920 return 0;
2921 };
2922
2923 /**
2924 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2925 *
2926 * @param {OO.ui.Window} win Window being closed
2927 * @param {Object} [data] Window closing data
2928 * @return {number} Milliseconds to wait
2929 */
2930 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2931 return 0;
2932 };
2933
2934 /**
2935 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2936 * executing the ‘teardown’ process.
2937 *
2938 * @param {OO.ui.Window} win Window being closed
2939 * @param {Object} [data] Window closing data
2940 * @return {number} Milliseconds to wait
2941 */
2942 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2943 return this.modal ? 250 : 0;
2944 };
2945
2946 /**
2947 * Get a window by its symbolic name.
2948 *
2949 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2950 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2951 * for more information about using factories.
2952 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2953 *
2954 * @param {string} name Symbolic name of the window
2955 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2956 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2957 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2958 */
2959 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2960 var deferred = $.Deferred(),
2961 win = this.windows[ name ];
2962
2963 if ( !( win instanceof OO.ui.Window ) ) {
2964 if ( this.factory ) {
2965 if ( !this.factory.lookup( name ) ) {
2966 deferred.reject( new OO.ui.Error(
2967 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2968 ) );
2969 } else {
2970 win = this.factory.create( name );
2971 this.addWindows( [ win ] );
2972 deferred.resolve( win );
2973 }
2974 } else {
2975 deferred.reject( new OO.ui.Error(
2976 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2977 ) );
2978 }
2979 } else {
2980 deferred.resolve( win );
2981 }
2982
2983 return deferred.promise();
2984 };
2985
2986 /**
2987 * Get current window.
2988 *
2989 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2990 */
2991 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2992 return this.currentWindow;
2993 };
2994
2995 /**
2996 * Open a window.
2997 *
2998 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2999 * @param {Object} [data] Window opening data
3000 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3001 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3002 * @fires opening
3003 */
3004 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3005 var manager = this,
3006 opening = $.Deferred();
3007
3008 // Argument handling
3009 if ( typeof win === 'string' ) {
3010 return this.getWindow( win ).then( function ( win ) {
3011 return manager.openWindow( win, data );
3012 } );
3013 }
3014
3015 // Error handling
3016 if ( !this.hasWindow( win ) ) {
3017 opening.reject( new OO.ui.Error(
3018 'Cannot open window: window is not attached to manager'
3019 ) );
3020 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3021 opening.reject( new OO.ui.Error(
3022 'Cannot open window: another window is opening or open'
3023 ) );
3024 }
3025
3026 // Window opening
3027 if ( opening.state() !== 'rejected' ) {
3028 // If a window is currently closing, wait for it to complete
3029 this.preparingToOpen = $.when( this.closing );
3030 // Ensure handlers get called after preparingToOpen is set
3031 this.preparingToOpen.done( function () {
3032 if ( manager.modal ) {
3033 manager.toggleGlobalEvents( true );
3034 manager.toggleAriaIsolation( true );
3035 }
3036 manager.currentWindow = win;
3037 manager.opening = opening;
3038 manager.preparingToOpen = null;
3039 manager.emit( 'opening', win, opening, data );
3040 setTimeout( function () {
3041 win.setup( data ).then( function () {
3042 manager.updateWindowSize( win );
3043 manager.opening.notify( { state: 'setup' } );
3044 setTimeout( function () {
3045 win.ready( data ).then( function () {
3046 manager.opening.notify( { state: 'ready' } );
3047 manager.opening = null;
3048 manager.opened = $.Deferred();
3049 opening.resolve( manager.opened.promise(), data );
3050 } );
3051 }, manager.getReadyDelay() );
3052 } );
3053 }, manager.getSetupDelay() );
3054 } );
3055 }
3056
3057 return opening.promise();
3058 };
3059
3060 /**
3061 * Close a window.
3062 *
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3064 * @param {Object} [data] Window closing data
3065 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3066 * See {@link #event-closing 'closing' event} for more information about closing promises.
3067 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3068 * @fires closing
3069 */
3070 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3071 var manager = this,
3072 closing = $.Deferred(),
3073 opened;
3074
3075 // Argument handling
3076 if ( typeof win === 'string' ) {
3077 win = this.windows[ win ];
3078 } else if ( !this.hasWindow( win ) ) {
3079 win = null;
3080 }
3081
3082 // Error handling
3083 if ( !win ) {
3084 closing.reject( new OO.ui.Error(
3085 'Cannot close window: window is not attached to manager'
3086 ) );
3087 } else if ( win !== this.currentWindow ) {
3088 closing.reject( new OO.ui.Error(
3089 'Cannot close window: window already closed with different data'
3090 ) );
3091 } else if ( this.preparingToClose || this.closing ) {
3092 closing.reject( new OO.ui.Error(
3093 'Cannot close window: window already closing with different data'
3094 ) );
3095 }
3096
3097 // Window closing
3098 if ( closing.state() !== 'rejected' ) {
3099 // If the window is currently opening, close it when it's done
3100 this.preparingToClose = $.when( this.opening );
3101 // Ensure handlers get called after preparingToClose is set
3102 this.preparingToClose.done( function () {
3103 manager.closing = closing;
3104 manager.preparingToClose = null;
3105 manager.emit( 'closing', win, closing, data );
3106 opened = manager.opened;
3107 manager.opened = null;
3108 opened.resolve( closing.promise(), data );
3109 setTimeout( function () {
3110 win.hold( data ).then( function () {
3111 closing.notify( { state: 'hold' } );
3112 setTimeout( function () {
3113 win.teardown( data ).then( function () {
3114 closing.notify( { state: 'teardown' } );
3115 if ( manager.modal ) {
3116 manager.toggleGlobalEvents( false );
3117 manager.toggleAriaIsolation( false );
3118 }
3119 manager.closing = null;
3120 manager.currentWindow = null;
3121 closing.resolve( data );
3122 } );
3123 }, manager.getTeardownDelay() );
3124 } );
3125 }, manager.getHoldDelay() );
3126 } );
3127 }
3128
3129 return closing.promise();
3130 };
3131
3132 /**
3133 * Add windows to the window manager.
3134 *
3135 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3136 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3137 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3138 *
3139 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3140 * by reference, symbolic name, or explicitly defined symbolic names.
3141 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3142 * explicit nor a statically configured symbolic name.
3143 */
3144 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3145 var i, len, win, name, list;
3146
3147 if ( Array.isArray( windows ) ) {
3148 // Convert to map of windows by looking up symbolic names from static configuration
3149 list = {};
3150 for ( i = 0, len = windows.length; i < len; i++ ) {
3151 name = windows[ i ].constructor.static.name;
3152 if ( typeof name !== 'string' ) {
3153 throw new Error( 'Cannot add window' );
3154 }
3155 list[ name ] = windows[ i ];
3156 }
3157 } else if ( OO.isPlainObject( windows ) ) {
3158 list = windows;
3159 }
3160
3161 // Add windows
3162 for ( name in list ) {
3163 win = list[ name ];
3164 this.windows[ name ] = win.toggle( false );
3165 this.$element.append( win.$element );
3166 win.setManager( this );
3167 }
3168 };
3169
3170 /**
3171 * Remove the specified windows from the windows manager.
3172 *
3173 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3174 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3175 * longer listens to events, use the #destroy method.
3176 *
3177 * @param {string[]} names Symbolic names of windows to remove
3178 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3179 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3180 */
3181 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3182 var i, len, win, name, cleanupWindow,
3183 manager = this,
3184 promises = [],
3185 cleanup = function ( name, win ) {
3186 delete manager.windows[ name ];
3187 win.$element.detach();
3188 };
3189
3190 for ( i = 0, len = names.length; i < len; i++ ) {
3191 name = names[ i ];
3192 win = this.windows[ name ];
3193 if ( !win ) {
3194 throw new Error( 'Cannot remove window' );
3195 }
3196 cleanupWindow = cleanup.bind( null, name, win );
3197 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3198 }
3199
3200 return $.when.apply( $, promises );
3201 };
3202
3203 /**
3204 * Remove all windows from the window manager.
3205 *
3206 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3207 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3208 * To remove just a subset of windows, use the #removeWindows method.
3209 *
3210 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3211 */
3212 OO.ui.WindowManager.prototype.clearWindows = function () {
3213 return this.removeWindows( Object.keys( this.windows ) );
3214 };
3215
3216 /**
3217 * Set dialog size. In general, this method should not be called directly.
3218 *
3219 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3220 *
3221 * @chainable
3222 */
3223 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3224 // Bypass for non-current, and thus invisible, windows
3225 if ( win !== this.currentWindow ) {
3226 return;
3227 }
3228
3229 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3230 sizes = this.constructor.static.sizes,
3231 size = win.getSize();
3232
3233 if ( !sizes[ size ] ) {
3234 size = this.constructor.static.defaultSize;
3235 }
3236 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3237 size = 'full';
3238 }
3239
3240 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3241 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3242 win.setDimensions( sizes[ size ] );
3243
3244 this.emit( 'resize', win );
3245
3246 return this;
3247 };
3248
3249 /**
3250 * Bind or unbind global events for scrolling.
3251 *
3252 * @private
3253 * @param {boolean} [on] Bind global events
3254 * @chainable
3255 */
3256 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3257 on = on === undefined ? !!this.globalEvents : !!on;
3258
3259 var scrollWidth, bodyMargin,
3260 $body = $( this.getElementDocument().body ),
3261 // We could have multiple window managers open so only modify
3262 // the body css at the bottom of the stack
3263 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3264
3265 if ( on ) {
3266 if ( !this.globalEvents ) {
3267 $( this.getElementWindow() ).on( {
3268 // Start listening for top-level window dimension changes
3269 'orientationchange resize': this.onWindowResizeHandler
3270 } );
3271 if ( stackDepth === 0 ) {
3272 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3273 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3274 $body.css( {
3275 overflow: 'hidden',
3276 'margin-right': bodyMargin + scrollWidth
3277 } );
3278 }
3279 stackDepth++;
3280 this.globalEvents = true;
3281 }
3282 } else if ( this.globalEvents ) {
3283 $( this.getElementWindow() ).off( {
3284 // Stop listening for top-level window dimension changes
3285 'orientationchange resize': this.onWindowResizeHandler
3286 } );
3287 stackDepth--;
3288 if ( stackDepth === 0 ) {
3289 $body.css( {
3290 overflow: '',
3291 'margin-right': ''
3292 } );
3293 }
3294 this.globalEvents = false;
3295 }
3296 $body.data( 'windowManagerGlobalEvents', stackDepth );
3297
3298 return this;
3299 };
3300
3301 /**
3302 * Toggle screen reader visibility of content other than the window manager.
3303 *
3304 * @private
3305 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3306 * @chainable
3307 */
3308 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3309 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3310
3311 if ( isolate ) {
3312 if ( !this.$ariaHidden ) {
3313 // Hide everything other than the window manager from screen readers
3314 this.$ariaHidden = $( 'body' )
3315 .children()
3316 .not( this.$element.parentsUntil( 'body' ).last() )
3317 .attr( 'aria-hidden', '' );
3318 }
3319 } else if ( this.$ariaHidden ) {
3320 // Restore screen reader visibility
3321 this.$ariaHidden.removeAttr( 'aria-hidden' );
3322 this.$ariaHidden = null;
3323 }
3324
3325 return this;
3326 };
3327
3328 /**
3329 * Destroy the window manager.
3330 *
3331 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3332 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3333 * instead.
3334 */
3335 OO.ui.WindowManager.prototype.destroy = function () {
3336 this.toggleGlobalEvents( false );
3337 this.toggleAriaIsolation( false );
3338 this.clearWindows();
3339 this.$element.remove();
3340 };
3341
3342 /**
3343 * Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
3344 * in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
3345 * appearance and functionality of the error interface.
3346 *
3347 * The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
3348 * is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
3349 * that initiated the failed process will be disabled.
3350 *
3351 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
3352 * process again.
3353 *
3354 * For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
3355 *
3356 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
3357 *
3358 * @class
3359 *
3360 * @constructor
3361 * @param {string|jQuery} message Description of error
3362 * @param {Object} [config] Configuration options
3363 * @cfg {boolean} [recoverable=true] Error is recoverable.
3364 * By default, errors are recoverable, and users can try the process again.
3365 * @cfg {boolean} [warning=false] Error is a warning.
3366 * If the error is a warning, the error interface will include a
3367 * 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
3368 * is not triggered a second time if the user chooses to continue.
3369 */
3370 OO.ui.Error = function OoUiError( message, config ) {
3371 // Allow passing positional parameters inside the config object
3372 if ( OO.isPlainObject( message ) && config === undefined ) {
3373 config = message;
3374 message = config.message;
3375 }
3376
3377 // Configuration initialization
3378 config = config || {};
3379
3380 // Properties
3381 this.message = message instanceof jQuery ? message : String( message );
3382 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3383 this.warning = !!config.warning;
3384 };
3385
3386 /* Setup */
3387
3388 OO.initClass( OO.ui.Error );
3389
3390 /* Methods */
3391
3392 /**
3393 * Check if the error is recoverable.
3394 *
3395 * If the error is recoverable, users are able to try the process again.
3396 *
3397 * @return {boolean} Error is recoverable
3398 */
3399 OO.ui.Error.prototype.isRecoverable = function () {
3400 return this.recoverable;
3401 };
3402
3403 /**
3404 * Check if the error is a warning.
3405 *
3406 * If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
3407 *
3408 * @return {boolean} Error is warning
3409 */
3410 OO.ui.Error.prototype.isWarning = function () {
3411 return this.warning;
3412 };
3413
3414 /**
3415 * Get error message as DOM nodes.
3416 *
3417 * @return {jQuery} Error message in DOM nodes
3418 */
3419 OO.ui.Error.prototype.getMessage = function () {
3420 return this.message instanceof jQuery ?
3421 this.message.clone() :
3422 $( '<div>' ).text( this.message ).contents();
3423 };
3424
3425 /**
3426 * Get the error message text.
3427 *
3428 * @return {string} Error message
3429 */
3430 OO.ui.Error.prototype.getMessageText = function () {
3431 return this.message instanceof jQuery ? this.message.text() : this.message;
3432 };
3433
3434 /**
3435 * Wraps an HTML snippet for use with configuration values which default
3436 * to strings. This bypasses the default html-escaping done to string
3437 * values.
3438 *
3439 * @class
3440 *
3441 * @constructor
3442 * @param {string} [content] HTML content
3443 */
3444 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3445 // Properties
3446 this.content = content;
3447 };
3448
3449 /* Setup */
3450
3451 OO.initClass( OO.ui.HtmlSnippet );
3452
3453 /* Methods */
3454
3455 /**
3456 * Render into HTML.
3457 *
3458 * @return {string} Unchanged HTML snippet.
3459 */
3460 OO.ui.HtmlSnippet.prototype.toString = function () {
3461 return this.content;
3462 };
3463
3464 /**
3465 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3466 * or a function:
3467 *
3468 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3469 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3470 * or stop if the promise is rejected.
3471 * - **function**: the process will execute the function. The process will stop if the function returns
3472 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3473 * will wait for that number of milliseconds before proceeding.
3474 *
3475 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3476 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3477 * its remaining steps will not be performed.
3478 *
3479 * @class
3480 *
3481 * @constructor
3482 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3483 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3484 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3485 * a number or promise.
3486 * @return {Object} Step object, with `callback` and `context` properties
3487 */
3488 OO.ui.Process = function ( step, context ) {
3489 // Properties
3490 this.steps = [];
3491
3492 // Initialization
3493 if ( step !== undefined ) {
3494 this.next( step, context );
3495 }
3496 };
3497
3498 /* Setup */
3499
3500 OO.initClass( OO.ui.Process );
3501
3502 /* Methods */
3503
3504 /**
3505 * Start the process.
3506 *
3507 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3508 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3509 * and any remaining steps are not performed.
3510 */
3511 OO.ui.Process.prototype.execute = function () {
3512 var i, len, promise;
3513
3514 /**
3515 * Continue execution.
3516 *
3517 * @ignore
3518 * @param {Array} step A function and the context it should be called in
3519 * @return {Function} Function that continues the process
3520 */
3521 function proceed( step ) {
3522 return function () {
3523 // Execute step in the correct context
3524 var deferred,
3525 result = step.callback.call( step.context );
3526
3527 if ( result === false ) {
3528 // Use rejected promise for boolean false results
3529 return $.Deferred().reject( [] ).promise();
3530 }
3531 if ( typeof result === 'number' ) {
3532 if ( result < 0 ) {
3533 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3534 }
3535 // Use a delayed promise for numbers, expecting them to be in milliseconds
3536 deferred = $.Deferred();
3537 setTimeout( deferred.resolve, result );
3538 return deferred.promise();
3539 }
3540 if ( result instanceof OO.ui.Error ) {
3541 // Use rejected promise for error
3542 return $.Deferred().reject( [ result ] ).promise();
3543 }
3544 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3545 // Use rejected promise for list of errors
3546 return $.Deferred().reject( result ).promise();
3547 }
3548 // Duck-type the object to see if it can produce a promise
3549 if ( result && $.isFunction( result.promise ) ) {
3550 // Use a promise generated from the result
3551 return result.promise();
3552 }
3553 // Use resolved promise for other results
3554 return $.Deferred().resolve().promise();
3555 };
3556 }
3557
3558 if ( this.steps.length ) {
3559 // Generate a chain reaction of promises
3560 promise = proceed( this.steps[ 0 ] )();
3561 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3562 promise = promise.then( proceed( this.steps[ i ] ) );
3563 }
3564 } else {
3565 promise = $.Deferred().resolve().promise();
3566 }
3567
3568 return promise;
3569 };
3570
3571 /**
3572 * Create a process step.
3573 *
3574 * @private
3575 * @param {number|jQuery.Promise|Function} step
3576 *
3577 * - Number of milliseconds to wait before proceeding
3578 * - Promise that must be resolved before proceeding
3579 * - Function to execute
3580 * - If the function returns a boolean false the process will stop
3581 * - If the function returns a promise, the process will continue to the next
3582 * step when the promise is resolved or stop if the promise is rejected
3583 * - If the function returns a number, the process will wait for that number of
3584 * milliseconds before proceeding
3585 * @param {Object} [context=null] Execution context of the function. The context is
3586 * ignored if the step is a number or promise.
3587 * @return {Object} Step object, with `callback` and `context` properties
3588 */
3589 OO.ui.Process.prototype.createStep = function ( step, context ) {
3590 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3591 return {
3592 callback: function () {
3593 return step;
3594 },
3595 context: null
3596 };
3597 }
3598 if ( $.isFunction( step ) ) {
3599 return {
3600 callback: step,
3601 context: context
3602 };
3603 }
3604 throw new Error( 'Cannot create process step: number, promise or function expected' );
3605 };
3606
3607 /**
3608 * Add step to the beginning of the process.
3609 *
3610 * @inheritdoc #createStep
3611 * @return {OO.ui.Process} this
3612 * @chainable
3613 */
3614 OO.ui.Process.prototype.first = function ( step, context ) {
3615 this.steps.unshift( this.createStep( step, context ) );
3616 return this;
3617 };
3618
3619 /**
3620 * Add step to the end of the process.
3621 *
3622 * @inheritdoc #createStep
3623 * @return {OO.ui.Process} this
3624 * @chainable
3625 */
3626 OO.ui.Process.prototype.next = function ( step, context ) {
3627 this.steps.push( this.createStep( step, context ) );
3628 return this;
3629 };
3630
3631 /**
3632 * Factory for tools.
3633 *
3634 * @class
3635 * @extends OO.Factory
3636 * @constructor
3637 */
3638 OO.ui.ToolFactory = function OoUiToolFactory() {
3639 // Parent constructor
3640 OO.ui.ToolFactory.super.call( this );
3641 };
3642
3643 /* Setup */
3644
3645 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3646
3647 /* Methods */
3648
3649 /**
3650 * Get tools from the factory
3651 *
3652 * @param {Array} include Included tools
3653 * @param {Array} exclude Excluded tools
3654 * @param {Array} promote Promoted tools
3655 * @param {Array} demote Demoted tools
3656 * @return {string[]} List of tools
3657 */
3658 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3659 var i, len, included, promoted, demoted,
3660 auto = [],
3661 used = {};
3662
3663 // Collect included and not excluded tools
3664 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3665
3666 // Promotion
3667 promoted = this.extract( promote, used );
3668 demoted = this.extract( demote, used );
3669
3670 // Auto
3671 for ( i = 0, len = included.length; i < len; i++ ) {
3672 if ( !used[ included[ i ] ] ) {
3673 auto.push( included[ i ] );
3674 }
3675 }
3676
3677 return promoted.concat( auto ).concat( demoted );
3678 };
3679
3680 /**
3681 * Get a flat list of names from a list of names or groups.
3682 *
3683 * Tools can be specified in the following ways:
3684 *
3685 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3686 * - All tools in a group: `{ group: 'group-name' }`
3687 * - All tools: `'*'`
3688 *
3689 * @private
3690 * @param {Array|string} collection List of tools
3691 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3692 * names will be added as properties
3693 * @return {string[]} List of extracted names
3694 */
3695 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3696 var i, len, item, name, tool,
3697 names = [];
3698
3699 if ( collection === '*' ) {
3700 for ( name in this.registry ) {
3701 tool = this.registry[ name ];
3702 if (
3703 // Only add tools by group name when auto-add is enabled
3704 tool.static.autoAddToCatchall &&
3705 // Exclude already used tools
3706 ( !used || !used[ name ] )
3707 ) {
3708 names.push( name );
3709 if ( used ) {
3710 used[ name ] = true;
3711 }
3712 }
3713 }
3714 } else if ( Array.isArray( collection ) ) {
3715 for ( i = 0, len = collection.length; i < len; i++ ) {
3716 item = collection[ i ];
3717 // Allow plain strings as shorthand for named tools
3718 if ( typeof item === 'string' ) {
3719 item = { name: item };
3720 }
3721 if ( OO.isPlainObject( item ) ) {
3722 if ( item.group ) {
3723 for ( name in this.registry ) {
3724 tool = this.registry[ name ];
3725 if (
3726 // Include tools with matching group
3727 tool.static.group === item.group &&
3728 // Only add tools by group name when auto-add is enabled
3729 tool.static.autoAddToGroup &&
3730 // Exclude already used tools
3731 ( !used || !used[ name ] )
3732 ) {
3733 names.push( name );
3734 if ( used ) {
3735 used[ name ] = true;
3736 }
3737 }
3738 }
3739 // Include tools with matching name and exclude already used tools
3740 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3741 names.push( item.name );
3742 if ( used ) {
3743 used[ item.name ] = true;
3744 }
3745 }
3746 }
3747 }
3748 }
3749 return names;
3750 };
3751
3752 /**
3753 * Factory for tool groups.
3754 *
3755 * @class
3756 * @extends OO.Factory
3757 * @constructor
3758 */
3759 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3760 // Parent constructor
3761 OO.Factory.call( this );
3762
3763 var i, l,
3764 defaultClasses = this.constructor.static.getDefaultClasses();
3765
3766 // Register default toolgroups
3767 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3768 this.register( defaultClasses[ i ] );
3769 }
3770 };
3771
3772 /* Setup */
3773
3774 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3775
3776 /* Static Methods */
3777
3778 /**
3779 * Get a default set of classes to be registered on construction
3780 *
3781 * @return {Function[]} Default classes
3782 */
3783 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3784 return [
3785 OO.ui.BarToolGroup,
3786 OO.ui.ListToolGroup,
3787 OO.ui.MenuToolGroup
3788 ];
3789 };
3790
3791 /**
3792 * Theme logic.
3793 *
3794 * @abstract
3795 * @class
3796 *
3797 * @constructor
3798 * @param {Object} [config] Configuration options
3799 */
3800 OO.ui.Theme = function OoUiTheme( config ) {
3801 // Configuration initialization
3802 config = config || {};
3803 };
3804
3805 /* Setup */
3806
3807 OO.initClass( OO.ui.Theme );
3808
3809 /* Methods */
3810
3811 /**
3812 * Get a list of classes to be applied to a widget.
3813 *
3814 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3815 * otherwise state transitions will not work properly.
3816 *
3817 * @param {OO.ui.Element} element Element for which to get classes
3818 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3819 */
3820 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3821 return { on: [], off: [] };
3822 };
3823
3824 /**
3825 * Update CSS classes provided by the theme.
3826 *
3827 * For elements with theme logic hooks, this should be called any time there's a state change.
3828 *
3829 * @param {OO.ui.Element} element Element for which to update classes
3830 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3831 */
3832 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3833 var classes = this.getElementClasses( element );
3834
3835 element.$element
3836 .removeClass( classes.off.join( ' ' ) )
3837 .addClass( classes.on.join( ' ' ) );
3838 };
3839
3840 /**
3841 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3842 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3843 * order in which users will navigate through the focusable elements via the "tab" key.
3844 *
3845 * @example
3846 * // TabIndexedElement is mixed into the ButtonWidget class
3847 * // to provide a tabIndex property.
3848 * var button1 = new OO.ui.ButtonWidget( {
3849 * label: 'fourth',
3850 * tabIndex: 4
3851 * } );
3852 * var button2 = new OO.ui.ButtonWidget( {
3853 * label: 'second',
3854 * tabIndex: 2
3855 * } );
3856 * var button3 = new OO.ui.ButtonWidget( {
3857 * label: 'third',
3858 * tabIndex: 3
3859 * } );
3860 * var button4 = new OO.ui.ButtonWidget( {
3861 * label: 'first',
3862 * tabIndex: 1
3863 * } );
3864 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3865 *
3866 * @abstract
3867 * @class
3868 *
3869 * @constructor
3870 * @param {Object} [config] Configuration options
3871 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3872 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3873 * functionality will be applied to it instead.
3874 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3875 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3876 * to remove the element from the tab-navigation flow.
3877 */
3878 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3879 // Configuration initialization
3880 config = $.extend( { tabIndex: 0 }, config );
3881
3882 // Properties
3883 this.$tabIndexed = null;
3884 this.tabIndex = null;
3885
3886 // Events
3887 this.connect( this, { disable: 'onDisable' } );
3888
3889 // Initialization
3890 this.setTabIndex( config.tabIndex );
3891 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3892 };
3893
3894 /* Setup */
3895
3896 OO.initClass( OO.ui.TabIndexedElement );
3897
3898 /* Methods */
3899
3900 /**
3901 * Set the element that should use the tabindex functionality.
3902 *
3903 * This method is used to retarget a tabindex mixin so that its functionality applies
3904 * to the specified element. If an element is currently using the functionality, the mixin’s
3905 * effect on that element is removed before the new element is set up.
3906 *
3907 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3908 * @chainable
3909 */
3910 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3911 var tabIndex = this.tabIndex;
3912 // Remove attributes from old $tabIndexed
3913 this.setTabIndex( null );
3914 // Force update of new $tabIndexed
3915 this.$tabIndexed = $tabIndexed;
3916 this.tabIndex = tabIndex;
3917 return this.updateTabIndex();
3918 };
3919
3920 /**
3921 * Set the value of the tabindex.
3922 *
3923 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3924 * @chainable
3925 */
3926 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3927 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3928
3929 if ( this.tabIndex !== tabIndex ) {
3930 this.tabIndex = tabIndex;
3931 this.updateTabIndex();
3932 }
3933
3934 return this;
3935 };
3936
3937 /**
3938 * Update the `tabindex` attribute, in case of changes to tab index or
3939 * disabled state.
3940 *
3941 * @private
3942 * @chainable
3943 */
3944 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3945 if ( this.$tabIndexed ) {
3946 if ( this.tabIndex !== null ) {
3947 // Do not index over disabled elements
3948 this.$tabIndexed.attr( {
3949 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3950 // ChromeVox and NVDA do not seem to inherit this from parent elements
3951 'aria-disabled': this.isDisabled().toString()
3952 } );
3953 } else {
3954 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3955 }
3956 }
3957 return this;
3958 };
3959
3960 /**
3961 * Handle disable events.
3962 *
3963 * @private
3964 * @param {boolean} disabled Element is disabled
3965 */
3966 OO.ui.TabIndexedElement.prototype.onDisable = function () {
3967 this.updateTabIndex();
3968 };
3969
3970 /**
3971 * Get the value of the tabindex.
3972 *
3973 * @return {number|null} Tabindex value
3974 */
3975 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3976 return this.tabIndex;
3977 };
3978
3979 /**
3980 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3981 * interface element that can be configured with access keys for accessibility.
3982 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3983 *
3984 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3985 * @abstract
3986 * @class
3987 *
3988 * @constructor
3989 * @param {Object} [config] Configuration options
3990 * @cfg {jQuery} [$button] The button element created by the class.
3991 * If this configuration is omitted, the button element will use a generated `<a>`.
3992 * @cfg {boolean} [framed=true] Render the button with a frame
3993 * @cfg {string} [accessKey] Button's access key
3994 */
3995 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3996 // Configuration initialization
3997 config = config || {};
3998
3999 // Properties
4000 this.$button = null;
4001 this.framed = null;
4002 this.accessKey = null;
4003 this.active = false;
4004 this.onMouseUpHandler = this.onMouseUp.bind( this );
4005 this.onMouseDownHandler = this.onMouseDown.bind( this );
4006 this.onKeyDownHandler = this.onKeyDown.bind( this );
4007 this.onKeyUpHandler = this.onKeyUp.bind( this );
4008 this.onClickHandler = this.onClick.bind( this );
4009 this.onKeyPressHandler = this.onKeyPress.bind( this );
4010
4011 // Initialization
4012 this.$element.addClass( 'oo-ui-buttonElement' );
4013 this.toggleFramed( config.framed === undefined || config.framed );
4014 this.setAccessKey( config.accessKey );
4015 this.setButtonElement( config.$button || $( '<a>' ) );
4016 };
4017
4018 /* Setup */
4019
4020 OO.initClass( OO.ui.ButtonElement );
4021
4022 /* Static Properties */
4023
4024 /**
4025 * Cancel mouse down events.
4026 *
4027 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4028 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4029 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4030 * parent widget.
4031 *
4032 * @static
4033 * @inheritable
4034 * @property {boolean}
4035 */
4036 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
4037
4038 /* Events */
4039
4040 /**
4041 * A 'click' event is emitted when the button element is clicked.
4042 *
4043 * @event click
4044 */
4045
4046 /* Methods */
4047
4048 /**
4049 * Set the button element.
4050 *
4051 * This method is used to retarget a button mixin so that its functionality applies to
4052 * the specified button element instead of the one created by the class. If a button element
4053 * is already set, the method will remove the mixin’s effect on that element.
4054 *
4055 * @param {jQuery} $button Element to use as button
4056 */
4057 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4058 if ( this.$button ) {
4059 this.$button
4060 .removeClass( 'oo-ui-buttonElement-button' )
4061 .removeAttr( 'role accesskey' )
4062 .off( {
4063 mousedown: this.onMouseDownHandler,
4064 keydown: this.onKeyDownHandler,
4065 click: this.onClickHandler,
4066 keypress: this.onKeyPressHandler
4067 } );
4068 }
4069
4070 this.$button = $button
4071 .addClass( 'oo-ui-buttonElement-button' )
4072 .attr( { role: 'button', accesskey: this.accessKey } )
4073 .on( {
4074 mousedown: this.onMouseDownHandler,
4075 keydown: this.onKeyDownHandler,
4076 click: this.onClickHandler,
4077 keypress: this.onKeyPressHandler
4078 } );
4079 };
4080
4081 /**
4082 * Handles mouse down events.
4083 *
4084 * @protected
4085 * @param {jQuery.Event} e Mouse down event
4086 */
4087 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4088 if ( this.isDisabled() || e.which !== 1 ) {
4089 return;
4090 }
4091 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4092 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4093 // reliably remove the pressed class
4094 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4095 // Prevent change of focus unless specifically configured otherwise
4096 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4097 return false;
4098 }
4099 };
4100
4101 /**
4102 * Handles mouse up events.
4103 *
4104 * @protected
4105 * @param {jQuery.Event} e Mouse up event
4106 */
4107 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4108 if ( this.isDisabled() || e.which !== 1 ) {
4109 return;
4110 }
4111 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4112 // Stop listening for mouseup, since we only needed this once
4113 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4114 };
4115
4116 /**
4117 * Handles mouse click events.
4118 *
4119 * @protected
4120 * @param {jQuery.Event} e Mouse click event
4121 * @fires click
4122 */
4123 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4124 if ( !this.isDisabled() && e.which === 1 ) {
4125 this.emit( 'click' );
4126 }
4127 return false;
4128 };
4129
4130 /**
4131 * Handles key down events.
4132 *
4133 * @protected
4134 * @param {jQuery.Event} e Key down event
4135 */
4136 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4137 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4138 return;
4139 }
4140 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4141 // Run the keyup handler no matter where the key is when the button is let go, so we can
4142 // reliably remove the pressed class
4143 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4144 };
4145
4146 /**
4147 * Handles key up events.
4148 *
4149 * @protected
4150 * @param {jQuery.Event} e Key up event
4151 */
4152 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4153 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4154 return;
4155 }
4156 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4157 // Stop listening for keyup, since we only needed this once
4158 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4159 };
4160
4161 /**
4162 * Handles key press events.
4163 *
4164 * @protected
4165 * @param {jQuery.Event} e Key press event
4166 * @fires click
4167 */
4168 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4169 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4170 this.emit( 'click' );
4171 return false;
4172 }
4173 };
4174
4175 /**
4176 * Check if button has a frame.
4177 *
4178 * @return {boolean} Button is framed
4179 */
4180 OO.ui.ButtonElement.prototype.isFramed = function () {
4181 return this.framed;
4182 };
4183
4184 /**
4185 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4186 *
4187 * @param {boolean} [framed] Make button framed, omit to toggle
4188 * @chainable
4189 */
4190 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4191 framed = framed === undefined ? !this.framed : !!framed;
4192 if ( framed !== this.framed ) {
4193 this.framed = framed;
4194 this.$element
4195 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4196 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4197 this.updateThemeClasses();
4198 }
4199
4200 return this;
4201 };
4202
4203 /**
4204 * Set the button's access key.
4205 *
4206 * @param {string} accessKey Button's access key, use empty string to remove
4207 * @chainable
4208 */
4209 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4210 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4211
4212 if ( this.accessKey !== accessKey ) {
4213 if ( this.$button ) {
4214 if ( accessKey !== null ) {
4215 this.$button.attr( 'accesskey', accessKey );
4216 } else {
4217 this.$button.removeAttr( 'accesskey' );
4218 }
4219 }
4220 this.accessKey = accessKey;
4221 }
4222
4223 return this;
4224 };
4225
4226 /**
4227 * Set the button to its 'active' state.
4228 *
4229 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4230 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4231 * for other button types.
4232 *
4233 * @param {boolean} [value] Make button active
4234 * @chainable
4235 */
4236 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4237 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4238 return this;
4239 };
4240
4241 /**
4242 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4243 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4244 * items from the group is done through the interface the class provides.
4245 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4246 *
4247 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4248 *
4249 * @abstract
4250 * @class
4251 *
4252 * @constructor
4253 * @param {Object} [config] Configuration options
4254 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4255 * is omitted, the group element will use a generated `<div>`.
4256 */
4257 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4258 // Configuration initialization
4259 config = config || {};
4260
4261 // Properties
4262 this.$group = null;
4263 this.items = [];
4264 this.aggregateItemEvents = {};
4265
4266 // Initialization
4267 this.setGroupElement( config.$group || $( '<div>' ) );
4268 };
4269
4270 /* Methods */
4271
4272 /**
4273 * Set the group element.
4274 *
4275 * If an element is already set, items will be moved to the new element.
4276 *
4277 * @param {jQuery} $group Element to use as group
4278 */
4279 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4280 var i, len;
4281
4282 this.$group = $group;
4283 for ( i = 0, len = this.items.length; i < len; i++ ) {
4284 this.$group.append( this.items[ i ].$element );
4285 }
4286 };
4287
4288 /**
4289 * Check if a group contains no items.
4290 *
4291 * @return {boolean} Group is empty
4292 */
4293 OO.ui.GroupElement.prototype.isEmpty = function () {
4294 return !this.items.length;
4295 };
4296
4297 /**
4298 * Get all items in the group.
4299 *
4300 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4301 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4302 * from a group).
4303 *
4304 * @return {OO.ui.Element[]} An array of items.
4305 */
4306 OO.ui.GroupElement.prototype.getItems = function () {
4307 return this.items.slice( 0 );
4308 };
4309
4310 /**
4311 * Get an item by its data.
4312 *
4313 * Only the first item with matching data will be returned. To return all matching items,
4314 * use the #getItemsFromData method.
4315 *
4316 * @param {Object} data Item data to search for
4317 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4318 */
4319 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4320 var i, len, item,
4321 hash = OO.getHash( data );
4322
4323 for ( i = 0, len = this.items.length; i < len; i++ ) {
4324 item = this.items[ i ];
4325 if ( hash === OO.getHash( item.getData() ) ) {
4326 return item;
4327 }
4328 }
4329
4330 return null;
4331 };
4332
4333 /**
4334 * Get items by their data.
4335 *
4336 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4337 *
4338 * @param {Object} data Item data to search for
4339 * @return {OO.ui.Element[]} Items with equivalent data
4340 */
4341 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4342 var i, len, item,
4343 hash = OO.getHash( data ),
4344 items = [];
4345
4346 for ( i = 0, len = this.items.length; i < len; i++ ) {
4347 item = this.items[ i ];
4348 if ( hash === OO.getHash( item.getData() ) ) {
4349 items.push( item );
4350 }
4351 }
4352
4353 return items;
4354 };
4355
4356 /**
4357 * Aggregate the events emitted by the group.
4358 *
4359 * When events are aggregated, the group will listen to all contained items for the event,
4360 * and then emit the event under a new name. The new event will contain an additional leading
4361 * parameter containing the item that emitted the original event. Other arguments emitted from
4362 * the original event are passed through.
4363 *
4364 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4365 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4366 * A `null` value will remove aggregated events.
4367
4368 * @throws {Error} An error is thrown if aggregation already exists.
4369 */
4370 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4371 var i, len, item, add, remove, itemEvent, groupEvent;
4372
4373 for ( itemEvent in events ) {
4374 groupEvent = events[ itemEvent ];
4375
4376 // Remove existing aggregated event
4377 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4378 // Don't allow duplicate aggregations
4379 if ( groupEvent ) {
4380 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4381 }
4382 // Remove event aggregation from existing items
4383 for ( i = 0, len = this.items.length; i < len; i++ ) {
4384 item = this.items[ i ];
4385 if ( item.connect && item.disconnect ) {
4386 remove = {};
4387 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4388 item.disconnect( this, remove );
4389 }
4390 }
4391 // Prevent future items from aggregating event
4392 delete this.aggregateItemEvents[ itemEvent ];
4393 }
4394
4395 // Add new aggregate event
4396 if ( groupEvent ) {
4397 // Make future items aggregate event
4398 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4399 // Add event aggregation to existing items
4400 for ( i = 0, len = this.items.length; i < len; i++ ) {
4401 item = this.items[ i ];
4402 if ( item.connect && item.disconnect ) {
4403 add = {};
4404 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4405 item.connect( this, add );
4406 }
4407 }
4408 }
4409 }
4410 };
4411
4412 /**
4413 * Add items to the group.
4414 *
4415 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4416 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4417 *
4418 * @param {OO.ui.Element[]} items An array of items to add to the group
4419 * @param {number} [index] Index of the insertion point
4420 * @chainable
4421 */
4422 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4423 var i, len, item, event, events, currentIndex,
4424 itemElements = [];
4425
4426 for ( i = 0, len = items.length; i < len; i++ ) {
4427 item = items[ i ];
4428
4429 // Check if item exists then remove it first, effectively "moving" it
4430 currentIndex = $.inArray( item, this.items );
4431 if ( currentIndex >= 0 ) {
4432 this.removeItems( [ item ] );
4433 // Adjust index to compensate for removal
4434 if ( currentIndex < index ) {
4435 index--;
4436 }
4437 }
4438 // Add the item
4439 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4440 events = {};
4441 for ( event in this.aggregateItemEvents ) {
4442 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4443 }
4444 item.connect( this, events );
4445 }
4446 item.setElementGroup( this );
4447 itemElements.push( item.$element.get( 0 ) );
4448 }
4449
4450 if ( index === undefined || index < 0 || index >= this.items.length ) {
4451 this.$group.append( itemElements );
4452 this.items.push.apply( this.items, items );
4453 } else if ( index === 0 ) {
4454 this.$group.prepend( itemElements );
4455 this.items.unshift.apply( this.items, items );
4456 } else {
4457 this.items[ index ].$element.before( itemElements );
4458 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4459 }
4460
4461 return this;
4462 };
4463
4464 /**
4465 * Remove the specified items from a group.
4466 *
4467 * Removed items are detached (not removed) from the DOM so that they may be reused.
4468 * To remove all items from a group, you may wish to use the #clearItems method instead.
4469 *
4470 * @param {OO.ui.Element[]} items An array of items to remove
4471 * @chainable
4472 */
4473 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4474 var i, len, item, index, remove, itemEvent;
4475
4476 // Remove specific items
4477 for ( i = 0, len = items.length; i < len; i++ ) {
4478 item = items[ i ];
4479 index = $.inArray( item, this.items );
4480 if ( index !== -1 ) {
4481 if (
4482 item.connect && item.disconnect &&
4483 !$.isEmptyObject( this.aggregateItemEvents )
4484 ) {
4485 remove = {};
4486 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4487 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4488 }
4489 item.disconnect( this, remove );
4490 }
4491 item.setElementGroup( null );
4492 this.items.splice( index, 1 );
4493 item.$element.detach();
4494 }
4495 }
4496
4497 return this;
4498 };
4499
4500 /**
4501 * Clear all items from the group.
4502 *
4503 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4504 * To remove only a subset of items from a group, use the #removeItems method.
4505 *
4506 * @chainable
4507 */
4508 OO.ui.GroupElement.prototype.clearItems = function () {
4509 var i, len, item, remove, itemEvent;
4510
4511 // Remove all items
4512 for ( i = 0, len = this.items.length; i < len; i++ ) {
4513 item = this.items[ i ];
4514 if (
4515 item.connect && item.disconnect &&
4516 !$.isEmptyObject( this.aggregateItemEvents )
4517 ) {
4518 remove = {};
4519 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4520 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4521 }
4522 item.disconnect( this, remove );
4523 }
4524 item.setElementGroup( null );
4525 item.$element.detach();
4526 }
4527
4528 this.items = [];
4529 return this;
4530 };
4531
4532 /**
4533 * DraggableElement is a mixin class used to create elements that can be clicked
4534 * and dragged by a mouse to a new position within a group. This class must be used
4535 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4536 * the draggable elements.
4537 *
4538 * @abstract
4539 * @class
4540 *
4541 * @constructor
4542 */
4543 OO.ui.DraggableElement = function OoUiDraggableElement() {
4544 // Properties
4545 this.index = null;
4546
4547 // Initialize and events
4548 this.$element
4549 .attr( 'draggable', true )
4550 .addClass( 'oo-ui-draggableElement' )
4551 .on( {
4552 dragstart: this.onDragStart.bind( this ),
4553 dragover: this.onDragOver.bind( this ),
4554 dragend: this.onDragEnd.bind( this ),
4555 drop: this.onDrop.bind( this )
4556 } );
4557 };
4558
4559 OO.initClass( OO.ui.DraggableElement );
4560
4561 /* Events */
4562
4563 /**
4564 * @event dragstart
4565 *
4566 * A dragstart event is emitted when the user clicks and begins dragging an item.
4567 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4568 */
4569
4570 /**
4571 * @event dragend
4572 * A dragend event is emitted when the user drags an item and releases the mouse,
4573 * thus terminating the drag operation.
4574 */
4575
4576 /**
4577 * @event drop
4578 * A drop event is emitted when the user drags an item and then releases the mouse button
4579 * over a valid target.
4580 */
4581
4582 /* Static Properties */
4583
4584 /**
4585 * @inheritdoc OO.ui.ButtonElement
4586 */
4587 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4588
4589 /* Methods */
4590
4591 /**
4592 * Respond to dragstart event.
4593 *
4594 * @private
4595 * @param {jQuery.Event} event jQuery event
4596 * @fires dragstart
4597 */
4598 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4599 var dataTransfer = e.originalEvent.dataTransfer;
4600 // Define drop effect
4601 dataTransfer.dropEffect = 'none';
4602 dataTransfer.effectAllowed = 'move';
4603 // We must set up a dataTransfer data property or Firefox seems to
4604 // ignore the fact the element is draggable.
4605 try {
4606 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4607 } catch ( err ) {
4608 // The above is only for firefox. No need to set a catch clause
4609 // if it fails, move on.
4610 }
4611 // Add dragging class
4612 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4613 // Emit event
4614 this.emit( 'dragstart', this );
4615 return true;
4616 };
4617
4618 /**
4619 * Respond to dragend event.
4620 *
4621 * @private
4622 * @fires dragend
4623 */
4624 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4625 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4626 this.emit( 'dragend' );
4627 };
4628
4629 /**
4630 * Handle drop event.
4631 *
4632 * @private
4633 * @param {jQuery.Event} event jQuery event
4634 * @fires drop
4635 */
4636 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4637 e.preventDefault();
4638 this.emit( 'drop', e );
4639 };
4640
4641 /**
4642 * In order for drag/drop to work, the dragover event must
4643 * return false and stop propogation.
4644 *
4645 * @private
4646 */
4647 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4648 e.preventDefault();
4649 };
4650
4651 /**
4652 * Set item index.
4653 * Store it in the DOM so we can access from the widget drag event
4654 *
4655 * @private
4656 * @param {number} Item index
4657 */
4658 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4659 if ( this.index !== index ) {
4660 this.index = index;
4661 this.$element.data( 'index', index );
4662 }
4663 };
4664
4665 /**
4666 * Get item index
4667 *
4668 * @private
4669 * @return {number} Item index
4670 */
4671 OO.ui.DraggableElement.prototype.getIndex = function () {
4672 return this.index;
4673 };
4674
4675 /**
4676 * DraggableGroupElement is a mixin class used to create a group element to
4677 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4678 * The class is used with OO.ui.DraggableElement.
4679 *
4680 * @abstract
4681 * @class
4682 * @mixins OO.ui.GroupElement
4683 *
4684 * @constructor
4685 * @param {Object} [config] Configuration options
4686 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4687 * should match the layout of the items. Items displayed in a single row
4688 * or in several rows should use horizontal orientation. The vertical orientation should only be
4689 * used when the items are displayed in a single column. Defaults to 'vertical'
4690 */
4691 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4692 // Configuration initialization
4693 config = config || {};
4694
4695 // Parent constructor
4696 OO.ui.GroupElement.call( this, config );
4697
4698 // Properties
4699 this.orientation = config.orientation || 'vertical';
4700 this.dragItem = null;
4701 this.itemDragOver = null;
4702 this.itemKeys = {};
4703 this.sideInsertion = '';
4704
4705 // Events
4706 this.aggregate( {
4707 dragstart: 'itemDragStart',
4708 dragend: 'itemDragEnd',
4709 drop: 'itemDrop'
4710 } );
4711 this.connect( this, {
4712 itemDragStart: 'onItemDragStart',
4713 itemDrop: 'onItemDrop',
4714 itemDragEnd: 'onItemDragEnd'
4715 } );
4716 this.$element.on( {
4717 dragover: $.proxy( this.onDragOver, this ),
4718 dragleave: $.proxy( this.onDragLeave, this )
4719 } );
4720
4721 // Initialize
4722 if ( Array.isArray( config.items ) ) {
4723 this.addItems( config.items );
4724 }
4725 this.$placeholder = $( '<div>' )
4726 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4727 this.$element
4728 .addClass( 'oo-ui-draggableGroupElement' )
4729 .append( this.$status )
4730 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4731 .prepend( this.$placeholder );
4732 };
4733
4734 /* Setup */
4735 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4736
4737 /* Events */
4738
4739 /**
4740 * A 'reorder' event is emitted when the order of items in the group changes.
4741 *
4742 * @event reorder
4743 * @param {OO.ui.DraggableElement} item Reordered item
4744 * @param {number} [newIndex] New index for the item
4745 */
4746
4747 /* Methods */
4748
4749 /**
4750 * Respond to item drag start event
4751 *
4752 * @private
4753 * @param {OO.ui.DraggableElement} item Dragged item
4754 */
4755 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4756 var i, len;
4757
4758 // Map the index of each object
4759 for ( i = 0, len = this.items.length; i < len; i++ ) {
4760 this.items[ i ].setIndex( i );
4761 }
4762
4763 if ( this.orientation === 'horizontal' ) {
4764 // Set the height of the indicator
4765 this.$placeholder.css( {
4766 height: item.$element.outerHeight(),
4767 width: 2
4768 } );
4769 } else {
4770 // Set the width of the indicator
4771 this.$placeholder.css( {
4772 height: 2,
4773 width: item.$element.outerWidth()
4774 } );
4775 }
4776 this.setDragItem( item );
4777 };
4778
4779 /**
4780 * Respond to item drag end event
4781 *
4782 * @private
4783 */
4784 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4785 this.unsetDragItem();
4786 return false;
4787 };
4788
4789 /**
4790 * Handle drop event and switch the order of the items accordingly
4791 *
4792 * @private
4793 * @param {OO.ui.DraggableElement} item Dropped item
4794 * @fires reorder
4795 */
4796 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4797 var toIndex = item.getIndex();
4798 // Check if the dropped item is from the current group
4799 // TODO: Figure out a way to configure a list of legally droppable
4800 // elements even if they are not yet in the list
4801 if ( this.getDragItem() ) {
4802 // If the insertion point is 'after', the insertion index
4803 // is shifted to the right (or to the left in RTL, hence 'after')
4804 if ( this.sideInsertion === 'after' ) {
4805 toIndex++;
4806 }
4807 // Emit change event
4808 this.emit( 'reorder', this.getDragItem(), toIndex );
4809 }
4810 this.unsetDragItem();
4811 // Return false to prevent propogation
4812 return false;
4813 };
4814
4815 /**
4816 * Handle dragleave event.
4817 *
4818 * @private
4819 */
4820 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4821 // This means the item was dragged outside the widget
4822 this.$placeholder
4823 .css( 'left', 0 )
4824 .addClass( 'oo-ui-element-hidden' );
4825 };
4826
4827 /**
4828 * Respond to dragover event
4829 *
4830 * @private
4831 * @param {jQuery.Event} event Event details
4832 */
4833 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4834 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4835 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4836 clientX = e.originalEvent.clientX,
4837 clientY = e.originalEvent.clientY;
4838
4839 // Get the OptionWidget item we are dragging over
4840 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4841 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4842 if ( $optionWidget[ 0 ] ) {
4843 itemOffset = $optionWidget.offset();
4844 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4845 itemPosition = $optionWidget.position();
4846 itemIndex = $optionWidget.data( 'index' );
4847 }
4848
4849 if (
4850 itemOffset &&
4851 this.isDragging() &&
4852 itemIndex !== this.getDragItem().getIndex()
4853 ) {
4854 if ( this.orientation === 'horizontal' ) {
4855 // Calculate where the mouse is relative to the item width
4856 itemSize = itemBoundingRect.width;
4857 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4858 dragPosition = clientX;
4859 // Which side of the item we hover over will dictate
4860 // where the placeholder will appear, on the left or
4861 // on the right
4862 cssOutput = {
4863 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4864 top: itemPosition.top
4865 };
4866 } else {
4867 // Calculate where the mouse is relative to the item height
4868 itemSize = itemBoundingRect.height;
4869 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4870 dragPosition = clientY;
4871 // Which side of the item we hover over will dictate
4872 // where the placeholder will appear, on the top or
4873 // on the bottom
4874 cssOutput = {
4875 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4876 left: itemPosition.left
4877 };
4878 }
4879 // Store whether we are before or after an item to rearrange
4880 // For horizontal layout, we need to account for RTL, as this is flipped
4881 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4882 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4883 } else {
4884 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4885 }
4886 // Add drop indicator between objects
4887 this.$placeholder
4888 .css( cssOutput )
4889 .removeClass( 'oo-ui-element-hidden' );
4890 } else {
4891 // This means the item was dragged outside the widget
4892 this.$placeholder
4893 .css( 'left', 0 )
4894 .addClass( 'oo-ui-element-hidden' );
4895 }
4896 // Prevent default
4897 e.preventDefault();
4898 };
4899
4900 /**
4901 * Set a dragged item
4902 *
4903 * @param {OO.ui.DraggableElement} item Dragged item
4904 */
4905 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4906 this.dragItem = item;
4907 };
4908
4909 /**
4910 * Unset the current dragged item
4911 */
4912 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4913 this.dragItem = null;
4914 this.itemDragOver = null;
4915 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4916 this.sideInsertion = '';
4917 };
4918
4919 /**
4920 * Get the item that is currently being dragged.
4921 *
4922 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4923 */
4924 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4925 return this.dragItem;
4926 };
4927
4928 /**
4929 * Check if an item in the group is currently being dragged.
4930 *
4931 * @return {Boolean} Item is being dragged
4932 */
4933 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4934 return this.getDragItem() !== null;
4935 };
4936
4937 /**
4938 * IconElement is often mixed into other classes to generate an icon.
4939 * Icons are graphics, about the size of normal text. They are used to aid the user
4940 * in locating a control or to convey information in a space-efficient way. See the
4941 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4942 * included in the library.
4943 *
4944 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4945 *
4946 * @abstract
4947 * @class
4948 *
4949 * @constructor
4950 * @param {Object} [config] Configuration options
4951 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4952 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4953 * the icon element be set to an existing icon instead of the one generated by this class, set a
4954 * value using a jQuery selection. For example:
4955 *
4956 * // Use a <div> tag instead of a <span>
4957 * $icon: $("<div>")
4958 * // Use an existing icon element instead of the one generated by the class
4959 * $icon: this.$element
4960 * // Use an icon element from a child widget
4961 * $icon: this.childwidget.$element
4962 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4963 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4964 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4965 * by the user's language.
4966 *
4967 * Example of an i18n map:
4968 *
4969 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4970 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4971 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4972 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4973 * text. The icon title is displayed when users move the mouse over the icon.
4974 */
4975 OO.ui.IconElement = function OoUiIconElement( config ) {
4976 // Configuration initialization
4977 config = config || {};
4978
4979 // Properties
4980 this.$icon = null;
4981 this.icon = null;
4982 this.iconTitle = null;
4983
4984 // Initialization
4985 this.setIcon( config.icon || this.constructor.static.icon );
4986 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4987 this.setIconElement( config.$icon || $( '<span>' ) );
4988 };
4989
4990 /* Setup */
4991
4992 OO.initClass( OO.ui.IconElement );
4993
4994 /* Static Properties */
4995
4996 /**
4997 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4998 * for i18n purposes and contains a `default` icon name and additional names keyed by
4999 * language code. The `default` name is used when no icon is keyed by the user's language.
5000 *
5001 * Example of an i18n map:
5002 *
5003 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
5004 *
5005 * Note: the static property will be overridden if the #icon configuration is used.
5006 *
5007 * @static
5008 * @inheritable
5009 * @property {Object|string}
5010 */
5011 OO.ui.IconElement.static.icon = null;
5012
5013 /**
5014 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
5015 * function that returns title text, or `null` for no title.
5016 *
5017 * The static property will be overridden if the #iconTitle configuration is used.
5018 *
5019 * @static
5020 * @inheritable
5021 * @property {string|Function|null}
5022 */
5023 OO.ui.IconElement.static.iconTitle = null;
5024
5025 /* Methods */
5026
5027 /**
5028 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5029 * applies to the specified icon element instead of the one created by the class. If an icon
5030 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5031 * and mixin methods will no longer affect the element.
5032 *
5033 * @param {jQuery} $icon Element to use as icon
5034 */
5035 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5036 if ( this.$icon ) {
5037 this.$icon
5038 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5039 .removeAttr( 'title' );
5040 }
5041
5042 this.$icon = $icon
5043 .addClass( 'oo-ui-iconElement-icon' )
5044 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5045 if ( this.iconTitle !== null ) {
5046 this.$icon.attr( 'title', this.iconTitle );
5047 }
5048 };
5049
5050 /**
5051 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5052 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5053 * for an example.
5054 *
5055 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5056 * by language code, or `null` to remove the icon.
5057 * @chainable
5058 */
5059 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5060 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5061 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5062
5063 if ( this.icon !== icon ) {
5064 if ( this.$icon ) {
5065 if ( this.icon !== null ) {
5066 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5067 }
5068 if ( icon !== null ) {
5069 this.$icon.addClass( 'oo-ui-icon-' + icon );
5070 }
5071 }
5072 this.icon = icon;
5073 }
5074
5075 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5076 this.updateThemeClasses();
5077
5078 return this;
5079 };
5080
5081 /**
5082 * Set the icon title. Use `null` to remove the title.
5083 *
5084 * @param {string|Function|null} iconTitle A text string used as the icon title,
5085 * a function that returns title text, or `null` for no title.
5086 * @chainable
5087 */
5088 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5089 iconTitle = typeof iconTitle === 'function' ||
5090 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5091 OO.ui.resolveMsg( iconTitle ) : null;
5092
5093 if ( this.iconTitle !== iconTitle ) {
5094 this.iconTitle = iconTitle;
5095 if ( this.$icon ) {
5096 if ( this.iconTitle !== null ) {
5097 this.$icon.attr( 'title', iconTitle );
5098 } else {
5099 this.$icon.removeAttr( 'title' );
5100 }
5101 }
5102 }
5103
5104 return this;
5105 };
5106
5107 /**
5108 * Get the symbolic name of the icon.
5109 *
5110 * @return {string} Icon name
5111 */
5112 OO.ui.IconElement.prototype.getIcon = function () {
5113 return this.icon;
5114 };
5115
5116 /**
5117 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5118 *
5119 * @return {string} Icon title text
5120 */
5121 OO.ui.IconElement.prototype.getIconTitle = function () {
5122 return this.iconTitle;
5123 };
5124
5125 /**
5126 * IndicatorElement is often mixed into other classes to generate an indicator.
5127 * Indicators are small graphics that are generally used in two ways:
5128 *
5129 * - To draw attention to the status of an item. For example, an indicator might be
5130 * used to show that an item in a list has errors that need to be resolved.
5131 * - To clarify the function of a control that acts in an exceptional way (a button
5132 * that opens a menu instead of performing an action directly, for example).
5133 *
5134 * For a list of indicators included in the library, please see the
5135 * [OOjs UI documentation on MediaWiki] [1].
5136 *
5137 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5138 *
5139 * @abstract
5140 * @class
5141 *
5142 * @constructor
5143 * @param {Object} [config] Configuration options
5144 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5145 * configuration is omitted, the indicator element will use a generated `<span>`.
5146 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5147 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5148 * in the library.
5149 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5150 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5151 * or a function that returns title text. The indicator title is displayed when users move
5152 * the mouse over the indicator.
5153 */
5154 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5155 // Configuration initialization
5156 config = config || {};
5157
5158 // Properties
5159 this.$indicator = null;
5160 this.indicator = null;
5161 this.indicatorTitle = null;
5162
5163 // Initialization
5164 this.setIndicator( config.indicator || this.constructor.static.indicator );
5165 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5166 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5167 };
5168
5169 /* Setup */
5170
5171 OO.initClass( OO.ui.IndicatorElement );
5172
5173 /* Static Properties */
5174
5175 /**
5176 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5177 * The static property will be overridden if the #indicator configuration is used.
5178 *
5179 * @static
5180 * @inheritable
5181 * @property {string|null}
5182 */
5183 OO.ui.IndicatorElement.static.indicator = null;
5184
5185 /**
5186 * A text string used as the indicator title, a function that returns title text, or `null`
5187 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5188 *
5189 * @static
5190 * @inheritable
5191 * @property {string|Function|null}
5192 */
5193 OO.ui.IndicatorElement.static.indicatorTitle = null;
5194
5195 /* Methods */
5196
5197 /**
5198 * Set the indicator element.
5199 *
5200 * If an element is already set, it will be cleaned up before setting up the new element.
5201 *
5202 * @param {jQuery} $indicator Element to use as indicator
5203 */
5204 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5205 if ( this.$indicator ) {
5206 this.$indicator
5207 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5208 .removeAttr( 'title' );
5209 }
5210
5211 this.$indicator = $indicator
5212 .addClass( 'oo-ui-indicatorElement-indicator' )
5213 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5214 if ( this.indicatorTitle !== null ) {
5215 this.$indicator.attr( 'title', this.indicatorTitle );
5216 }
5217 };
5218
5219 /**
5220 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5221 *
5222 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5223 * @chainable
5224 */
5225 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5226 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5227
5228 if ( this.indicator !== indicator ) {
5229 if ( this.$indicator ) {
5230 if ( this.indicator !== null ) {
5231 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5232 }
5233 if ( indicator !== null ) {
5234 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5235 }
5236 }
5237 this.indicator = indicator;
5238 }
5239
5240 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5241 this.updateThemeClasses();
5242
5243 return this;
5244 };
5245
5246 /**
5247 * Set the indicator title.
5248 *
5249 * The title is displayed when a user moves the mouse over the indicator.
5250 *
5251 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5252 * `null` for no indicator title
5253 * @chainable
5254 */
5255 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5256 indicatorTitle = typeof indicatorTitle === 'function' ||
5257 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5258 OO.ui.resolveMsg( indicatorTitle ) : null;
5259
5260 if ( this.indicatorTitle !== indicatorTitle ) {
5261 this.indicatorTitle = indicatorTitle;
5262 if ( this.$indicator ) {
5263 if ( this.indicatorTitle !== null ) {
5264 this.$indicator.attr( 'title', indicatorTitle );
5265 } else {
5266 this.$indicator.removeAttr( 'title' );
5267 }
5268 }
5269 }
5270
5271 return this;
5272 };
5273
5274 /**
5275 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5276 *
5277 * @return {string} Symbolic name of indicator
5278 */
5279 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5280 return this.indicator;
5281 };
5282
5283 /**
5284 * Get the indicator title.
5285 *
5286 * The title is displayed when a user moves the mouse over the indicator.
5287 *
5288 * @return {string} Indicator title text
5289 */
5290 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5291 return this.indicatorTitle;
5292 };
5293
5294 /**
5295 * LabelElement is often mixed into other classes to generate a label, which
5296 * helps identify the function of an interface element.
5297 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5298 *
5299 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5300 *
5301 * @abstract
5302 * @class
5303 *
5304 * @constructor
5305 * @param {Object} [config] Configuration options
5306 * @cfg {jQuery} [$label] The label element created by the class. If this
5307 * configuration is omitted, the label element will use a generated `<span>`.
5308 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5309 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5310 * [OOjs UI documentation on MediaWiki] [2] for examples.
5311 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5312 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5313 * The label will be truncated to fit if necessary.
5314 */
5315 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5316 // Configuration initialization
5317 config = config || {};
5318
5319 // Properties
5320 this.$label = null;
5321 this.label = null;
5322 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5323
5324 // Initialization
5325 this.setLabel( config.label || this.constructor.static.label );
5326 this.setLabelElement( config.$label || $( '<span>' ) );
5327 };
5328
5329 /* Setup */
5330
5331 OO.initClass( OO.ui.LabelElement );
5332
5333 /* Events */
5334
5335 /**
5336 * @event labelChange
5337 * @param {string} value
5338 */
5339
5340 /* Static Properties */
5341
5342 /**
5343 * The label text. The label can be specified as a plaintext string, a function that will
5344 * produce a string in the future, or `null` for no label. The static value will
5345 * be overridden if a label is specified with the #label config option.
5346 *
5347 * @static
5348 * @inheritable
5349 * @property {string|Function|null}
5350 */
5351 OO.ui.LabelElement.static.label = null;
5352
5353 /* Methods */
5354
5355 /**
5356 * Set the label element.
5357 *
5358 * If an element is already set, it will be cleaned up before setting up the new element.
5359 *
5360 * @param {jQuery} $label Element to use as label
5361 */
5362 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5363 if ( this.$label ) {
5364 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5365 }
5366
5367 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5368 this.setLabelContent( this.label );
5369 };
5370
5371 /**
5372 * Set the label.
5373 *
5374 * An empty string will result in the label being hidden. A string containing only whitespace will
5375 * be converted to a single `&nbsp;`.
5376 *
5377 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5378 * text; or null for no label
5379 * @chainable
5380 */
5381 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5382 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5383 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5384
5385 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5386
5387 if ( this.label !== label ) {
5388 if ( this.$label ) {
5389 this.setLabelContent( label );
5390 }
5391 this.label = label;
5392 this.emit( 'labelChange' );
5393 }
5394
5395 return this;
5396 };
5397
5398 /**
5399 * Get the label.
5400 *
5401 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5402 * text; or null for no label
5403 */
5404 OO.ui.LabelElement.prototype.getLabel = function () {
5405 return this.label;
5406 };
5407
5408 /**
5409 * Fit the label.
5410 *
5411 * @chainable
5412 */
5413 OO.ui.LabelElement.prototype.fitLabel = function () {
5414 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5415 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5416 }
5417
5418 return this;
5419 };
5420
5421 /**
5422 * Set the content of the label.
5423 *
5424 * Do not call this method until after the label element has been set by #setLabelElement.
5425 *
5426 * @private
5427 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5428 * text; or null for no label
5429 */
5430 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5431 if ( typeof label === 'string' ) {
5432 if ( label.match( /^\s*$/ ) ) {
5433 // Convert whitespace only string to a single non-breaking space
5434 this.$label.html( '&nbsp;' );
5435 } else {
5436 this.$label.text( label );
5437 }
5438 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5439 this.$label.html( label.toString() );
5440 } else if ( label instanceof jQuery ) {
5441 this.$label.empty().append( label );
5442 } else {
5443 this.$label.empty();
5444 }
5445 };
5446
5447 /**
5448 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5449 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5450 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5451 * from the lookup menu, that value becomes the value of the input field.
5452 *
5453 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5454 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5455 * re-enable lookups.
5456 *
5457 * See the [OOjs UI demos][1] for an example.
5458 *
5459 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5460 *
5461 * @class
5462 * @abstract
5463 *
5464 * @constructor
5465 * @param {Object} [config] Configuration options
5466 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5467 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5468 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5469 * By default, the lookup menu is not generated and displayed until the user begins to type.
5470 */
5471 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5472 // Configuration initialization
5473 config = config || {};
5474
5475 // Properties
5476 this.$overlay = config.$overlay || this.$element;
5477 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5478 widget: this,
5479 input: this,
5480 $container: config.$container
5481 } );
5482
5483 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5484
5485 this.lookupCache = {};
5486 this.lookupQuery = null;
5487 this.lookupRequest = null;
5488 this.lookupsDisabled = false;
5489 this.lookupInputFocused = false;
5490
5491 // Events
5492 this.$input.on( {
5493 focus: this.onLookupInputFocus.bind( this ),
5494 blur: this.onLookupInputBlur.bind( this ),
5495 mousedown: this.onLookupInputMouseDown.bind( this )
5496 } );
5497 this.connect( this, { change: 'onLookupInputChange' } );
5498 this.lookupMenu.connect( this, {
5499 toggle: 'onLookupMenuToggle',
5500 choose: 'onLookupMenuItemChoose'
5501 } );
5502
5503 // Initialization
5504 this.$element.addClass( 'oo-ui-lookupElement' );
5505 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5506 this.$overlay.append( this.lookupMenu.$element );
5507 };
5508
5509 /* Methods */
5510
5511 /**
5512 * Handle input focus event.
5513 *
5514 * @protected
5515 * @param {jQuery.Event} e Input focus event
5516 */
5517 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5518 this.lookupInputFocused = true;
5519 this.populateLookupMenu();
5520 };
5521
5522 /**
5523 * Handle input blur event.
5524 *
5525 * @protected
5526 * @param {jQuery.Event} e Input blur event
5527 */
5528 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5529 this.closeLookupMenu();
5530 this.lookupInputFocused = false;
5531 };
5532
5533 /**
5534 * Handle input mouse down event.
5535 *
5536 * @protected
5537 * @param {jQuery.Event} e Input mouse down event
5538 */
5539 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5540 // Only open the menu if the input was already focused.
5541 // This way we allow the user to open the menu again after closing it with Esc
5542 // by clicking in the input. Opening (and populating) the menu when initially
5543 // clicking into the input is handled by the focus handler.
5544 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5545 this.populateLookupMenu();
5546 }
5547 };
5548
5549 /**
5550 * Handle input change event.
5551 *
5552 * @protected
5553 * @param {string} value New input value
5554 */
5555 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5556 if ( this.lookupInputFocused ) {
5557 this.populateLookupMenu();
5558 }
5559 };
5560
5561 /**
5562 * Handle the lookup menu being shown/hidden.
5563 *
5564 * @protected
5565 * @param {boolean} visible Whether the lookup menu is now visible.
5566 */
5567 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5568 if ( !visible ) {
5569 // When the menu is hidden, abort any active request and clear the menu.
5570 // This has to be done here in addition to closeLookupMenu(), because
5571 // MenuSelectWidget will close itself when the user presses Esc.
5572 this.abortLookupRequest();
5573 this.lookupMenu.clearItems();
5574 }
5575 };
5576
5577 /**
5578 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5579 *
5580 * @protected
5581 * @param {OO.ui.MenuOptionWidget} item Selected item
5582 */
5583 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5584 this.setValue( item.getData() );
5585 };
5586
5587 /**
5588 * Get lookup menu.
5589 *
5590 * @private
5591 * @return {OO.ui.TextInputMenuSelectWidget}
5592 */
5593 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5594 return this.lookupMenu;
5595 };
5596
5597 /**
5598 * Disable or re-enable lookups.
5599 *
5600 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5601 *
5602 * @param {boolean} disabled Disable lookups
5603 */
5604 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5605 this.lookupsDisabled = !!disabled;
5606 };
5607
5608 /**
5609 * Open the menu. If there are no entries in the menu, this does nothing.
5610 *
5611 * @private
5612 * @chainable
5613 */
5614 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5615 if ( !this.lookupMenu.isEmpty() ) {
5616 this.lookupMenu.toggle( true );
5617 }
5618 return this;
5619 };
5620
5621 /**
5622 * Close the menu, empty it, and abort any pending request.
5623 *
5624 * @private
5625 * @chainable
5626 */
5627 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5628 this.lookupMenu.toggle( false );
5629 this.abortLookupRequest();
5630 this.lookupMenu.clearItems();
5631 return this;
5632 };
5633
5634 /**
5635 * Request menu items based on the input's current value, and when they arrive,
5636 * populate the menu with these items and show the menu.
5637 *
5638 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5639 *
5640 * @private
5641 * @chainable
5642 */
5643 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5644 var widget = this,
5645 value = this.getValue();
5646
5647 if ( this.lookupsDisabled ) {
5648 return;
5649 }
5650
5651 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5652 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5653 this.closeLookupMenu();
5654 // Skip population if there is already a request pending for the current value
5655 } else if ( value !== this.lookupQuery ) {
5656 this.getLookupMenuItems()
5657 .done( function ( items ) {
5658 widget.lookupMenu.clearItems();
5659 if ( items.length ) {
5660 widget.lookupMenu
5661 .addItems( items )
5662 .toggle( true );
5663 widget.initializeLookupMenuSelection();
5664 } else {
5665 widget.lookupMenu.toggle( false );
5666 }
5667 } )
5668 .fail( function () {
5669 widget.lookupMenu.clearItems();
5670 } );
5671 }
5672
5673 return this;
5674 };
5675
5676 /**
5677 * Select and highlight the first selectable item in the menu.
5678 *
5679 * @private
5680 * @chainable
5681 */
5682 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5683 if ( !this.lookupMenu.getSelectedItem() ) {
5684 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5685 }
5686 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5687 };
5688
5689 /**
5690 * Get lookup menu items for the current query.
5691 *
5692 * @private
5693 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5694 * the done event. If the request was aborted to make way for a subsequent request, this promise
5695 * will not be rejected: it will remain pending forever.
5696 */
5697 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5698 var widget = this,
5699 value = this.getValue(),
5700 deferred = $.Deferred(),
5701 ourRequest;
5702
5703 this.abortLookupRequest();
5704 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5705 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5706 } else {
5707 this.pushPending();
5708 this.lookupQuery = value;
5709 ourRequest = this.lookupRequest = this.getLookupRequest();
5710 ourRequest
5711 .always( function () {
5712 // We need to pop pending even if this is an old request, otherwise
5713 // the widget will remain pending forever.
5714 // TODO: this assumes that an aborted request will fail or succeed soon after
5715 // being aborted, or at least eventually. It would be nice if we could popPending()
5716 // at abort time, but only if we knew that we hadn't already called popPending()
5717 // for that request.
5718 widget.popPending();
5719 } )
5720 .done( function ( response ) {
5721 // If this is an old request (and aborting it somehow caused it to still succeed),
5722 // ignore its success completely
5723 if ( ourRequest === widget.lookupRequest ) {
5724 widget.lookupQuery = null;
5725 widget.lookupRequest = null;
5726 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5727 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5728 }
5729 } )
5730 .fail( function () {
5731 // If this is an old request (or a request failing because it's being aborted),
5732 // ignore its failure completely
5733 if ( ourRequest === widget.lookupRequest ) {
5734 widget.lookupQuery = null;
5735 widget.lookupRequest = null;
5736 deferred.reject();
5737 }
5738 } );
5739 }
5740 return deferred.promise();
5741 };
5742
5743 /**
5744 * Abort the currently pending lookup request, if any.
5745 *
5746 * @private
5747 */
5748 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5749 var oldRequest = this.lookupRequest;
5750 if ( oldRequest ) {
5751 // First unset this.lookupRequest to the fail handler will notice
5752 // that the request is no longer current
5753 this.lookupRequest = null;
5754 this.lookupQuery = null;
5755 oldRequest.abort();
5756 }
5757 };
5758
5759 /**
5760 * Get a new request object of the current lookup query value.
5761 *
5762 * @protected
5763 * @abstract
5764 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5765 */
5766 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5767 // Stub, implemented in subclass
5768 return null;
5769 };
5770
5771 /**
5772 * Pre-process data returned by the request from #getLookupRequest.
5773 *
5774 * The return value of this function will be cached, and any further queries for the given value
5775 * will use the cache rather than doing API requests.
5776 *
5777 * @protected
5778 * @abstract
5779 * @param {Mixed} response Response from server
5780 * @return {Mixed} Cached result data
5781 */
5782 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5783 // Stub, implemented in subclass
5784 return [];
5785 };
5786
5787 /**
5788 * Get a list of menu option widgets from the (possibly cached) data returned by
5789 * #getLookupCacheDataFromResponse.
5790 *
5791 * @protected
5792 * @abstract
5793 * @param {Mixed} data Cached result data, usually an array
5794 * @return {OO.ui.MenuOptionWidget[]} Menu items
5795 */
5796 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5797 // Stub, implemented in subclass
5798 return [];
5799 };
5800
5801 /**
5802 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5803 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5804 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5805 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5806 *
5807 * @abstract
5808 * @class
5809 *
5810 * @constructor
5811 * @param {Object} [config] Configuration options
5812 * @cfg {Object} [popup] Configuration to pass to popup
5813 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5814 */
5815 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5816 // Configuration initialization
5817 config = config || {};
5818
5819 // Properties
5820 this.popup = new OO.ui.PopupWidget( $.extend(
5821 { autoClose: true },
5822 config.popup,
5823 { $autoCloseIgnore: this.$element }
5824 ) );
5825 };
5826
5827 /* Methods */
5828
5829 /**
5830 * Get popup.
5831 *
5832 * @return {OO.ui.PopupWidget} Popup widget
5833 */
5834 OO.ui.PopupElement.prototype.getPopup = function () {
5835 return this.popup;
5836 };
5837
5838 /**
5839 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5840 * additional functionality to an element created by another class. The class provides
5841 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5842 * which are used to customize the look and feel of a widget to better describe its
5843 * importance and functionality.
5844 *
5845 * The library currently contains the following styling flags for general use:
5846 *
5847 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5848 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5849 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5850 *
5851 * The flags affect the appearance of the buttons:
5852 *
5853 * @example
5854 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5855 * var button1 = new OO.ui.ButtonWidget( {
5856 * label: 'Constructive',
5857 * flags: 'constructive'
5858 * } );
5859 * var button2 = new OO.ui.ButtonWidget( {
5860 * label: 'Destructive',
5861 * flags: 'destructive'
5862 * } );
5863 * var button3 = new OO.ui.ButtonWidget( {
5864 * label: 'Progressive',
5865 * flags: 'progressive'
5866 * } );
5867 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5868 *
5869 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5870 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5871 *
5872 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5873 *
5874 * @abstract
5875 * @class
5876 *
5877 * @constructor
5878 * @param {Object} [config] Configuration options
5879 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5880 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5881 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5882 * @cfg {jQuery} [$flagged] The flagged element. By default,
5883 * the flagged functionality is applied to the element created by the class ($element).
5884 * If a different element is specified, the flagged functionality will be applied to it instead.
5885 */
5886 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5887 // Configuration initialization
5888 config = config || {};
5889
5890 // Properties
5891 this.flags = {};
5892 this.$flagged = null;
5893
5894 // Initialization
5895 this.setFlags( config.flags );
5896 this.setFlaggedElement( config.$flagged || this.$element );
5897 };
5898
5899 /* Events */
5900
5901 /**
5902 * @event flag
5903 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5904 * parameter contains the name of each modified flag and indicates whether it was
5905 * added or removed.
5906 *
5907 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5908 * that the flag was added, `false` that the flag was removed.
5909 */
5910
5911 /* Methods */
5912
5913 /**
5914 * Set the flagged element.
5915 *
5916 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5917 * If an element is already set, the method will remove the mixin’s effect on that element.
5918 *
5919 * @param {jQuery} $flagged Element that should be flagged
5920 */
5921 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5922 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5923 return 'oo-ui-flaggedElement-' + flag;
5924 } ).join( ' ' );
5925
5926 if ( this.$flagged ) {
5927 this.$flagged.removeClass( classNames );
5928 }
5929
5930 this.$flagged = $flagged.addClass( classNames );
5931 };
5932
5933 /**
5934 * Check if the specified flag is set.
5935 *
5936 * @param {string} flag Name of flag
5937 * @return {boolean} The flag is set
5938 */
5939 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5940 return flag in this.flags;
5941 };
5942
5943 /**
5944 * Get the names of all flags set.
5945 *
5946 * @return {string[]} Flag names
5947 */
5948 OO.ui.FlaggedElement.prototype.getFlags = function () {
5949 return Object.keys( this.flags );
5950 };
5951
5952 /**
5953 * Clear all flags.
5954 *
5955 * @chainable
5956 * @fires flag
5957 */
5958 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5959 var flag, className,
5960 changes = {},
5961 remove = [],
5962 classPrefix = 'oo-ui-flaggedElement-';
5963
5964 for ( flag in this.flags ) {
5965 className = classPrefix + flag;
5966 changes[ flag ] = false;
5967 delete this.flags[ flag ];
5968 remove.push( className );
5969 }
5970
5971 if ( this.$flagged ) {
5972 this.$flagged.removeClass( remove.join( ' ' ) );
5973 }
5974
5975 this.updateThemeClasses();
5976 this.emit( 'flag', changes );
5977
5978 return this;
5979 };
5980
5981 /**
5982 * Add one or more flags.
5983 *
5984 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5985 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5986 * be added (`true`) or removed (`false`).
5987 * @chainable
5988 * @fires flag
5989 */
5990 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5991 var i, len, flag, className,
5992 changes = {},
5993 add = [],
5994 remove = [],
5995 classPrefix = 'oo-ui-flaggedElement-';
5996
5997 if ( typeof flags === 'string' ) {
5998 className = classPrefix + flags;
5999 // Set
6000 if ( !this.flags[ flags ] ) {
6001 this.flags[ flags ] = true;
6002 add.push( className );
6003 }
6004 } else if ( Array.isArray( flags ) ) {
6005 for ( i = 0, len = flags.length; i < len; i++ ) {
6006 flag = flags[ i ];
6007 className = classPrefix + flag;
6008 // Set
6009 if ( !this.flags[ flag ] ) {
6010 changes[ flag ] = true;
6011 this.flags[ flag ] = true;
6012 add.push( className );
6013 }
6014 }
6015 } else if ( OO.isPlainObject( flags ) ) {
6016 for ( flag in flags ) {
6017 className = classPrefix + flag;
6018 if ( flags[ flag ] ) {
6019 // Set
6020 if ( !this.flags[ flag ] ) {
6021 changes[ flag ] = true;
6022 this.flags[ flag ] = true;
6023 add.push( className );
6024 }
6025 } else {
6026 // Remove
6027 if ( this.flags[ flag ] ) {
6028 changes[ flag ] = false;
6029 delete this.flags[ flag ];
6030 remove.push( className );
6031 }
6032 }
6033 }
6034 }
6035
6036 if ( this.$flagged ) {
6037 this.$flagged
6038 .addClass( add.join( ' ' ) )
6039 .removeClass( remove.join( ' ' ) );
6040 }
6041
6042 this.updateThemeClasses();
6043 this.emit( 'flag', changes );
6044
6045 return this;
6046 };
6047
6048 /**
6049 * TitledElement is mixed into other classes to provide a `title` attribute.
6050 * Titles are rendered by the browser and are made visible when the user moves
6051 * the mouse over the element. Titles are not visible on touch devices.
6052 *
6053 * @example
6054 * // TitledElement provides a 'title' attribute to the
6055 * // ButtonWidget class
6056 * var button = new OO.ui.ButtonWidget( {
6057 * label: 'Button with Title',
6058 * title: 'I am a button'
6059 * } );
6060 * $( 'body' ).append( button.$element );
6061 *
6062 * @abstract
6063 * @class
6064 *
6065 * @constructor
6066 * @param {Object} [config] Configuration options
6067 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6068 * If this config is omitted, the title functionality is applied to $element, the
6069 * element created by the class.
6070 * @cfg {string|Function} [title] The title text or a function that returns text. If
6071 * this config is omitted, the value of the {@link #static-title static title} property is used.
6072 */
6073 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6074 // Configuration initialization
6075 config = config || {};
6076
6077 // Properties
6078 this.$titled = null;
6079 this.title = null;
6080
6081 // Initialization
6082 this.setTitle( config.title || this.constructor.static.title );
6083 this.setTitledElement( config.$titled || this.$element );
6084 };
6085
6086 /* Setup */
6087
6088 OO.initClass( OO.ui.TitledElement );
6089
6090 /* Static Properties */
6091
6092 /**
6093 * The title text, a function that returns text, or `null` for no title. The value of the static property
6094 * is overridden if the #title config option is used.
6095 *
6096 * @static
6097 * @inheritable
6098 * @property {string|Function|null}
6099 */
6100 OO.ui.TitledElement.static.title = null;
6101
6102 /* Methods */
6103
6104 /**
6105 * Set the titled element.
6106 *
6107 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6108 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6109 *
6110 * @param {jQuery} $titled Element that should use the 'titled' functionality
6111 */
6112 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6113 if ( this.$titled ) {
6114 this.$titled.removeAttr( 'title' );
6115 }
6116
6117 this.$titled = $titled;
6118 if ( this.title ) {
6119 this.$titled.attr( 'title', this.title );
6120 }
6121 };
6122
6123 /**
6124 * Set title.
6125 *
6126 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6127 * @chainable
6128 */
6129 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6130 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6131
6132 if ( this.title !== title ) {
6133 if ( this.$titled ) {
6134 if ( title !== null ) {
6135 this.$titled.attr( 'title', title );
6136 } else {
6137 this.$titled.removeAttr( 'title' );
6138 }
6139 }
6140 this.title = title;
6141 }
6142
6143 return this;
6144 };
6145
6146 /**
6147 * Get title.
6148 *
6149 * @return {string} Title string
6150 */
6151 OO.ui.TitledElement.prototype.getTitle = function () {
6152 return this.title;
6153 };
6154
6155 /**
6156 * Element that can be automatically clipped to visible boundaries.
6157 *
6158 * Whenever the element's natural height changes, you have to call
6159 * #clip to make sure it's still clipping correctly.
6160 *
6161 * @abstract
6162 * @class
6163 *
6164 * @constructor
6165 * @param {Object} [config] Configuration options
6166 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6167 */
6168 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6169 // Configuration initialization
6170 config = config || {};
6171
6172 // Properties
6173 this.$clippable = null;
6174 this.clipping = false;
6175 this.clippedHorizontally = false;
6176 this.clippedVertically = false;
6177 this.$clippableContainer = null;
6178 this.$clippableScroller = null;
6179 this.$clippableWindow = null;
6180 this.idealWidth = null;
6181 this.idealHeight = null;
6182 this.onClippableContainerScrollHandler = this.clip.bind( this );
6183 this.onClippableWindowResizeHandler = this.clip.bind( this );
6184
6185 // Initialization
6186 this.setClippableElement( config.$clippable || this.$element );
6187 };
6188
6189 /* Methods */
6190
6191 /**
6192 * Set clippable element.
6193 *
6194 * If an element is already set, it will be cleaned up before setting up the new element.
6195 *
6196 * @param {jQuery} $clippable Element to make clippable
6197 */
6198 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6199 if ( this.$clippable ) {
6200 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6201 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6202 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6203 }
6204
6205 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6206 this.clip();
6207 };
6208
6209 /**
6210 * Toggle clipping.
6211 *
6212 * Do not turn clipping on until after the element is attached to the DOM and visible.
6213 *
6214 * @param {boolean} [clipping] Enable clipping, omit to toggle
6215 * @chainable
6216 */
6217 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6218 clipping = clipping === undefined ? !this.clipping : !!clipping;
6219
6220 if ( this.clipping !== clipping ) {
6221 this.clipping = clipping;
6222 if ( clipping ) {
6223 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6224 // If the clippable container is the root, we have to listen to scroll events and check
6225 // jQuery.scrollTop on the window because of browser inconsistencies
6226 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6227 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6228 this.$clippableContainer;
6229 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6230 this.$clippableWindow = $( this.getElementWindow() )
6231 .on( 'resize', this.onClippableWindowResizeHandler );
6232 // Initial clip after visible
6233 this.clip();
6234 } else {
6235 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6236 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6237
6238 this.$clippableContainer = null;
6239 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6240 this.$clippableScroller = null;
6241 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6242 this.$clippableWindow = null;
6243 }
6244 }
6245
6246 return this;
6247 };
6248
6249 /**
6250 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6251 *
6252 * @return {boolean} Element will be clipped to the visible area
6253 */
6254 OO.ui.ClippableElement.prototype.isClipping = function () {
6255 return this.clipping;
6256 };
6257
6258 /**
6259 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6260 *
6261 * @return {boolean} Part of the element is being clipped
6262 */
6263 OO.ui.ClippableElement.prototype.isClipped = function () {
6264 return this.clippedHorizontally || this.clippedVertically;
6265 };
6266
6267 /**
6268 * Check if the right of the element is being clipped by the nearest scrollable container.
6269 *
6270 * @return {boolean} Part of the element is being clipped
6271 */
6272 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6273 return this.clippedHorizontally;
6274 };
6275
6276 /**
6277 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6278 *
6279 * @return {boolean} Part of the element is being clipped
6280 */
6281 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6282 return this.clippedVertically;
6283 };
6284
6285 /**
6286 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6287 *
6288 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6289 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6290 */
6291 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6292 this.idealWidth = width;
6293 this.idealHeight = height;
6294
6295 if ( !this.clipping ) {
6296 // Update dimensions
6297 this.$clippable.css( { width: width, height: height } );
6298 }
6299 // While clipping, idealWidth and idealHeight are not considered
6300 };
6301
6302 /**
6303 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6304 * the element's natural height changes.
6305 *
6306 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6307 * overlapped by, the visible area of the nearest scrollable container.
6308 *
6309 * @chainable
6310 */
6311 OO.ui.ClippableElement.prototype.clip = function () {
6312 if ( !this.clipping ) {
6313 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6314 return this;
6315 }
6316
6317 var buffer = 7, // Chosen by fair dice roll
6318 cOffset = this.$clippable.offset(),
6319 $container = this.$clippableContainer.is( 'html, body' ) ?
6320 this.$clippableWindow : this.$clippableContainer,
6321 ccOffset = $container.offset() || { top: 0, left: 0 },
6322 ccHeight = $container.innerHeight() - buffer,
6323 ccWidth = $container.innerWidth() - buffer,
6324 cHeight = this.$clippable.outerHeight() + buffer,
6325 cWidth = this.$clippable.outerWidth() + buffer,
6326 scrollTop = this.$clippableScroller.scrollTop(),
6327 scrollLeft = this.$clippableScroller.scrollLeft(),
6328 desiredWidth = cOffset.left < 0 ?
6329 cWidth + cOffset.left :
6330 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6331 desiredHeight = cOffset.top < 0 ?
6332 cHeight + cOffset.top :
6333 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6334 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6335 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6336 clipWidth = desiredWidth < naturalWidth,
6337 clipHeight = desiredHeight < naturalHeight;
6338
6339 if ( clipWidth ) {
6340 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6341 } else {
6342 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6343 }
6344 if ( clipHeight ) {
6345 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6346 } else {
6347 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6348 }
6349
6350 // If we stopped clipping in at least one of the dimensions
6351 if ( !clipWidth || !clipHeight ) {
6352 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6353 }
6354
6355 this.clippedHorizontally = clipWidth;
6356 this.clippedVertically = clipHeight;
6357
6358 return this;
6359 };
6360
6361 /**
6362 * Generic toolbar tool.
6363 *
6364 * @abstract
6365 * @class
6366 * @extends OO.ui.Widget
6367 * @mixins OO.ui.IconElement
6368 * @mixins OO.ui.FlaggedElement
6369 *
6370 * @constructor
6371 * @param {OO.ui.ToolGroup} toolGroup
6372 * @param {Object} [config] Configuration options
6373 * @cfg {string|Function} [title] Title text or a function that returns text
6374 */
6375 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6376 // Allow passing positional parameters inside the config object
6377 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6378 config = toolGroup;
6379 toolGroup = config.toolGroup;
6380 }
6381
6382 // Configuration initialization
6383 config = config || {};
6384
6385 // Parent constructor
6386 OO.ui.Tool.super.call( this, config );
6387
6388 // Mixin constructors
6389 OO.ui.IconElement.call( this, config );
6390 OO.ui.FlaggedElement.call( this, config );
6391
6392 // Properties
6393 this.toolGroup = toolGroup;
6394 this.toolbar = this.toolGroup.getToolbar();
6395 this.active = false;
6396 this.$title = $( '<span>' );
6397 this.$accel = $( '<span>' );
6398 this.$link = $( '<a>' );
6399 this.title = null;
6400
6401 // Events
6402 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6403
6404 // Initialization
6405 this.$title.addClass( 'oo-ui-tool-title' );
6406 this.$accel
6407 .addClass( 'oo-ui-tool-accel' )
6408 .prop( {
6409 // This may need to be changed if the key names are ever localized,
6410 // but for now they are essentially written in English
6411 dir: 'ltr',
6412 lang: 'en'
6413 } );
6414 this.$link
6415 .addClass( 'oo-ui-tool-link' )
6416 .append( this.$icon, this.$title, this.$accel )
6417 .prop( 'tabIndex', 0 )
6418 .attr( 'role', 'button' );
6419 this.$element
6420 .data( 'oo-ui-tool', this )
6421 .addClass(
6422 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6423 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6424 )
6425 .append( this.$link );
6426 this.setTitle( config.title || this.constructor.static.title );
6427 };
6428
6429 /* Setup */
6430
6431 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6432 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6433 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6434
6435 /* Events */
6436
6437 /**
6438 * @event select
6439 */
6440
6441 /* Static Properties */
6442
6443 /**
6444 * @static
6445 * @inheritdoc
6446 */
6447 OO.ui.Tool.static.tagName = 'span';
6448
6449 /**
6450 * Symbolic name of tool.
6451 *
6452 * @abstract
6453 * @static
6454 * @inheritable
6455 * @property {string}
6456 */
6457 OO.ui.Tool.static.name = '';
6458
6459 /**
6460 * Tool group.
6461 *
6462 * @abstract
6463 * @static
6464 * @inheritable
6465 * @property {string}
6466 */
6467 OO.ui.Tool.static.group = '';
6468
6469 /**
6470 * Tool title.
6471 *
6472 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6473 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6474 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6475 * appended to the title if the tool is part of a bar tool group.
6476 *
6477 * @abstract
6478 * @static
6479 * @inheritable
6480 * @property {string|Function} Title text or a function that returns text
6481 */
6482 OO.ui.Tool.static.title = '';
6483
6484 /**
6485 * Tool can be automatically added to catch-all groups.
6486 *
6487 * @static
6488 * @inheritable
6489 * @property {boolean}
6490 */
6491 OO.ui.Tool.static.autoAddToCatchall = true;
6492
6493 /**
6494 * Tool can be automatically added to named groups.
6495 *
6496 * @static
6497 * @property {boolean}
6498 * @inheritable
6499 */
6500 OO.ui.Tool.static.autoAddToGroup = true;
6501
6502 /**
6503 * Check if this tool is compatible with given data.
6504 *
6505 * @static
6506 * @inheritable
6507 * @param {Mixed} data Data to check
6508 * @return {boolean} Tool can be used with data
6509 */
6510 OO.ui.Tool.static.isCompatibleWith = function () {
6511 return false;
6512 };
6513
6514 /* Methods */
6515
6516 /**
6517 * Handle the toolbar state being updated.
6518 *
6519 * This is an abstract method that must be overridden in a concrete subclass.
6520 *
6521 * @abstract
6522 */
6523 OO.ui.Tool.prototype.onUpdateState = function () {
6524 throw new Error(
6525 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6526 );
6527 };
6528
6529 /**
6530 * Handle the tool being selected.
6531 *
6532 * This is an abstract method that must be overridden in a concrete subclass.
6533 *
6534 * @abstract
6535 */
6536 OO.ui.Tool.prototype.onSelect = function () {
6537 throw new Error(
6538 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6539 );
6540 };
6541
6542 /**
6543 * Check if the button is active.
6544 *
6545 * @return {boolean} Button is active
6546 */
6547 OO.ui.Tool.prototype.isActive = function () {
6548 return this.active;
6549 };
6550
6551 /**
6552 * Make the button appear active or inactive.
6553 *
6554 * @param {boolean} state Make button appear active
6555 */
6556 OO.ui.Tool.prototype.setActive = function ( state ) {
6557 this.active = !!state;
6558 if ( this.active ) {
6559 this.$element.addClass( 'oo-ui-tool-active' );
6560 } else {
6561 this.$element.removeClass( 'oo-ui-tool-active' );
6562 }
6563 };
6564
6565 /**
6566 * Get the tool title.
6567 *
6568 * @param {string|Function} title Title text or a function that returns text
6569 * @chainable
6570 */
6571 OO.ui.Tool.prototype.setTitle = function ( title ) {
6572 this.title = OO.ui.resolveMsg( title );
6573 this.updateTitle();
6574 return this;
6575 };
6576
6577 /**
6578 * Get the tool title.
6579 *
6580 * @return {string} Title text
6581 */
6582 OO.ui.Tool.prototype.getTitle = function () {
6583 return this.title;
6584 };
6585
6586 /**
6587 * Get the tool's symbolic name.
6588 *
6589 * @return {string} Symbolic name of tool
6590 */
6591 OO.ui.Tool.prototype.getName = function () {
6592 return this.constructor.static.name;
6593 };
6594
6595 /**
6596 * Update the title.
6597 */
6598 OO.ui.Tool.prototype.updateTitle = function () {
6599 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6600 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6601 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6602 tooltipParts = [];
6603
6604 this.$title.text( this.title );
6605 this.$accel.text( accel );
6606
6607 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6608 tooltipParts.push( this.title );
6609 }
6610 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6611 tooltipParts.push( accel );
6612 }
6613 if ( tooltipParts.length ) {
6614 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6615 } else {
6616 this.$link.removeAttr( 'title' );
6617 }
6618 };
6619
6620 /**
6621 * Destroy tool.
6622 */
6623 OO.ui.Tool.prototype.destroy = function () {
6624 this.toolbar.disconnect( this );
6625 this.$element.remove();
6626 };
6627
6628 /**
6629 * Collection of tool groups.
6630 *
6631 * @class
6632 * @extends OO.ui.Element
6633 * @mixins OO.EventEmitter
6634 * @mixins OO.ui.GroupElement
6635 *
6636 * @constructor
6637 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6638 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6639 * @param {Object} [config] Configuration options
6640 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6641 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6642 */
6643 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6644 // Allow passing positional parameters inside the config object
6645 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6646 config = toolFactory;
6647 toolFactory = config.toolFactory;
6648 toolGroupFactory = config.toolGroupFactory;
6649 }
6650
6651 // Configuration initialization
6652 config = config || {};
6653
6654 // Parent constructor
6655 OO.ui.Toolbar.super.call( this, config );
6656
6657 // Mixin constructors
6658 OO.EventEmitter.call( this );
6659 OO.ui.GroupElement.call( this, config );
6660
6661 // Properties
6662 this.toolFactory = toolFactory;
6663 this.toolGroupFactory = toolGroupFactory;
6664 this.groups = [];
6665 this.tools = {};
6666 this.$bar = $( '<div>' );
6667 this.$actions = $( '<div>' );
6668 this.initialized = false;
6669 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6670
6671 // Events
6672 this.$element
6673 .add( this.$bar ).add( this.$group ).add( this.$actions )
6674 .on( 'mousedown', this.onPointerDown.bind( this ) );
6675
6676 // Initialization
6677 this.$group.addClass( 'oo-ui-toolbar-tools' );
6678 if ( config.actions ) {
6679 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6680 }
6681 this.$bar
6682 .addClass( 'oo-ui-toolbar-bar' )
6683 .append( this.$group, '<div style="clear:both"></div>' );
6684 if ( config.shadow ) {
6685 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6686 }
6687 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6688 };
6689
6690 /* Setup */
6691
6692 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6693 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6694 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6695
6696 /* Methods */
6697
6698 /**
6699 * Get the tool factory.
6700 *
6701 * @return {OO.ui.ToolFactory} Tool factory
6702 */
6703 OO.ui.Toolbar.prototype.getToolFactory = function () {
6704 return this.toolFactory;
6705 };
6706
6707 /**
6708 * Get the tool group factory.
6709 *
6710 * @return {OO.Factory} Tool group factory
6711 */
6712 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6713 return this.toolGroupFactory;
6714 };
6715
6716 /**
6717 * Handles mouse down events.
6718 *
6719 * @param {jQuery.Event} e Mouse down event
6720 */
6721 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6722 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6723 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6724 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6725 return false;
6726 }
6727 };
6728
6729 /**
6730 * Handle window resize event.
6731 *
6732 * @private
6733 * @param {jQuery.Event} e Window resize event
6734 */
6735 OO.ui.Toolbar.prototype.onWindowResize = function () {
6736 this.$element.toggleClass(
6737 'oo-ui-toolbar-narrow',
6738 this.$bar.width() <= this.narrowThreshold
6739 );
6740 };
6741
6742 /**
6743 * Sets up handles and preloads required information for the toolbar to work.
6744 * This must be called after it is attached to a visible document and before doing anything else.
6745 */
6746 OO.ui.Toolbar.prototype.initialize = function () {
6747 this.initialized = true;
6748 this.narrowThreshold = this.$group.width() + this.$actions.width();
6749 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6750 this.onWindowResize();
6751 };
6752
6753 /**
6754 * Setup toolbar.
6755 *
6756 * Tools can be specified in the following ways:
6757 *
6758 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6759 * - All tools in a group: `{ group: 'group-name' }`
6760 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6761 *
6762 * @param {Object.<string,Array>} groups List of tool group configurations
6763 * @param {Array|string} [groups.include] Tools to include
6764 * @param {Array|string} [groups.exclude] Tools to exclude
6765 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6766 * @param {Array|string} [groups.demote] Tools to demote to the end
6767 */
6768 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6769 var i, len, type, group,
6770 items = [],
6771 defaultType = 'bar';
6772
6773 // Cleanup previous groups
6774 this.reset();
6775
6776 // Build out new groups
6777 for ( i = 0, len = groups.length; i < len; i++ ) {
6778 group = groups[ i ];
6779 if ( group.include === '*' ) {
6780 // Apply defaults to catch-all groups
6781 if ( group.type === undefined ) {
6782 group.type = 'list';
6783 }
6784 if ( group.label === undefined ) {
6785 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6786 }
6787 }
6788 // Check type has been registered
6789 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6790 items.push(
6791 this.getToolGroupFactory().create( type, this, group )
6792 );
6793 }
6794 this.addItems( items );
6795 };
6796
6797 /**
6798 * Remove all tools and groups from the toolbar.
6799 */
6800 OO.ui.Toolbar.prototype.reset = function () {
6801 var i, len;
6802
6803 this.groups = [];
6804 this.tools = {};
6805 for ( i = 0, len = this.items.length; i < len; i++ ) {
6806 this.items[ i ].destroy();
6807 }
6808 this.clearItems();
6809 };
6810
6811 /**
6812 * Destroys toolbar, removing event handlers and DOM elements.
6813 *
6814 * Call this whenever you are done using a toolbar.
6815 */
6816 OO.ui.Toolbar.prototype.destroy = function () {
6817 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
6818 this.reset();
6819 this.$element.remove();
6820 };
6821
6822 /**
6823 * Check if tool has not been used yet.
6824 *
6825 * @param {string} name Symbolic name of tool
6826 * @return {boolean} Tool is available
6827 */
6828 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6829 return !this.tools[ name ];
6830 };
6831
6832 /**
6833 * Prevent tool from being used again.
6834 *
6835 * @param {OO.ui.Tool} tool Tool to reserve
6836 */
6837 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6838 this.tools[ tool.getName() ] = tool;
6839 };
6840
6841 /**
6842 * Allow tool to be used again.
6843 *
6844 * @param {OO.ui.Tool} tool Tool to release
6845 */
6846 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6847 delete this.tools[ tool.getName() ];
6848 };
6849
6850 /**
6851 * Get accelerator label for tool.
6852 *
6853 * This is a stub that should be overridden to provide access to accelerator information.
6854 *
6855 * @param {string} name Symbolic name of tool
6856 * @return {string|undefined} Tool accelerator label if available
6857 */
6858 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6859 return undefined;
6860 };
6861
6862 /**
6863 * Collection of tools.
6864 *
6865 * Tools can be specified in the following ways:
6866 *
6867 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6868 * - All tools in a group: `{ group: 'group-name' }`
6869 * - All tools: `'*'`
6870 *
6871 * @abstract
6872 * @class
6873 * @extends OO.ui.Widget
6874 * @mixins OO.ui.GroupElement
6875 *
6876 * @constructor
6877 * @param {OO.ui.Toolbar} toolbar
6878 * @param {Object} [config] Configuration options
6879 * @cfg {Array|string} [include=[]] List of tools to include
6880 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6881 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6882 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6883 */
6884 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6885 // Allow passing positional parameters inside the config object
6886 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
6887 config = toolbar;
6888 toolbar = config.toolbar;
6889 }
6890
6891 // Configuration initialization
6892 config = config || {};
6893
6894 // Parent constructor
6895 OO.ui.ToolGroup.super.call( this, config );
6896
6897 // Mixin constructors
6898 OO.ui.GroupElement.call( this, config );
6899
6900 // Properties
6901 this.toolbar = toolbar;
6902 this.tools = {};
6903 this.pressed = null;
6904 this.autoDisabled = false;
6905 this.include = config.include || [];
6906 this.exclude = config.exclude || [];
6907 this.promote = config.promote || [];
6908 this.demote = config.demote || [];
6909 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6910
6911 // Events
6912 this.$element.on( {
6913 mousedown: this.onPointerDown.bind( this ),
6914 mouseup: this.onPointerUp.bind( this ),
6915 mouseover: this.onMouseOver.bind( this ),
6916 mouseout: this.onMouseOut.bind( this )
6917 } );
6918 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6919 this.aggregate( { disable: 'itemDisable' } );
6920 this.connect( this, { itemDisable: 'updateDisabled' } );
6921
6922 // Initialization
6923 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6924 this.$element
6925 .addClass( 'oo-ui-toolGroup' )
6926 .append( this.$group );
6927 this.populate();
6928 };
6929
6930 /* Setup */
6931
6932 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6933 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6934
6935 /* Events */
6936
6937 /**
6938 * @event update
6939 */
6940
6941 /* Static Properties */
6942
6943 /**
6944 * Show labels in tooltips.
6945 *
6946 * @static
6947 * @inheritable
6948 * @property {boolean}
6949 */
6950 OO.ui.ToolGroup.static.titleTooltips = false;
6951
6952 /**
6953 * Show acceleration labels in tooltips.
6954 *
6955 * @static
6956 * @inheritable
6957 * @property {boolean}
6958 */
6959 OO.ui.ToolGroup.static.accelTooltips = false;
6960
6961 /**
6962 * Automatically disable the toolgroup when all tools are disabled
6963 *
6964 * @static
6965 * @inheritable
6966 * @property {boolean}
6967 */
6968 OO.ui.ToolGroup.static.autoDisable = true;
6969
6970 /* Methods */
6971
6972 /**
6973 * @inheritdoc
6974 */
6975 OO.ui.ToolGroup.prototype.isDisabled = function () {
6976 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6977 };
6978
6979 /**
6980 * @inheritdoc
6981 */
6982 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6983 var i, item, allDisabled = true;
6984
6985 if ( this.constructor.static.autoDisable ) {
6986 for ( i = this.items.length - 1; i >= 0; i-- ) {
6987 item = this.items[ i ];
6988 if ( !item.isDisabled() ) {
6989 allDisabled = false;
6990 break;
6991 }
6992 }
6993 this.autoDisabled = allDisabled;
6994 }
6995 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6996 };
6997
6998 /**
6999 * Handle mouse down events.
7000 *
7001 * @param {jQuery.Event} e Mouse down event
7002 */
7003 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
7004 if ( !this.isDisabled() && e.which === 1 ) {
7005 this.pressed = this.getTargetTool( e );
7006 if ( this.pressed ) {
7007 this.pressed.setActive( true );
7008 this.getElementDocument().addEventListener(
7009 'mouseup', this.onCapturedMouseUpHandler, true
7010 );
7011 }
7012 }
7013 return false;
7014 };
7015
7016 /**
7017 * Handle captured mouse up events.
7018 *
7019 * @param {Event} e Mouse up event
7020 */
7021 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
7022 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
7023 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7024 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7025 this.onPointerUp( e );
7026 };
7027
7028 /**
7029 * Handle mouse up events.
7030 *
7031 * @param {jQuery.Event} e Mouse up event
7032 */
7033 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
7034 var tool = this.getTargetTool( e );
7035
7036 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
7037 this.pressed.onSelect();
7038 }
7039
7040 this.pressed = null;
7041 return false;
7042 };
7043
7044 /**
7045 * Handle mouse over events.
7046 *
7047 * @param {jQuery.Event} e Mouse over event
7048 */
7049 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
7050 var tool = this.getTargetTool( e );
7051
7052 if ( this.pressed && this.pressed === tool ) {
7053 this.pressed.setActive( true );
7054 }
7055 };
7056
7057 /**
7058 * Handle mouse out events.
7059 *
7060 * @param {jQuery.Event} e Mouse out event
7061 */
7062 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
7063 var tool = this.getTargetTool( e );
7064
7065 if ( this.pressed && this.pressed === tool ) {
7066 this.pressed.setActive( false );
7067 }
7068 };
7069
7070 /**
7071 * Get the closest tool to a jQuery.Event.
7072 *
7073 * Only tool links are considered, which prevents other elements in the tool such as popups from
7074 * triggering tool group interactions.
7075 *
7076 * @private
7077 * @param {jQuery.Event} e
7078 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7079 */
7080 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7081 var tool,
7082 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7083
7084 if ( $item.length ) {
7085 tool = $item.parent().data( 'oo-ui-tool' );
7086 }
7087
7088 return tool && !tool.isDisabled() ? tool : null;
7089 };
7090
7091 /**
7092 * Handle tool registry register events.
7093 *
7094 * If a tool is registered after the group is created, we must repopulate the list to account for:
7095 *
7096 * - a tool being added that may be included
7097 * - a tool already included being overridden
7098 *
7099 * @param {string} name Symbolic name of tool
7100 */
7101 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7102 this.populate();
7103 };
7104
7105 /**
7106 * Get the toolbar this group is in.
7107 *
7108 * @return {OO.ui.Toolbar} Toolbar of group
7109 */
7110 OO.ui.ToolGroup.prototype.getToolbar = function () {
7111 return this.toolbar;
7112 };
7113
7114 /**
7115 * Add and remove tools based on configuration.
7116 */
7117 OO.ui.ToolGroup.prototype.populate = function () {
7118 var i, len, name, tool,
7119 toolFactory = this.toolbar.getToolFactory(),
7120 names = {},
7121 add = [],
7122 remove = [],
7123 list = this.toolbar.getToolFactory().getTools(
7124 this.include, this.exclude, this.promote, this.demote
7125 );
7126
7127 // Build a list of needed tools
7128 for ( i = 0, len = list.length; i < len; i++ ) {
7129 name = list[ i ];
7130 if (
7131 // Tool exists
7132 toolFactory.lookup( name ) &&
7133 // Tool is available or is already in this group
7134 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7135 ) {
7136 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7137 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7138 this.toolbar.tools[ name ] = true;
7139 tool = this.tools[ name ];
7140 if ( !tool ) {
7141 // Auto-initialize tools on first use
7142 this.tools[ name ] = tool = toolFactory.create( name, this );
7143 tool.updateTitle();
7144 }
7145 this.toolbar.reserveTool( tool );
7146 add.push( tool );
7147 names[ name ] = true;
7148 }
7149 }
7150 // Remove tools that are no longer needed
7151 for ( name in this.tools ) {
7152 if ( !names[ name ] ) {
7153 this.tools[ name ].destroy();
7154 this.toolbar.releaseTool( this.tools[ name ] );
7155 remove.push( this.tools[ name ] );
7156 delete this.tools[ name ];
7157 }
7158 }
7159 if ( remove.length ) {
7160 this.removeItems( remove );
7161 }
7162 // Update emptiness state
7163 if ( add.length ) {
7164 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7165 } else {
7166 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7167 }
7168 // Re-add tools (moving existing ones to new locations)
7169 this.addItems( add );
7170 // Disabled state may depend on items
7171 this.updateDisabled();
7172 };
7173
7174 /**
7175 * Destroy tool group.
7176 */
7177 OO.ui.ToolGroup.prototype.destroy = function () {
7178 var name;
7179
7180 this.clearItems();
7181 this.toolbar.getToolFactory().disconnect( this );
7182 for ( name in this.tools ) {
7183 this.toolbar.releaseTool( this.tools[ name ] );
7184 this.tools[ name ].disconnect( this ).destroy();
7185 delete this.tools[ name ];
7186 }
7187 this.$element.remove();
7188 };
7189
7190 /**
7191 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7192 * consists of a header that contains the dialog title, a body with the message, and a footer that
7193 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7194 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7195 *
7196 * There are two basic types of message dialogs, confirmation and alert:
7197 *
7198 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7199 * more details about the consequences.
7200 * - **alert**: the dialog title describes which event occurred and the message provides more information
7201 * about why the event occurred.
7202 *
7203 * The MessageDialog class specifies two actions: ‘accept’, the primary
7204 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7205 * passing along the selected action.
7206 *
7207 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7208 *
7209 * @example
7210 * // Example: Creating and opening a message dialog window.
7211 * var messageDialog = new OO.ui.MessageDialog();
7212 *
7213 * // Create and append a window manager.
7214 * var windowManager = new OO.ui.WindowManager();
7215 * $( 'body' ).append( windowManager.$element );
7216 * windowManager.addWindows( [ messageDialog ] );
7217 * // Open the window.
7218 * windowManager.openWindow( messageDialog, {
7219 * title: 'Basic message dialog',
7220 * message: 'This is the message'
7221 * } );
7222 *
7223 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7224 *
7225 * @class
7226 * @extends OO.ui.Dialog
7227 *
7228 * @constructor
7229 * @param {Object} [config] Configuration options
7230 */
7231 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7232 // Parent constructor
7233 OO.ui.MessageDialog.super.call( this, config );
7234
7235 // Properties
7236 this.verticalActionLayout = null;
7237
7238 // Initialization
7239 this.$element.addClass( 'oo-ui-messageDialog' );
7240 };
7241
7242 /* Inheritance */
7243
7244 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7245
7246 /* Static Properties */
7247
7248 OO.ui.MessageDialog.static.name = 'message';
7249
7250 OO.ui.MessageDialog.static.size = 'small';
7251
7252 OO.ui.MessageDialog.static.verbose = false;
7253
7254 /**
7255 * Dialog title.
7256 *
7257 * The title of a confirmation dialog describes what a progressive action will do. The
7258 * title of an alert dialog describes which event occurred.
7259 *
7260 * @static
7261 * @inheritable
7262 * @property {jQuery|string|Function|null}
7263 */
7264 OO.ui.MessageDialog.static.title = null;
7265
7266 /**
7267 * The message displayed in the dialog body.
7268 *
7269 * A confirmation message describes the consequences of a progressive action. An alert
7270 * message describes why an event occurred.
7271 *
7272 * @static
7273 * @inheritable
7274 * @property {jQuery|string|Function|null}
7275 */
7276 OO.ui.MessageDialog.static.message = null;
7277
7278 OO.ui.MessageDialog.static.actions = [
7279 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7280 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7281 ];
7282
7283 /* Methods */
7284
7285 /**
7286 * @inheritdoc
7287 */
7288 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7289 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7290
7291 // Events
7292 this.manager.connect( this, {
7293 resize: 'onResize'
7294 } );
7295
7296 return this;
7297 };
7298
7299 /**
7300 * @inheritdoc
7301 */
7302 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7303 this.fitActions();
7304 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7305 };
7306
7307 /**
7308 * Handle window resized events.
7309 *
7310 * @private
7311 */
7312 OO.ui.MessageDialog.prototype.onResize = function () {
7313 var dialog = this;
7314 dialog.fitActions();
7315 // Wait for CSS transition to finish and do it again :(
7316 setTimeout( function () {
7317 dialog.fitActions();
7318 }, 300 );
7319 };
7320
7321 /**
7322 * Toggle action layout between vertical and horizontal.
7323 *
7324 *
7325 * @private
7326 * @param {boolean} [value] Layout actions vertically, omit to toggle
7327 * @chainable
7328 */
7329 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7330 value = value === undefined ? !this.verticalActionLayout : !!value;
7331
7332 if ( value !== this.verticalActionLayout ) {
7333 this.verticalActionLayout = value;
7334 this.$actions
7335 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7336 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7337 }
7338
7339 return this;
7340 };
7341
7342 /**
7343 * @inheritdoc
7344 */
7345 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7346 if ( action ) {
7347 return new OO.ui.Process( function () {
7348 this.close( { action: action } );
7349 }, this );
7350 }
7351 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7352 };
7353
7354 /**
7355 * @inheritdoc
7356 *
7357 * @param {Object} [data] Dialog opening data
7358 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7359 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7360 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7361 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7362 * action item
7363 */
7364 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7365 data = data || {};
7366
7367 // Parent method
7368 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7369 .next( function () {
7370 this.title.setLabel(
7371 data.title !== undefined ? data.title : this.constructor.static.title
7372 );
7373 this.message.setLabel(
7374 data.message !== undefined ? data.message : this.constructor.static.message
7375 );
7376 this.message.$element.toggleClass(
7377 'oo-ui-messageDialog-message-verbose',
7378 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7379 );
7380 }, this );
7381 };
7382
7383 /**
7384 * @inheritdoc
7385 */
7386 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7387 var bodyHeight, oldOverflow,
7388 $scrollable = this.container.$element;
7389
7390 oldOverflow = $scrollable[ 0 ].style.overflow;
7391 $scrollable[ 0 ].style.overflow = 'hidden';
7392
7393 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7394
7395 bodyHeight = this.text.$element.outerHeight( true );
7396 $scrollable[ 0 ].style.overflow = oldOverflow;
7397
7398 return bodyHeight;
7399 };
7400
7401 /**
7402 * @inheritdoc
7403 */
7404 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7405 var $scrollable = this.container.$element;
7406 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7407
7408 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7409 // Need to do it after transition completes (250ms), add 50ms just in case.
7410 setTimeout( function () {
7411 var oldOverflow = $scrollable[ 0 ].style.overflow;
7412 $scrollable[ 0 ].style.overflow = 'hidden';
7413
7414 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7415
7416 $scrollable[ 0 ].style.overflow = oldOverflow;
7417 }, 300 );
7418
7419 return this;
7420 };
7421
7422 /**
7423 * @inheritdoc
7424 */
7425 OO.ui.MessageDialog.prototype.initialize = function () {
7426 // Parent method
7427 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7428
7429 // Properties
7430 this.$actions = $( '<div>' );
7431 this.container = new OO.ui.PanelLayout( {
7432 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7433 } );
7434 this.text = new OO.ui.PanelLayout( {
7435 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7436 } );
7437 this.message = new OO.ui.LabelWidget( {
7438 classes: [ 'oo-ui-messageDialog-message' ]
7439 } );
7440
7441 // Initialization
7442 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7443 this.$content.addClass( 'oo-ui-messageDialog-content' );
7444 this.container.$element.append( this.text.$element );
7445 this.text.$element.append( this.title.$element, this.message.$element );
7446 this.$body.append( this.container.$element );
7447 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7448 this.$foot.append( this.$actions );
7449 };
7450
7451 /**
7452 * @inheritdoc
7453 */
7454 OO.ui.MessageDialog.prototype.attachActions = function () {
7455 var i, len, other, special, others;
7456
7457 // Parent method
7458 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7459
7460 special = this.actions.getSpecial();
7461 others = this.actions.getOthers();
7462 if ( special.safe ) {
7463 this.$actions.append( special.safe.$element );
7464 special.safe.toggleFramed( false );
7465 }
7466 if ( others.length ) {
7467 for ( i = 0, len = others.length; i < len; i++ ) {
7468 other = others[ i ];
7469 this.$actions.append( other.$element );
7470 other.toggleFramed( false );
7471 }
7472 }
7473 if ( special.primary ) {
7474 this.$actions.append( special.primary.$element );
7475 special.primary.toggleFramed( false );
7476 }
7477
7478 if ( !this.isOpening() ) {
7479 // If the dialog is currently opening, this will be called automatically soon.
7480 // This also calls #fitActions.
7481 this.updateSize();
7482 }
7483 };
7484
7485 /**
7486 * Fit action actions into columns or rows.
7487 *
7488 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7489 *
7490 * @private
7491 */
7492 OO.ui.MessageDialog.prototype.fitActions = function () {
7493 var i, len, action,
7494 previous = this.verticalActionLayout,
7495 actions = this.actions.get();
7496
7497 // Detect clipping
7498 this.toggleVerticalActionLayout( false );
7499 for ( i = 0, len = actions.length; i < len; i++ ) {
7500 action = actions[ i ];
7501 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7502 this.toggleVerticalActionLayout( true );
7503 break;
7504 }
7505 }
7506
7507 // Move the body out of the way of the foot
7508 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7509
7510 if ( this.verticalActionLayout !== previous ) {
7511 // We changed the layout, window height might need to be updated.
7512 this.updateSize();
7513 }
7514 };
7515
7516 /**
7517 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7518 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7519 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7520 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7521 * required for each process.
7522 *
7523 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7524 * processes with an animation. The header contains the dialog title as well as
7525 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7526 * a ‘primary’ action on the right (e.g., ‘Done’).
7527 *
7528 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7529 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7530 *
7531 * @example
7532 * // Example: Creating and opening a process dialog window.
7533 * function MyProcessDialog( config ) {
7534 * MyProcessDialog.super.call( this, config );
7535 * }
7536 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7537 *
7538 * MyProcessDialog.static.title = 'Process dialog';
7539 * MyProcessDialog.static.actions = [
7540 * { action: 'save', label: 'Done', flags: 'primary' },
7541 * { label: 'Cancel', flags: 'safe' }
7542 * ];
7543 *
7544 * MyProcessDialog.prototype.initialize = function () {
7545 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7546 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
7547 * this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
7548 * this.$body.append( this.content.$element );
7549 * };
7550 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7551 * var dialog = this;
7552 * if ( action ) {
7553 * return new OO.ui.Process( function () {
7554 * dialog.close( { action: action } );
7555 * } );
7556 * }
7557 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7558 * };
7559 *
7560 * var windowManager = new OO.ui.WindowManager();
7561 * $( 'body' ).append( windowManager.$element );
7562 *
7563 * var dialog = new MyProcessDialog();
7564 * windowManager.addWindows( [ dialog ] );
7565 * windowManager.openWindow( dialog );
7566 *
7567 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7568 *
7569 * @abstract
7570 * @class
7571 * @extends OO.ui.Dialog
7572 *
7573 * @constructor
7574 * @param {Object} [config] Configuration options
7575 */
7576 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7577 // Parent constructor
7578 OO.ui.ProcessDialog.super.call( this, config );
7579
7580 // Initialization
7581 this.$element.addClass( 'oo-ui-processDialog' );
7582 };
7583
7584 /* Setup */
7585
7586 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7587
7588 /* Methods */
7589
7590 /**
7591 * Handle dismiss button click events.
7592 *
7593 * Hides errors.
7594 *
7595 * @private
7596 */
7597 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7598 this.hideErrors();
7599 };
7600
7601 /**
7602 * Handle retry button click events.
7603 *
7604 * Hides errors and then tries again.
7605 *
7606 * @private
7607 */
7608 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7609 this.hideErrors();
7610 this.executeAction( this.currentAction );
7611 };
7612
7613 /**
7614 * @inheritdoc
7615 */
7616 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7617 if ( this.actions.isSpecial( action ) ) {
7618 this.fitLabel();
7619 }
7620 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7621 };
7622
7623 /**
7624 * @inheritdoc
7625 */
7626 OO.ui.ProcessDialog.prototype.initialize = function () {
7627 // Parent method
7628 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7629
7630 // Properties
7631 this.$navigation = $( '<div>' );
7632 this.$location = $( '<div>' );
7633 this.$safeActions = $( '<div>' );
7634 this.$primaryActions = $( '<div>' );
7635 this.$otherActions = $( '<div>' );
7636 this.dismissButton = new OO.ui.ButtonWidget( {
7637 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7638 } );
7639 this.retryButton = new OO.ui.ButtonWidget();
7640 this.$errors = $( '<div>' );
7641 this.$errorsTitle = $( '<div>' );
7642
7643 // Events
7644 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7645 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7646
7647 // Initialization
7648 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7649 this.$location
7650 .append( this.title.$element )
7651 .addClass( 'oo-ui-processDialog-location' );
7652 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7653 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7654 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7655 this.$errorsTitle
7656 .addClass( 'oo-ui-processDialog-errors-title' )
7657 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7658 this.$errors
7659 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7660 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7661 this.$content
7662 .addClass( 'oo-ui-processDialog-content' )
7663 .append( this.$errors );
7664 this.$navigation
7665 .addClass( 'oo-ui-processDialog-navigation' )
7666 .append( this.$safeActions, this.$location, this.$primaryActions );
7667 this.$head.append( this.$navigation );
7668 this.$foot.append( this.$otherActions );
7669 };
7670
7671 /**
7672 * @inheritdoc
7673 */
7674 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7675 var i, len, widgets = [];
7676 for ( i = 0, len = actions.length; i < len; i++ ) {
7677 widgets.push(
7678 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7679 );
7680 }
7681 return widgets;
7682 };
7683
7684 /**
7685 * @inheritdoc
7686 */
7687 OO.ui.ProcessDialog.prototype.attachActions = function () {
7688 var i, len, other, special, others;
7689
7690 // Parent method
7691 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7692
7693 special = this.actions.getSpecial();
7694 others = this.actions.getOthers();
7695 if ( special.primary ) {
7696 this.$primaryActions.append( special.primary.$element );
7697 }
7698 for ( i = 0, len = others.length; i < len; i++ ) {
7699 other = others[ i ];
7700 this.$otherActions.append( other.$element );
7701 }
7702 if ( special.safe ) {
7703 this.$safeActions.append( special.safe.$element );
7704 }
7705
7706 this.fitLabel();
7707 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7708 };
7709
7710 /**
7711 * @inheritdoc
7712 */
7713 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7714 var process = this;
7715 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7716 .fail( function ( errors ) {
7717 process.showErrors( errors || [] );
7718 } );
7719 };
7720
7721 /**
7722 * Fit label between actions.
7723 *
7724 * @private
7725 * @chainable
7726 */
7727 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7728 var width = Math.max(
7729 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7730 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7731 );
7732 this.$location.css( { paddingLeft: width, paddingRight: width } );
7733
7734 return this;
7735 };
7736
7737 /**
7738 * Handle errors that occurred during accept or reject processes.
7739 *
7740 * @private
7741 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7742 */
7743 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7744 var i, len, $item, actions,
7745 items = [],
7746 abilities = {},
7747 recoverable = true,
7748 warning = false;
7749
7750 if ( errors instanceof OO.ui.Error ) {
7751 errors = [ errors ];
7752 }
7753
7754 for ( i = 0, len = errors.length; i < len; i++ ) {
7755 if ( !errors[ i ].isRecoverable() ) {
7756 recoverable = false;
7757 }
7758 if ( errors[ i ].isWarning() ) {
7759 warning = true;
7760 }
7761 $item = $( '<div>' )
7762 .addClass( 'oo-ui-processDialog-error' )
7763 .append( errors[ i ].getMessage() );
7764 items.push( $item[ 0 ] );
7765 }
7766 this.$errorItems = $( items );
7767 if ( recoverable ) {
7768 abilities[this.currentAction] = true;
7769 // Copy the flags from the first matching action
7770 actions = this.actions.get( { actions: this.currentAction } );
7771 if ( actions.length ) {
7772 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7773 }
7774 } else {
7775 abilities[this.currentAction] = false;
7776 this.actions.setAbilities( abilities );
7777 }
7778 if ( warning ) {
7779 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7780 } else {
7781 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7782 }
7783 this.retryButton.toggle( recoverable );
7784 this.$errorsTitle.after( this.$errorItems );
7785 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7786 };
7787
7788 /**
7789 * Hide errors.
7790 *
7791 * @private
7792 */
7793 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7794 this.$errors.addClass( 'oo-ui-element-hidden' );
7795 if ( this.$errorItems ) {
7796 this.$errorItems.remove();
7797 this.$errorItems = null;
7798 }
7799 };
7800
7801 /**
7802 * @inheritdoc
7803 */
7804 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
7805 // Parent method
7806 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
7807 .first( function () {
7808 // Make sure to hide errors
7809 this.hideErrors();
7810 }, this );
7811 };
7812
7813 /**
7814 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7815 * which is a widget that is specified by reference before any optional configuration settings.
7816 *
7817 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7818 *
7819 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7820 * A left-alignment is used for forms with many fields.
7821 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7822 * A right-alignment is used for long but familiar forms which users tab through,
7823 * verifying the current field with a quick glance at the label.
7824 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7825 * that users fill out from top to bottom.
7826 * - **inline**: The label is placed after the field-widget and aligned to the left.
7827 * An inline-alignment is best used with checkboxes or radio buttons.
7828 *
7829 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7830 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7831 *
7832 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7833 * @class
7834 * @extends OO.ui.Layout
7835 * @mixins OO.ui.LabelElement
7836 *
7837 * @constructor
7838 * @param {OO.ui.Widget} fieldWidget Field widget
7839 * @param {Object} [config] Configuration options
7840 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7841 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7842 * in the upper-right corner of the rendered field.
7843 */
7844 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7845 // Allow passing positional parameters inside the config object
7846 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7847 config = fieldWidget;
7848 fieldWidget = config.fieldWidget;
7849 }
7850
7851 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7852
7853 // Configuration initialization
7854 config = $.extend( { align: 'left' }, config );
7855
7856 // Parent constructor
7857 OO.ui.FieldLayout.super.call( this, config );
7858
7859 // Mixin constructors
7860 OO.ui.LabelElement.call( this, config );
7861
7862 // Properties
7863 this.fieldWidget = fieldWidget;
7864 this.$field = $( '<div>' );
7865 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7866 this.align = null;
7867 if ( config.help ) {
7868 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7869 classes: [ 'oo-ui-fieldLayout-help' ],
7870 framed: false,
7871 icon: 'info'
7872 } );
7873
7874 this.popupButtonWidget.getPopup().$body.append(
7875 $( '<div>' )
7876 .text( config.help )
7877 .addClass( 'oo-ui-fieldLayout-help-content' )
7878 );
7879 this.$help = this.popupButtonWidget.$element;
7880 } else {
7881 this.$help = $( [] );
7882 }
7883
7884 // Events
7885 if ( hasInputWidget ) {
7886 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7887 }
7888 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7889
7890 // Initialization
7891 this.$element
7892 .addClass( 'oo-ui-fieldLayout' )
7893 .append( this.$help, this.$body );
7894 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7895 this.$field
7896 .addClass( 'oo-ui-fieldLayout-field' )
7897 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7898 .append( this.fieldWidget.$element );
7899
7900 this.setAlignment( config.align );
7901 };
7902
7903 /* Setup */
7904
7905 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7906 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7907
7908 /* Methods */
7909
7910 /**
7911 * Handle field disable events.
7912 *
7913 * @private
7914 * @param {boolean} value Field is disabled
7915 */
7916 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7917 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7918 };
7919
7920 /**
7921 * Handle label mouse click events.
7922 *
7923 * @private
7924 * @param {jQuery.Event} e Mouse click event
7925 */
7926 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7927 this.fieldWidget.simulateLabelClick();
7928 return false;
7929 };
7930
7931 /**
7932 * Get the widget contained by the field.
7933 *
7934 * @return {OO.ui.Widget} Field widget
7935 */
7936 OO.ui.FieldLayout.prototype.getField = function () {
7937 return this.fieldWidget;
7938 };
7939
7940 /**
7941 * Set the field alignment mode.
7942 *
7943 * @private
7944 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7945 * @chainable
7946 */
7947 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7948 if ( value !== this.align ) {
7949 // Default to 'left'
7950 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7951 value = 'left';
7952 }
7953 // Reorder elements
7954 if ( value === 'inline' ) {
7955 this.$body.append( this.$field, this.$label );
7956 } else {
7957 this.$body.append( this.$label, this.$field );
7958 }
7959 // Set classes. The following classes can be used here:
7960 // * oo-ui-fieldLayout-align-left
7961 // * oo-ui-fieldLayout-align-right
7962 // * oo-ui-fieldLayout-align-top
7963 // * oo-ui-fieldLayout-align-inline
7964 if ( this.align ) {
7965 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7966 }
7967 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7968 this.align = value;
7969 }
7970
7971 return this;
7972 };
7973
7974 /**
7975 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
7976 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
7977 * is required and is specified before any optional configuration settings.
7978 *
7979 * Labels can be aligned in one of four ways:
7980 *
7981 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7982 * A left-alignment is used for forms with many fields.
7983 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7984 * A right-alignment is used for long but familiar forms which users tab through,
7985 * verifying the current field with a quick glance at the label.
7986 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7987 * that users fill out from top to bottom.
7988 * - **inline**: The label is placed after the field-widget and aligned to the left.
7989 * An inline-alignment is best used with checkboxes or radio buttons.
7990 *
7991 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
7992 * text is specified.
7993 *
7994 * @example
7995 * // Example of an ActionFieldLayout
7996 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
7997 * new OO.ui.TextInputWidget( {
7998 * placeholder: 'Field widget'
7999 * } ),
8000 * new OO.ui.ButtonWidget( {
8001 * label: 'Button'
8002 * } ),
8003 * {
8004 * label: 'An ActionFieldLayout. This label is aligned top',
8005 * align: 'top',
8006 * help: 'This is help text'
8007 * }
8008 * );
8009 *
8010 * $( 'body' ).append( actionFieldLayout.$element );
8011 *
8012 *
8013 * @class
8014 * @extends OO.ui.FieldLayout
8015 *
8016 * @constructor
8017 * @param {OO.ui.Widget} fieldWidget Field widget
8018 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
8019 * @param {Object} [config] Configuration options
8020 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
8021 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
8022 * upper-right corner of the rendered field.
8023 */
8024 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8025 // Allow passing positional parameters inside the config object
8026 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8027 config = fieldWidget;
8028 fieldWidget = config.fieldWidget;
8029 buttonWidget = config.buttonWidget;
8030 }
8031
8032 // Configuration initialization
8033 config = $.extend( { align: 'left' }, config );
8034
8035 // Parent constructor
8036 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
8037
8038 // Properties
8039 this.fieldWidget = fieldWidget;
8040 this.buttonWidget = buttonWidget;
8041 this.$button = $( '<div>' )
8042 .addClass( 'oo-ui-actionFieldLayout-button' )
8043 .append( this.buttonWidget.$element );
8044 this.$input = $( '<div>' )
8045 .addClass( 'oo-ui-actionFieldLayout-input' )
8046 .append( this.fieldWidget.$element );
8047 this.$field
8048 .addClass( 'oo-ui-actionFieldLayout' )
8049 .append( this.$input, this.$button );
8050 };
8051
8052 /* Setup */
8053
8054 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8055
8056 /**
8057 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8058 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8059 * configured with a label as well. For more information and examples,
8060 * please see the [OOjs UI documentation on MediaWiki][1].
8061 *
8062 * @example
8063 * // Example of a fieldset layout
8064 * var input1 = new OO.ui.TextInputWidget( {
8065 * placeholder: 'A text input field'
8066 * } );
8067 *
8068 * var input2 = new OO.ui.TextInputWidget( {
8069 * placeholder: 'A text input field'
8070 * } );
8071 *
8072 * var fieldset = new OO.ui.FieldsetLayout( {
8073 * label: 'Example of a fieldset layout'
8074 * } );
8075 *
8076 * fieldset.addItems( [
8077 * new OO.ui.FieldLayout( input1, {
8078 * label: 'Field One'
8079 * } ),
8080 * new OO.ui.FieldLayout( input2, {
8081 * label: 'Field Two'
8082 * } )
8083 * ] );
8084 * $( 'body' ).append( fieldset.$element );
8085 *
8086 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8087 *
8088 * @class
8089 * @extends OO.ui.Layout
8090 * @mixins OO.ui.IconElement
8091 * @mixins OO.ui.LabelElement
8092 * @mixins OO.ui.GroupElement
8093 *
8094 * @constructor
8095 * @param {Object} [config] Configuration options
8096 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8097 */
8098 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8099 // Configuration initialization
8100 config = config || {};
8101
8102 // Parent constructor
8103 OO.ui.FieldsetLayout.super.call( this, config );
8104
8105 // Mixin constructors
8106 OO.ui.IconElement.call( this, config );
8107 OO.ui.LabelElement.call( this, config );
8108 OO.ui.GroupElement.call( this, config );
8109
8110 if ( config.help ) {
8111 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8112 classes: [ 'oo-ui-fieldsetLayout-help' ],
8113 framed: false,
8114 icon: 'info'
8115 } );
8116
8117 this.popupButtonWidget.getPopup().$body.append(
8118 $( '<div>' )
8119 .text( config.help )
8120 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8121 );
8122 this.$help = this.popupButtonWidget.$element;
8123 } else {
8124 this.$help = $( [] );
8125 }
8126
8127 // Initialization
8128 this.$element
8129 .addClass( 'oo-ui-fieldsetLayout' )
8130 .prepend( this.$help, this.$icon, this.$label, this.$group );
8131 if ( Array.isArray( config.items ) ) {
8132 this.addItems( config.items );
8133 }
8134 };
8135
8136 /* Setup */
8137
8138 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8139 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8140 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8141 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8142
8143 /**
8144 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8145 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8146 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8147 *
8148 * @example
8149 * // Example of a form layout that wraps a fieldset layout
8150 * var input1 = new OO.ui.TextInputWidget( {
8151 * placeholder: 'Username'
8152 * } );
8153 * var input2 = new OO.ui.TextInputWidget( {
8154 * placeholder: 'Password',
8155 * type: 'password'
8156 * } );
8157 * var submit = new OO.ui.ButtonInputWidget( {
8158 * label: 'Submit'
8159 * } );
8160 *
8161 * var fieldset = new OO.ui.FieldsetLayout( {
8162 * label: 'A form layout'
8163 * } );
8164 * fieldset.addItems( [
8165 * new OO.ui.FieldLayout( input1, {
8166 * label: 'Username',
8167 * align: 'top'
8168 * } ),
8169 * new OO.ui.FieldLayout( input2, {
8170 * label: 'Password',
8171 * align: 'top'
8172 * } ),
8173 * new OO.ui.FieldLayout( submit )
8174 * ] );
8175 * var form = new OO.ui.FormLayout( {
8176 * items: [ fieldset ],
8177 * action: '/api/formhandler',
8178 * method: 'get'
8179 * } )
8180 * $( 'body' ).append( form.$element );
8181 *
8182 * @class
8183 * @extends OO.ui.Layout
8184 * @mixins OO.ui.GroupElement
8185 *
8186 * @constructor
8187 * @param {Object} [config] Configuration options
8188 * @cfg {string} [method] HTML form `method` attribute
8189 * @cfg {string} [action] HTML form `action` attribute
8190 * @cfg {string} [enctype] HTML form `enctype` attribute
8191 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8192 */
8193 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8194 // Configuration initialization
8195 config = config || {};
8196
8197 // Parent constructor
8198 OO.ui.FormLayout.super.call( this, config );
8199
8200 // Mixin constructors
8201 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8202
8203 // Events
8204 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8205
8206 // Initialization
8207 this.$element
8208 .addClass( 'oo-ui-formLayout' )
8209 .attr( {
8210 method: config.method,
8211 action: config.action,
8212 enctype: config.enctype
8213 } );
8214 if ( Array.isArray( config.items ) ) {
8215 this.addItems( config.items );
8216 }
8217 };
8218
8219 /* Setup */
8220
8221 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8222 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8223
8224 /* Events */
8225
8226 /**
8227 * A 'submit' event is emitted when the form is submitted.
8228 *
8229 * @event submit
8230 */
8231
8232 /* Static Properties */
8233
8234 OO.ui.FormLayout.static.tagName = 'form';
8235
8236 /* Methods */
8237
8238 /**
8239 * Handle form submit events.
8240 *
8241 * @private
8242 * @param {jQuery.Event} e Submit event
8243 * @fires submit
8244 */
8245 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8246 this.emit( 'submit' );
8247 return false;
8248 };
8249
8250 /**
8251 * Layout with a content and menu area.
8252 *
8253 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8254 * all remaining space.
8255 *
8256 * @class
8257 * @extends OO.ui.Layout
8258 *
8259 * @constructor
8260 * @param {Object} [config] Configuration options
8261 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8262 * @cfg {boolean} [showMenu=true] Show menu
8263 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8264 */
8265 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8266 var positions = this.constructor.static.menuPositions;
8267
8268 // Configuration initialization
8269 config = config || {};
8270
8271 // Parent constructor
8272 OO.ui.MenuLayout.super.call( this, config );
8273
8274 // Properties
8275 this.showMenu = config.showMenu !== false;
8276 this.menuSize = config.menuSize || '18em';
8277 this.menuPosition = positions[ config.menuPosition ] || positions.before;
8278
8279 /**
8280 * Menu DOM node
8281 *
8282 * @property {jQuery}
8283 */
8284 this.$menu = $( '<div>' );
8285 /**
8286 * Content DOM node
8287 *
8288 * @property {jQuery}
8289 */
8290 this.$content = $( '<div>' );
8291
8292 // Initialization
8293 this.toggleMenu( this.showMenu );
8294 this.updateSizes();
8295 this.$menu
8296 .addClass( 'oo-ui-menuLayout-menu' )
8297 .css( this.menuPosition.sizeProperty, this.menuSize );
8298 this.$content.addClass( 'oo-ui-menuLayout-content' );
8299 this.$element
8300 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
8301 .append( this.$content, this.$menu );
8302 };
8303
8304 /* Setup */
8305
8306 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8307
8308 /* Static Properties */
8309
8310 OO.ui.MenuLayout.static.menuPositions = {
8311 top: {
8312 sizeProperty: 'height',
8313 className: 'oo-ui-menuLayout-top'
8314 },
8315 after: {
8316 sizeProperty: 'width',
8317 className: 'oo-ui-menuLayout-after'
8318 },
8319 bottom: {
8320 sizeProperty: 'height',
8321 className: 'oo-ui-menuLayout-bottom'
8322 },
8323 before: {
8324 sizeProperty: 'width',
8325 className: 'oo-ui-menuLayout-before'
8326 }
8327 };
8328
8329 /* Methods */
8330
8331 /**
8332 * Toggle menu.
8333 *
8334 * @param {boolean} showMenu Show menu, omit to toggle
8335 * @chainable
8336 */
8337 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8338 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8339
8340 if ( this.showMenu !== showMenu ) {
8341 this.showMenu = showMenu;
8342 this.updateSizes();
8343 }
8344
8345 return this;
8346 };
8347
8348 /**
8349 * Check if menu is visible
8350 *
8351 * @return {boolean} Menu is visible
8352 */
8353 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8354 return this.showMenu;
8355 };
8356
8357 /**
8358 * Set menu size.
8359 *
8360 * @param {number|string} size Size of menu in pixels or any CSS unit
8361 * @chainable
8362 */
8363 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
8364 this.menuSize = size;
8365 this.updateSizes();
8366
8367 return this;
8368 };
8369
8370 /**
8371 * Update menu and content CSS based on current menu size and visibility
8372 *
8373 * This method is called internally when size or position is changed.
8374 */
8375 OO.ui.MenuLayout.prototype.updateSizes = function () {
8376 if ( this.showMenu ) {
8377 this.$menu
8378 .css( this.menuPosition.sizeProperty, this.menuSize )
8379 .css( 'overflow', '' );
8380 // Set offsets on all sides. CSS resets all but one with
8381 // 'important' rules so directionality flips are supported
8382 this.$content.css( {
8383 top: this.menuSize,
8384 right: this.menuSize,
8385 bottom: this.menuSize,
8386 left: this.menuSize
8387 } );
8388 } else {
8389 this.$menu
8390 .css( this.menuPosition.sizeProperty, 0 )
8391 .css( 'overflow', 'hidden' );
8392 this.$content.css( {
8393 top: 0,
8394 right: 0,
8395 bottom: 0,
8396 left: 0
8397 } );
8398 }
8399 };
8400
8401 /**
8402 * Get menu size.
8403 *
8404 * @return {number|string} Menu size
8405 */
8406 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8407 return this.menuSize;
8408 };
8409
8410 /**
8411 * Set menu position.
8412 *
8413 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8414 * @throws {Error} If position value is not supported
8415 * @chainable
8416 */
8417 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8418 var positions = this.constructor.static.menuPositions;
8419
8420 if ( !positions[ position ] ) {
8421 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8422 }
8423
8424 this.$menu.css( this.menuPosition.sizeProperty, '' );
8425 this.$element.removeClass( this.menuPosition.className );
8426
8427 this.menuPosition = positions[ position ];
8428
8429 this.updateSizes();
8430 this.$element.addClass( this.menuPosition.className );
8431
8432 return this;
8433 };
8434
8435 /**
8436 * Get menu position.
8437 *
8438 * @return {string} Menu position
8439 */
8440 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8441 return this.menuPosition;
8442 };
8443
8444 /**
8445 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8446 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8447 * through the pages and select which one to display. By default, only one page is
8448 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8449 * the booklet layout automatically focuses on the first focusable element, unless the
8450 * default setting is changed. Optionally, booklets can be configured to show
8451 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8452 *
8453 * @example
8454 * // Example of a BookletLayout that contains two PageLayouts.
8455 *
8456 * function PageOneLayout( name, config ) {
8457 * PageOneLayout.super.call( this, name, config );
8458 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8459 * }
8460 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8461 * PageOneLayout.prototype.setupOutlineItem = function () {
8462 * this.outlineItem.setLabel( 'Page One' );
8463 * };
8464 *
8465 * function PageTwoLayout( name, config ) {
8466 * PageTwoLayout.super.call( this, name, config );
8467 * this.$element.append( '<p>Second page</p>' );
8468 * }
8469 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8470 * PageTwoLayout.prototype.setupOutlineItem = function () {
8471 * this.outlineItem.setLabel( 'Page Two' );
8472 * };
8473 *
8474 * var page1 = new PageOneLayout( 'one' ),
8475 * page2 = new PageTwoLayout( 'two' );
8476 *
8477 * var booklet = new OO.ui.BookletLayout( {
8478 * outlined: true
8479 * } );
8480 *
8481 * booklet.addPages ( [ page1, page2 ] );
8482 * $( 'body' ).append( booklet.$element );
8483 *
8484 * @class
8485 * @extends OO.ui.MenuLayout
8486 *
8487 * @constructor
8488 * @param {Object} [config] Configuration options
8489 * @cfg {boolean} [continuous=false] Show all pages, one after another
8490 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8491 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8492 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8493 */
8494 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8495 // Configuration initialization
8496 config = config || {};
8497
8498 // Parent constructor
8499 OO.ui.BookletLayout.super.call( this, config );
8500
8501 // Properties
8502 this.currentPageName = null;
8503 this.pages = {};
8504 this.ignoreFocus = false;
8505 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8506 this.$content.append( this.stackLayout.$element );
8507 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8508 this.outlineVisible = false;
8509 this.outlined = !!config.outlined;
8510 if ( this.outlined ) {
8511 this.editable = !!config.editable;
8512 this.outlineControlsWidget = null;
8513 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8514 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8515 this.$menu.append( this.outlinePanel.$element );
8516 this.outlineVisible = true;
8517 if ( this.editable ) {
8518 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8519 this.outlineSelectWidget
8520 );
8521 }
8522 }
8523 this.toggleMenu( this.outlined );
8524
8525 // Events
8526 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8527 if ( this.outlined ) {
8528 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8529 }
8530 if ( this.autoFocus ) {
8531 // Event 'focus' does not bubble, but 'focusin' does
8532 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8533 }
8534
8535 // Initialization
8536 this.$element.addClass( 'oo-ui-bookletLayout' );
8537 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8538 if ( this.outlined ) {
8539 this.outlinePanel.$element
8540 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8541 .append( this.outlineSelectWidget.$element );
8542 if ( this.editable ) {
8543 this.outlinePanel.$element
8544 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8545 .append( this.outlineControlsWidget.$element );
8546 }
8547 }
8548 };
8549
8550 /* Setup */
8551
8552 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8553
8554 /* Events */
8555
8556 /**
8557 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8558 * @event set
8559 * @param {OO.ui.PageLayout} page Current page
8560 */
8561
8562 /**
8563 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8564 *
8565 * @event add
8566 * @param {OO.ui.PageLayout[]} page Added pages
8567 * @param {number} index Index pages were added at
8568 */
8569
8570 /**
8571 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8572 * {@link #removePages removed} from the booklet.
8573 *
8574 * @event remove
8575 * @param {OO.ui.PageLayout[]} pages Removed pages
8576 */
8577
8578 /* Methods */
8579
8580 /**
8581 * Handle stack layout focus.
8582 *
8583 * @private
8584 * @param {jQuery.Event} e Focusin event
8585 */
8586 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8587 var name, $target;
8588
8589 // Find the page that an element was focused within
8590 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8591 for ( name in this.pages ) {
8592 // Check for page match, exclude current page to find only page changes
8593 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8594 this.setPage( name );
8595 break;
8596 }
8597 }
8598 };
8599
8600 /**
8601 * Handle stack layout set events.
8602 *
8603 * @private
8604 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8605 */
8606 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8607 var layout = this;
8608 if ( page ) {
8609 page.scrollElementIntoView( { complete: function () {
8610 if ( layout.autoFocus ) {
8611 layout.focus();
8612 }
8613 } } );
8614 }
8615 };
8616
8617 /**
8618 * Focus the first input in the current page.
8619 *
8620 * If no page is selected, the first selectable page will be selected.
8621 * If the focus is already in an element on the current page, nothing will happen.
8622 * @param {number} [itemIndex] A specific item to focus on
8623 */
8624 OO.ui.BookletLayout.prototype.focus = function ( itemIndex ) {
8625 var $input, page,
8626 items = this.stackLayout.getItems();
8627
8628 if ( itemIndex !== undefined && items[ itemIndex ] ) {
8629 page = items[ itemIndex ];
8630 } else {
8631 page = this.stackLayout.getCurrentItem();
8632 }
8633
8634 if ( !page && this.outlined ) {
8635 this.selectFirstSelectablePage();
8636 page = this.stackLayout.getCurrentItem();
8637 }
8638 if ( !page ) {
8639 return;
8640 }
8641 // Only change the focus if is not already in the current page
8642 if ( !page.$element.find( ':focus' ).length ) {
8643 $input = page.$element.find( ':input:first' );
8644 if ( $input.length ) {
8645 $input[ 0 ].focus();
8646 }
8647 }
8648 };
8649
8650 /**
8651 * Handle outline widget select events.
8652 *
8653 * @private
8654 * @param {OO.ui.OptionWidget|null} item Selected item
8655 */
8656 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8657 if ( item ) {
8658 this.setPage( item.getData() );
8659 }
8660 };
8661
8662 /**
8663 * Check if booklet has an outline.
8664 *
8665 * @return {boolean} Booklet has an outline
8666 */
8667 OO.ui.BookletLayout.prototype.isOutlined = function () {
8668 return this.outlined;
8669 };
8670
8671 /**
8672 * Check if booklet has editing controls.
8673 *
8674 * @return {boolean} Booklet is editable
8675 */
8676 OO.ui.BookletLayout.prototype.isEditable = function () {
8677 return this.editable;
8678 };
8679
8680 /**
8681 * Check if booklet has a visible outline.
8682 *
8683 * @return {boolean} Outline is visible
8684 */
8685 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8686 return this.outlined && this.outlineVisible;
8687 };
8688
8689 /**
8690 * Hide or show the outline.
8691 *
8692 * @param {boolean} [show] Show outline, omit to invert current state
8693 * @chainable
8694 */
8695 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8696 if ( this.outlined ) {
8697 show = show === undefined ? !this.outlineVisible : !!show;
8698 this.outlineVisible = show;
8699 this.toggleMenu( show );
8700 }
8701
8702 return this;
8703 };
8704
8705 /**
8706 * Get the page closest to the specified page.
8707 *
8708 * @param {OO.ui.PageLayout} page Page to use as a reference point
8709 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8710 */
8711 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8712 var next, prev, level,
8713 pages = this.stackLayout.getItems(),
8714 index = $.inArray( page, pages );
8715
8716 if ( index !== -1 ) {
8717 next = pages[ index + 1 ];
8718 prev = pages[ index - 1 ];
8719 // Prefer adjacent pages at the same level
8720 if ( this.outlined ) {
8721 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8722 if (
8723 prev &&
8724 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8725 ) {
8726 return prev;
8727 }
8728 if (
8729 next &&
8730 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8731 ) {
8732 return next;
8733 }
8734 }
8735 }
8736 return prev || next || null;
8737 };
8738
8739 /**
8740 * Get the outline widget.
8741 *
8742 * If the booklet is not outlined, the method will return `null`.
8743 *
8744 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8745 */
8746 OO.ui.BookletLayout.prototype.getOutline = function () {
8747 return this.outlineSelectWidget;
8748 };
8749
8750 /**
8751 * Get the outline controls widget.
8752 *
8753 * If the outline is not editable, the method will return `null`.
8754 *
8755 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8756 */
8757 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8758 return this.outlineControlsWidget;
8759 };
8760
8761 /**
8762 * Get a page by its symbolic name.
8763 *
8764 * @param {string} name Symbolic name of page
8765 * @return {OO.ui.PageLayout|undefined} Page, if found
8766 */
8767 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8768 return this.pages[ name ];
8769 };
8770
8771 /**
8772 * Get the current page.
8773 *
8774 * @return {OO.ui.PageLayout|undefined} Current page, if found
8775 */
8776 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8777 var name = this.getCurrentPageName();
8778 return name ? this.getPage( name ) : undefined;
8779 };
8780
8781 /**
8782 * Get the symbolic name of the current page.
8783 *
8784 * @return {string|null} Symbolic name of the current page
8785 */
8786 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8787 return this.currentPageName;
8788 };
8789
8790 /**
8791 * Add pages to the booklet layout
8792 *
8793 * When pages are added with the same names as existing pages, the existing pages will be
8794 * automatically removed before the new pages are added.
8795 *
8796 * @param {OO.ui.PageLayout[]} pages Pages to add
8797 * @param {number} index Index of the insertion point
8798 * @fires add
8799 * @chainable
8800 */
8801 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8802 var i, len, name, page, item, currentIndex,
8803 stackLayoutPages = this.stackLayout.getItems(),
8804 remove = [],
8805 items = [];
8806
8807 // Remove pages with same names
8808 for ( i = 0, len = pages.length; i < len; i++ ) {
8809 page = pages[ i ];
8810 name = page.getName();
8811
8812 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8813 // Correct the insertion index
8814 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8815 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8816 index--;
8817 }
8818 remove.push( this.pages[ name ] );
8819 }
8820 }
8821 if ( remove.length ) {
8822 this.removePages( remove );
8823 }
8824
8825 // Add new pages
8826 for ( i = 0, len = pages.length; i < len; i++ ) {
8827 page = pages[ i ];
8828 name = page.getName();
8829 this.pages[ page.getName() ] = page;
8830 if ( this.outlined ) {
8831 item = new OO.ui.OutlineOptionWidget( { data: name } );
8832 page.setOutlineItem( item );
8833 items.push( item );
8834 }
8835 }
8836
8837 if ( this.outlined && items.length ) {
8838 this.outlineSelectWidget.addItems( items, index );
8839 this.selectFirstSelectablePage();
8840 }
8841 this.stackLayout.addItems( pages, index );
8842 this.emit( 'add', pages, index );
8843
8844 return this;
8845 };
8846
8847 /**
8848 * Remove the specified pages from the booklet layout.
8849 *
8850 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
8851 *
8852 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
8853 * @fires remove
8854 * @chainable
8855 */
8856 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8857 var i, len, name, page,
8858 items = [];
8859
8860 for ( i = 0, len = pages.length; i < len; i++ ) {
8861 page = pages[ i ];
8862 name = page.getName();
8863 delete this.pages[ name ];
8864 if ( this.outlined ) {
8865 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8866 page.setOutlineItem( null );
8867 }
8868 }
8869 if ( this.outlined && items.length ) {
8870 this.outlineSelectWidget.removeItems( items );
8871 this.selectFirstSelectablePage();
8872 }
8873 this.stackLayout.removeItems( pages );
8874 this.emit( 'remove', pages );
8875
8876 return this;
8877 };
8878
8879 /**
8880 * Clear all pages from the booklet layout.
8881 *
8882 * To remove only a subset of pages from the booklet, use the #removePages method.
8883 *
8884 * @fires remove
8885 * @chainable
8886 */
8887 OO.ui.BookletLayout.prototype.clearPages = function () {
8888 var i, len,
8889 pages = this.stackLayout.getItems();
8890
8891 this.pages = {};
8892 this.currentPageName = null;
8893 if ( this.outlined ) {
8894 this.outlineSelectWidget.clearItems();
8895 for ( i = 0, len = pages.length; i < len; i++ ) {
8896 pages[ i ].setOutlineItem( null );
8897 }
8898 }
8899 this.stackLayout.clearItems();
8900
8901 this.emit( 'remove', pages );
8902
8903 return this;
8904 };
8905
8906 /**
8907 * Set the current page by symbolic name.
8908 *
8909 * @fires set
8910 * @param {string} name Symbolic name of page
8911 */
8912 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8913 var selectedItem,
8914 $focused,
8915 page = this.pages[ name ];
8916
8917 if ( name !== this.currentPageName ) {
8918 if ( this.outlined ) {
8919 selectedItem = this.outlineSelectWidget.getSelectedItem();
8920 if ( selectedItem && selectedItem.getData() !== name ) {
8921 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8922 }
8923 }
8924 if ( page ) {
8925 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8926 this.pages[ this.currentPageName ].setActive( false );
8927 // Blur anything focused if the next page doesn't have anything focusable - this
8928 // is not needed if the next page has something focusable because once it is focused
8929 // this blur happens automatically
8930 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8931 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8932 if ( $focused.length ) {
8933 $focused[ 0 ].blur();
8934 }
8935 }
8936 }
8937 this.currentPageName = name;
8938 this.stackLayout.setItem( page );
8939 page.setActive( true );
8940 this.emit( 'set', page );
8941 }
8942 }
8943 };
8944
8945 /**
8946 * Select the first selectable page.
8947 *
8948 * @chainable
8949 */
8950 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8951 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8952 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8953 }
8954
8955 return this;
8956 };
8957
8958 /**
8959 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8960 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8961 *
8962 * @example
8963 * // Example of a panel layout
8964 * var panel = new OO.ui.PanelLayout( {
8965 * expanded: false,
8966 * framed: true,
8967 * padded: true,
8968 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8969 * } );
8970 * $( 'body' ).append( panel.$element );
8971 *
8972 * @class
8973 * @extends OO.ui.Layout
8974 *
8975 * @constructor
8976 * @param {Object} [config] Configuration options
8977 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8978 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8979 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8980 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8981 */
8982 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8983 // Configuration initialization
8984 config = $.extend( {
8985 scrollable: false,
8986 padded: false,
8987 expanded: true,
8988 framed: false
8989 }, config );
8990
8991 // Parent constructor
8992 OO.ui.PanelLayout.super.call( this, config );
8993
8994 // Initialization
8995 this.$element.addClass( 'oo-ui-panelLayout' );
8996 if ( config.scrollable ) {
8997 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8998 }
8999 if ( config.padded ) {
9000 this.$element.addClass( 'oo-ui-panelLayout-padded' );
9001 }
9002 if ( config.expanded ) {
9003 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
9004 }
9005 if ( config.framed ) {
9006 this.$element.addClass( 'oo-ui-panelLayout-framed' );
9007 }
9008 };
9009
9010 /* Setup */
9011
9012 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
9013
9014 /**
9015 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
9016 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
9017 * rather extended to include the required content and functionality.
9018 *
9019 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
9020 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
9021 * {@link OO.ui.BookletLayout BookletLayout} for an example.
9022 *
9023 * @class
9024 * @extends OO.ui.PanelLayout
9025 *
9026 * @constructor
9027 * @param {string} name Unique symbolic name of page
9028 * @param {Object} [config] Configuration options
9029 */
9030 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
9031 // Allow passing positional parameters inside the config object
9032 if ( OO.isPlainObject( name ) && config === undefined ) {
9033 config = name;
9034 name = config.name;
9035 }
9036
9037 // Configuration initialization
9038 config = $.extend( { scrollable: true }, config );
9039
9040 // Parent constructor
9041 OO.ui.PageLayout.super.call( this, config );
9042
9043 // Properties
9044 this.name = name;
9045 this.outlineItem = null;
9046 this.active = false;
9047
9048 // Initialization
9049 this.$element.addClass( 'oo-ui-pageLayout' );
9050 };
9051
9052 /* Setup */
9053
9054 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
9055
9056 /* Events */
9057
9058 /**
9059 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9060 * shown in a booklet layout that is configured to display only one page at a time.
9061 *
9062 * @event active
9063 * @param {boolean} active Page is active
9064 */
9065
9066 /* Methods */
9067
9068 /**
9069 * Get the symbolic name of the page.
9070 *
9071 * @return {string} Symbolic name of page
9072 */
9073 OO.ui.PageLayout.prototype.getName = function () {
9074 return this.name;
9075 };
9076
9077 /**
9078 * Check if page is active.
9079 *
9080 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9081 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9082 *
9083 * @return {boolean} Page is active
9084 */
9085 OO.ui.PageLayout.prototype.isActive = function () {
9086 return this.active;
9087 };
9088
9089 /**
9090 * Get outline item.
9091 *
9092 * The outline item allows users to access the page from the booklet's outline
9093 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9094 *
9095 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9096 */
9097 OO.ui.PageLayout.prototype.getOutlineItem = function () {
9098 return this.outlineItem;
9099 };
9100
9101 /**
9102 * Set or unset the outline item.
9103 *
9104 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9105 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9106 * level), use #setupOutlineItem instead of this method.
9107 *
9108 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9109 * @chainable
9110 */
9111 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
9112 this.outlineItem = outlineItem || null;
9113 if ( outlineItem ) {
9114 this.setupOutlineItem();
9115 }
9116 return this;
9117 };
9118
9119 /**
9120 * Set up the outline item.
9121 *
9122 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9123 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9124 * the #setOutlineItem method instead.
9125 *
9126 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9127 * @chainable
9128 */
9129 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
9130 return this;
9131 };
9132
9133 /**
9134 * Set the page to its 'active' state.
9135 *
9136 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9137 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9138 * context, setting the active state on a page does nothing.
9139 *
9140 * @param {boolean} value Page is active
9141 * @fires active
9142 */
9143 OO.ui.PageLayout.prototype.setActive = function ( active ) {
9144 active = !!active;
9145
9146 if ( active !== this.active ) {
9147 this.active = active;
9148 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
9149 this.emit( 'active', this.active );
9150 }
9151 };
9152
9153 /**
9154 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9155 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9156 * by setting the #continuous option to 'true'.
9157 *
9158 * @example
9159 * // A stack layout with two panels, configured to be displayed continously
9160 * var myStack = new OO.ui.StackLayout( {
9161 * items: [
9162 * new OO.ui.PanelLayout( {
9163 * $content: $( '<p>Panel One</p>' ),
9164 * padded: true,
9165 * framed: true
9166 * } ),
9167 * new OO.ui.PanelLayout( {
9168 * $content: $( '<p>Panel Two</p>' ),
9169 * padded: true,
9170 * framed: true
9171 * } )
9172 * ],
9173 * continuous: true
9174 * } );
9175 * $( 'body' ).append( myStack.$element );
9176 *
9177 * @class
9178 * @extends OO.ui.PanelLayout
9179 * @mixins OO.ui.GroupElement
9180 *
9181 * @constructor
9182 * @param {Object} [config] Configuration options
9183 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9184 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9185 */
9186 OO.ui.StackLayout = function OoUiStackLayout( config ) {
9187 // Configuration initialization
9188 config = $.extend( { scrollable: true }, config );
9189
9190 // Parent constructor
9191 OO.ui.StackLayout.super.call( this, config );
9192
9193 // Mixin constructors
9194 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9195
9196 // Properties
9197 this.currentItem = null;
9198 this.continuous = !!config.continuous;
9199
9200 // Initialization
9201 this.$element.addClass( 'oo-ui-stackLayout' );
9202 if ( this.continuous ) {
9203 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
9204 }
9205 if ( Array.isArray( config.items ) ) {
9206 this.addItems( config.items );
9207 }
9208 };
9209
9210 /* Setup */
9211
9212 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
9213 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
9214
9215 /* Events */
9216
9217 /**
9218 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9219 * {@link #clearItems cleared} or {@link #setItem displayed}.
9220 *
9221 * @event set
9222 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9223 */
9224
9225 /* Methods */
9226
9227 /**
9228 * Get the current panel.
9229 *
9230 * @return {OO.ui.Layout|null}
9231 */
9232 OO.ui.StackLayout.prototype.getCurrentItem = function () {
9233 return this.currentItem;
9234 };
9235
9236 /**
9237 * Unset the current item.
9238 *
9239 * @private
9240 * @param {OO.ui.StackLayout} layout
9241 * @fires set
9242 */
9243 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
9244 var prevItem = this.currentItem;
9245 if ( prevItem === null ) {
9246 return;
9247 }
9248
9249 this.currentItem = null;
9250 this.emit( 'set', null );
9251 };
9252
9253 /**
9254 * Add panel layouts to the stack layout.
9255 *
9256 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9257 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9258 * by the index.
9259 *
9260 * @param {OO.ui.Layout[]} items Panels to add
9261 * @param {number} [index] Index of the insertion point
9262 * @chainable
9263 */
9264 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
9265 // Update the visibility
9266 this.updateHiddenState( items, this.currentItem );
9267
9268 // Mixin method
9269 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
9270
9271 if ( !this.currentItem && items.length ) {
9272 this.setItem( items[ 0 ] );
9273 }
9274
9275 return this;
9276 };
9277
9278 /**
9279 * Remove the specified panels from the stack layout.
9280 *
9281 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9282 * you may wish to use the #clearItems method instead.
9283 *
9284 * @param {OO.ui.Layout[]} items Panels to remove
9285 * @chainable
9286 * @fires set
9287 */
9288 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
9289 // Mixin method
9290 OO.ui.GroupElement.prototype.removeItems.call( this, items );
9291
9292 if ( $.inArray( this.currentItem, items ) !== -1 ) {
9293 if ( this.items.length ) {
9294 this.setItem( this.items[ 0 ] );
9295 } else {
9296 this.unsetCurrentItem();
9297 }
9298 }
9299
9300 return this;
9301 };
9302
9303 /**
9304 * Clear all panels from the stack layout.
9305 *
9306 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9307 * a subset of panels, use the #removeItems method.
9308 *
9309 * @chainable
9310 * @fires set
9311 */
9312 OO.ui.StackLayout.prototype.clearItems = function () {
9313 this.unsetCurrentItem();
9314 OO.ui.GroupElement.prototype.clearItems.call( this );
9315
9316 return this;
9317 };
9318
9319 /**
9320 * Show the specified panel.
9321 *
9322 * If another panel is currently displayed, it will be hidden.
9323 *
9324 * @param {OO.ui.Layout} item Panel to show
9325 * @chainable
9326 * @fires set
9327 */
9328 OO.ui.StackLayout.prototype.setItem = function ( item ) {
9329 if ( item !== this.currentItem ) {
9330 this.updateHiddenState( this.items, item );
9331
9332 if ( $.inArray( item, this.items ) !== -1 ) {
9333 this.currentItem = item;
9334 this.emit( 'set', item );
9335 } else {
9336 this.unsetCurrentItem();
9337 }
9338 }
9339
9340 return this;
9341 };
9342
9343 /**
9344 * Update the visibility of all items in case of non-continuous view.
9345 *
9346 * Ensure all items are hidden except for the selected one.
9347 * This method does nothing when the stack is continuous.
9348 *
9349 * @private
9350 * @param {OO.ui.Layout[]} items Item list iterate over
9351 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9352 */
9353 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
9354 var i, len;
9355
9356 if ( !this.continuous ) {
9357 for ( i = 0, len = items.length; i < len; i++ ) {
9358 if ( !selectedItem || selectedItem !== items[ i ] ) {
9359 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
9360 }
9361 }
9362 if ( selectedItem ) {
9363 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
9364 }
9365 }
9366 };
9367
9368 /**
9369 * Horizontal bar layout of tools as icon buttons.
9370 *
9371 * @class
9372 * @extends OO.ui.ToolGroup
9373 *
9374 * @constructor
9375 * @param {OO.ui.Toolbar} toolbar
9376 * @param {Object} [config] Configuration options
9377 */
9378 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
9379 // Allow passing positional parameters inside the config object
9380 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9381 config = toolbar;
9382 toolbar = config.toolbar;
9383 }
9384
9385 // Parent constructor
9386 OO.ui.BarToolGroup.super.call( this, toolbar, config );
9387
9388 // Initialization
9389 this.$element.addClass( 'oo-ui-barToolGroup' );
9390 };
9391
9392 /* Setup */
9393
9394 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
9395
9396 /* Static Properties */
9397
9398 OO.ui.BarToolGroup.static.titleTooltips = true;
9399
9400 OO.ui.BarToolGroup.static.accelTooltips = true;
9401
9402 OO.ui.BarToolGroup.static.name = 'bar';
9403
9404 /**
9405 * Popup list of tools with an icon and optional label.
9406 *
9407 * @abstract
9408 * @class
9409 * @extends OO.ui.ToolGroup
9410 * @mixins OO.ui.IconElement
9411 * @mixins OO.ui.IndicatorElement
9412 * @mixins OO.ui.LabelElement
9413 * @mixins OO.ui.TitledElement
9414 * @mixins OO.ui.ClippableElement
9415 *
9416 * @constructor
9417 * @param {OO.ui.Toolbar} toolbar
9418 * @param {Object} [config] Configuration options
9419 * @cfg {string} [header] Text to display at the top of the pop-up
9420 */
9421 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
9422 // Allow passing positional parameters inside the config object
9423 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9424 config = toolbar;
9425 toolbar = config.toolbar;
9426 }
9427
9428 // Configuration initialization
9429 config = config || {};
9430
9431 // Parent constructor
9432 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
9433
9434 // Mixin constructors
9435 OO.ui.IconElement.call( this, config );
9436 OO.ui.IndicatorElement.call( this, config );
9437 OO.ui.LabelElement.call( this, config );
9438 OO.ui.TitledElement.call( this, config );
9439 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
9440
9441 // Properties
9442 this.active = false;
9443 this.dragging = false;
9444 this.onBlurHandler = this.onBlur.bind( this );
9445 this.$handle = $( '<span>' );
9446
9447 // Events
9448 this.$handle.on( {
9449 mousedown: this.onHandlePointerDown.bind( this ),
9450 mouseup: this.onHandlePointerUp.bind( this )
9451 } );
9452
9453 // Initialization
9454 this.$handle
9455 .addClass( 'oo-ui-popupToolGroup-handle' )
9456 .append( this.$icon, this.$label, this.$indicator );
9457 // If the pop-up should have a header, add it to the top of the toolGroup.
9458 // Note: If this feature is useful for other widgets, we could abstract it into an
9459 // OO.ui.HeaderedElement mixin constructor.
9460 if ( config.header !== undefined ) {
9461 this.$group
9462 .prepend( $( '<span>' )
9463 .addClass( 'oo-ui-popupToolGroup-header' )
9464 .text( config.header )
9465 );
9466 }
9467 this.$element
9468 .addClass( 'oo-ui-popupToolGroup' )
9469 .prepend( this.$handle );
9470 };
9471
9472 /* Setup */
9473
9474 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
9475 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
9476 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
9477 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
9478 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
9479 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
9480
9481 /* Static Properties */
9482
9483 /* Methods */
9484
9485 /**
9486 * @inheritdoc
9487 */
9488 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
9489 // Parent method
9490 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
9491
9492 if ( this.isDisabled() && this.isElementAttached() ) {
9493 this.setActive( false );
9494 }
9495 };
9496
9497 /**
9498 * Handle focus being lost.
9499 *
9500 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9501 *
9502 * @param {jQuery.Event} e Mouse up event
9503 */
9504 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
9505 // Only deactivate when clicking outside the dropdown element
9506 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
9507 this.setActive( false );
9508 }
9509 };
9510
9511 /**
9512 * @inheritdoc
9513 */
9514 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
9515 // Only close toolgroup when a tool was actually selected
9516 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9517 this.setActive( false );
9518 }
9519 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9520 };
9521
9522 /**
9523 * Handle mouse up events.
9524 *
9525 * @param {jQuery.Event} e Mouse up event
9526 */
9527 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9528 return false;
9529 };
9530
9531 /**
9532 * Handle mouse down events.
9533 *
9534 * @param {jQuery.Event} e Mouse down event
9535 */
9536 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9537 if ( !this.isDisabled() && e.which === 1 ) {
9538 this.setActive( !this.active );
9539 }
9540 return false;
9541 };
9542
9543 /**
9544 * Switch into active mode.
9545 *
9546 * When active, mouseup events anywhere in the document will trigger deactivation.
9547 */
9548 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9549 value = !!value;
9550 if ( this.active !== value ) {
9551 this.active = value;
9552 if ( value ) {
9553 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9554
9555 // Try anchoring the popup to the left first
9556 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9557 this.toggleClipping( true );
9558 if ( this.isClippedHorizontally() ) {
9559 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9560 this.toggleClipping( false );
9561 this.$element
9562 .removeClass( 'oo-ui-popupToolGroup-left' )
9563 .addClass( 'oo-ui-popupToolGroup-right' );
9564 this.toggleClipping( true );
9565 }
9566 } else {
9567 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9568 this.$element.removeClass(
9569 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9570 );
9571 this.toggleClipping( false );
9572 }
9573 }
9574 };
9575
9576 /**
9577 * Drop down list layout of tools as labeled icon buttons.
9578 *
9579 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9580 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9581 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9582 *
9583 * @class
9584 * @extends OO.ui.PopupToolGroup
9585 *
9586 * @constructor
9587 * @param {OO.ui.Toolbar} toolbar
9588 * @param {Object} [config] Configuration options
9589 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9590 * shown.
9591 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9592 * allowed to be collapsed.
9593 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9594 */
9595 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9596 // Allow passing positional parameters inside the config object
9597 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9598 config = toolbar;
9599 toolbar = config.toolbar;
9600 }
9601
9602 // Configuration initialization
9603 config = config || {};
9604
9605 // Properties (must be set before parent constructor, which calls #populate)
9606 this.allowCollapse = config.allowCollapse;
9607 this.forceExpand = config.forceExpand;
9608 this.expanded = config.expanded !== undefined ? config.expanded : false;
9609 this.collapsibleTools = [];
9610
9611 // Parent constructor
9612 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9613
9614 // Initialization
9615 this.$element.addClass( 'oo-ui-listToolGroup' );
9616 };
9617
9618 /* Setup */
9619
9620 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9621
9622 /* Static Properties */
9623
9624 OO.ui.ListToolGroup.static.accelTooltips = true;
9625
9626 OO.ui.ListToolGroup.static.name = 'list';
9627
9628 /* Methods */
9629
9630 /**
9631 * @inheritdoc
9632 */
9633 OO.ui.ListToolGroup.prototype.populate = function () {
9634 var i, len, allowCollapse = [];
9635
9636 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9637
9638 // Update the list of collapsible tools
9639 if ( this.allowCollapse !== undefined ) {
9640 allowCollapse = this.allowCollapse;
9641 } else if ( this.forceExpand !== undefined ) {
9642 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9643 }
9644
9645 this.collapsibleTools = [];
9646 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9647 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9648 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9649 }
9650 }
9651
9652 // Keep at the end, even when tools are added
9653 this.$group.append( this.getExpandCollapseTool().$element );
9654
9655 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9656 this.updateCollapsibleState();
9657 };
9658
9659 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9660 if ( this.expandCollapseTool === undefined ) {
9661 var ExpandCollapseTool = function () {
9662 ExpandCollapseTool.super.apply( this, arguments );
9663 };
9664
9665 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9666
9667 ExpandCollapseTool.prototype.onSelect = function () {
9668 this.toolGroup.expanded = !this.toolGroup.expanded;
9669 this.toolGroup.updateCollapsibleState();
9670 this.setActive( false );
9671 };
9672 ExpandCollapseTool.prototype.onUpdateState = function () {
9673 // Do nothing. Tool interface requires an implementation of this function.
9674 };
9675
9676 ExpandCollapseTool.static.name = 'more-fewer';
9677
9678 this.expandCollapseTool = new ExpandCollapseTool( this );
9679 }
9680 return this.expandCollapseTool;
9681 };
9682
9683 /**
9684 * @inheritdoc
9685 */
9686 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9687 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9688
9689 // Do not close the popup when the user wants to show more/fewer tools
9690 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9691 // Prevent the popup list from being hidden
9692 this.setActive( true );
9693 }
9694
9695 return ret;
9696 };
9697
9698 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9699 var i, len;
9700
9701 this.getExpandCollapseTool()
9702 .setIcon( this.expanded ? 'collapse' : 'expand' )
9703 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9704
9705 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9706 this.collapsibleTools[ i ].toggle( this.expanded );
9707 }
9708 };
9709
9710 /**
9711 * Drop down menu layout of tools as selectable menu items.
9712 *
9713 * @class
9714 * @extends OO.ui.PopupToolGroup
9715 *
9716 * @constructor
9717 * @param {OO.ui.Toolbar} toolbar
9718 * @param {Object} [config] Configuration options
9719 */
9720 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9721 // Allow passing positional parameters inside the config object
9722 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9723 config = toolbar;
9724 toolbar = config.toolbar;
9725 }
9726
9727 // Configuration initialization
9728 config = config || {};
9729
9730 // Parent constructor
9731 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9732
9733 // Events
9734 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9735
9736 // Initialization
9737 this.$element.addClass( 'oo-ui-menuToolGroup' );
9738 };
9739
9740 /* Setup */
9741
9742 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9743
9744 /* Static Properties */
9745
9746 OO.ui.MenuToolGroup.static.accelTooltips = true;
9747
9748 OO.ui.MenuToolGroup.static.name = 'menu';
9749
9750 /* Methods */
9751
9752 /**
9753 * Handle the toolbar state being updated.
9754 *
9755 * When the state changes, the title of each active item in the menu will be joined together and
9756 * used as a label for the group. The label will be empty if none of the items are active.
9757 */
9758 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9759 var name,
9760 labelTexts = [];
9761
9762 for ( name in this.tools ) {
9763 if ( this.tools[ name ].isActive() ) {
9764 labelTexts.push( this.tools[ name ].getTitle() );
9765 }
9766 }
9767
9768 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9769 };
9770
9771 /**
9772 * Tool that shows a popup when selected.
9773 *
9774 * @abstract
9775 * @class
9776 * @extends OO.ui.Tool
9777 * @mixins OO.ui.PopupElement
9778 *
9779 * @constructor
9780 * @param {OO.ui.ToolGroup} toolGroup
9781 * @param {Object} [config] Configuration options
9782 */
9783 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
9784 // Allow passing positional parameters inside the config object
9785 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9786 config = toolGroup;
9787 toolGroup = config.toolGroup;
9788 }
9789
9790 // Parent constructor
9791 OO.ui.PopupTool.super.call( this, toolGroup, config );
9792
9793 // Mixin constructors
9794 OO.ui.PopupElement.call( this, config );
9795
9796 // Initialization
9797 this.$element
9798 .addClass( 'oo-ui-popupTool' )
9799 .append( this.popup.$element );
9800 };
9801
9802 /* Setup */
9803
9804 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9805 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9806
9807 /* Methods */
9808
9809 /**
9810 * Handle the tool being selected.
9811 *
9812 * @inheritdoc
9813 */
9814 OO.ui.PopupTool.prototype.onSelect = function () {
9815 if ( !this.isDisabled() ) {
9816 this.popup.toggle();
9817 }
9818 this.setActive( false );
9819 return false;
9820 };
9821
9822 /**
9823 * Handle the toolbar state being updated.
9824 *
9825 * @inheritdoc
9826 */
9827 OO.ui.PopupTool.prototype.onUpdateState = function () {
9828 this.setActive( false );
9829 };
9830
9831 /**
9832 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9833 * menus in toolbars (T74159).
9834 *
9835 * @abstract
9836 * @class
9837 * @extends OO.ui.Tool
9838 *
9839 * @constructor
9840 * @param {OO.ui.ToolGroup} toolGroup
9841 * @param {Object} [config] Configuration options
9842 */
9843 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
9844 // Allow passing positional parameters inside the config object
9845 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9846 config = toolGroup;
9847 toolGroup = config.toolGroup;
9848 }
9849
9850 // Parent constructor
9851 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
9852
9853 // Properties
9854 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
9855
9856 // Initialization
9857 this.$link.remove();
9858 this.$element
9859 .addClass( 'oo-ui-toolGroupTool' )
9860 .append( this.innerToolGroup.$element );
9861 };
9862
9863 /* Setup */
9864
9865 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
9866
9867 /* Static Properties */
9868
9869 /**
9870 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9871 *
9872 * @property {Object.<string,Array>}
9873 */
9874 OO.ui.ToolGroupTool.static.groupConfig = {};
9875
9876 /* Methods */
9877
9878 /**
9879 * Handle the tool being selected.
9880 *
9881 * @inheritdoc
9882 */
9883 OO.ui.ToolGroupTool.prototype.onSelect = function () {
9884 this.innerToolGroup.setActive( !this.innerToolGroup.active );
9885 return false;
9886 };
9887
9888 /**
9889 * Handle the toolbar state being updated.
9890 *
9891 * @inheritdoc
9892 */
9893 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
9894 this.setActive( false );
9895 };
9896
9897 /**
9898 * Build a OO.ui.ToolGroup from the configuration.
9899 *
9900 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9901 * accepted values.
9902 * @return {OO.ui.ListToolGroup}
9903 */
9904 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
9905 if ( group.include === '*' ) {
9906 // Apply defaults to catch-all groups
9907 if ( group.label === undefined ) {
9908 group.label = OO.ui.msg( 'ooui-toolbar-more' );
9909 }
9910 }
9911
9912 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
9913 };
9914
9915 /**
9916 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9917 *
9918 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9919 *
9920 * @private
9921 * @abstract
9922 * @class
9923 * @extends OO.ui.GroupElement
9924 *
9925 * @constructor
9926 * @param {Object} [config] Configuration options
9927 */
9928 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9929 // Parent constructor
9930 OO.ui.GroupWidget.super.call( this, config );
9931 };
9932
9933 /* Setup */
9934
9935 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9936
9937 /* Methods */
9938
9939 /**
9940 * Set the disabled state of the widget.
9941 *
9942 * This will also update the disabled state of child widgets.
9943 *
9944 * @param {boolean} disabled Disable widget
9945 * @chainable
9946 */
9947 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9948 var i, len;
9949
9950 // Parent method
9951 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9952 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9953
9954 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9955 if ( this.items ) {
9956 for ( i = 0, len = this.items.length; i < len; i++ ) {
9957 this.items[ i ].updateDisabled();
9958 }
9959 }
9960
9961 return this;
9962 };
9963
9964 /**
9965 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9966 *
9967 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9968 * allows bidirectional communication.
9969 *
9970 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9971 *
9972 * @private
9973 * @abstract
9974 * @class
9975 *
9976 * @constructor
9977 */
9978 OO.ui.ItemWidget = function OoUiItemWidget() {
9979 //
9980 };
9981
9982 /* Methods */
9983
9984 /**
9985 * Check if widget is disabled.
9986 *
9987 * Checks parent if present, making disabled state inheritable.
9988 *
9989 * @return {boolean} Widget is disabled
9990 */
9991 OO.ui.ItemWidget.prototype.isDisabled = function () {
9992 return this.disabled ||
9993 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9994 };
9995
9996 /**
9997 * Set group element is in.
9998 *
9999 * @param {OO.ui.GroupElement|null} group Group element, null if none
10000 * @chainable
10001 */
10002 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
10003 // Parent method
10004 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
10005 OO.ui.Element.prototype.setElementGroup.call( this, group );
10006
10007 // Initialize item disabled states
10008 this.updateDisabled();
10009
10010 return this;
10011 };
10012
10013 /**
10014 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
10015 * Controls include moving items up and down, removing items, and adding different kinds of items.
10016 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
10017 *
10018 * @class
10019 * @extends OO.ui.Widget
10020 * @mixins OO.ui.GroupElement
10021 * @mixins OO.ui.IconElement
10022 *
10023 * @constructor
10024 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
10025 * @param {Object} [config] Configuration options
10026 * @cfg {Object} [abilities] List of abilties
10027 * @cfg {boolean} [abilities.move=true] Allow moving movable items
10028 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
10029 */
10030 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
10031 // Allow passing positional parameters inside the config object
10032 if ( OO.isPlainObject( outline ) && config === undefined ) {
10033 config = outline;
10034 outline = config.outline;
10035 }
10036
10037 // Configuration initialization
10038 config = $.extend( { icon: 'add' }, config );
10039
10040 // Parent constructor
10041 OO.ui.OutlineControlsWidget.super.call( this, config );
10042
10043 // Mixin constructors
10044 OO.ui.GroupElement.call( this, config );
10045 OO.ui.IconElement.call( this, config );
10046
10047 // Properties
10048 this.outline = outline;
10049 this.$movers = $( '<div>' );
10050 this.upButton = new OO.ui.ButtonWidget( {
10051 framed: false,
10052 icon: 'collapse',
10053 title: OO.ui.msg( 'ooui-outline-control-move-up' )
10054 } );
10055 this.downButton = new OO.ui.ButtonWidget( {
10056 framed: false,
10057 icon: 'expand',
10058 title: OO.ui.msg( 'ooui-outline-control-move-down' )
10059 } );
10060 this.removeButton = new OO.ui.ButtonWidget( {
10061 framed: false,
10062 icon: 'remove',
10063 title: OO.ui.msg( 'ooui-outline-control-remove' )
10064 } );
10065 this.abilities = { move: true, remove: true };
10066
10067 // Events
10068 outline.connect( this, {
10069 select: 'onOutlineChange',
10070 add: 'onOutlineChange',
10071 remove: 'onOutlineChange'
10072 } );
10073 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
10074 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
10075 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
10076
10077 // Initialization
10078 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
10079 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
10080 this.$movers
10081 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10082 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
10083 this.$element.append( this.$icon, this.$group, this.$movers );
10084 this.setAbilities( config.abilities || {} );
10085 };
10086
10087 /* Setup */
10088
10089 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
10090 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
10091 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
10092
10093 /* Events */
10094
10095 /**
10096 * @event move
10097 * @param {number} places Number of places to move
10098 */
10099
10100 /**
10101 * @event remove
10102 */
10103
10104 /* Methods */
10105
10106 /**
10107 * Set abilities.
10108 *
10109 * @param {Object} abilities List of abilties
10110 * @param {boolean} [abilities.move] Allow moving movable items
10111 * @param {boolean} [abilities.remove] Allow removing removable items
10112 */
10113 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
10114 var ability;
10115
10116 for ( ability in this.abilities ) {
10117 if ( abilities[ability] !== undefined ) {
10118 this.abilities[ability] = !!abilities[ability];
10119 }
10120 }
10121
10122 this.onOutlineChange();
10123 };
10124
10125 /**
10126 *
10127 * @private
10128 * Handle outline change events.
10129 */
10130 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
10131 var i, len, firstMovable, lastMovable,
10132 items = this.outline.getItems(),
10133 selectedItem = this.outline.getSelectedItem(),
10134 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
10135 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
10136
10137 if ( movable ) {
10138 i = -1;
10139 len = items.length;
10140 while ( ++i < len ) {
10141 if ( items[ i ].isMovable() ) {
10142 firstMovable = items[ i ];
10143 break;
10144 }
10145 }
10146 i = len;
10147 while ( i-- ) {
10148 if ( items[ i ].isMovable() ) {
10149 lastMovable = items[ i ];
10150 break;
10151 }
10152 }
10153 }
10154 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
10155 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
10156 this.removeButton.setDisabled( !removable );
10157 };
10158
10159 /**
10160 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
10161 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10162 *
10163 * @abstract
10164 * @class
10165 *
10166 * @constructor
10167 * @param {Object} [config] Configuration options
10168 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10169 * By default, the toggle is in the 'off' state.
10170 */
10171 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
10172 // Configuration initialization
10173 config = config || {};
10174
10175 // Properties
10176 this.value = null;
10177
10178 // Initialization
10179 this.$element.addClass( 'oo-ui-toggleWidget' );
10180 this.setValue( !!config.value );
10181 };
10182
10183 /* Events */
10184
10185 /**
10186 * @event change
10187 *
10188 * A change event is emitted when the on/off state of the toggle changes.
10189 *
10190 * @param {boolean} value Value representing the new state of the toggle
10191 */
10192
10193 /* Methods */
10194
10195 /**
10196 * Get the value representing the toggle’s state.
10197 *
10198 * @return {boolean} The on/off state of the toggle
10199 */
10200 OO.ui.ToggleWidget.prototype.getValue = function () {
10201 return this.value;
10202 };
10203
10204 /**
10205 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10206 *
10207 * @param {boolean} value The state of the toggle
10208 * @fires change
10209 * @chainable
10210 */
10211 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
10212 value = !!value;
10213 if ( this.value !== value ) {
10214 this.value = value;
10215 this.emit( 'change', value );
10216 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
10217 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
10218 this.$element.attr( 'aria-checked', value.toString() );
10219 }
10220 return this;
10221 };
10222
10223 /**
10224 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10225 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10226 * removed, and cleared from the group.
10227 *
10228 * @example
10229 * // Example: A ButtonGroupWidget with two buttons
10230 * var button1 = new OO.ui.PopupButtonWidget( {
10231 * label: 'Select a category',
10232 * icon: 'menu',
10233 * popup: {
10234 * $content: $( '<p>List of categories...</p>' ),
10235 * padded: true,
10236 * align: 'left'
10237 * }
10238 * } );
10239 * var button2 = new OO.ui.ButtonWidget( {
10240 * label: 'Add item'
10241 * });
10242 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10243 * items: [button1, button2]
10244 * } );
10245 * $( 'body' ).append( buttonGroup.$element );
10246 *
10247 * @class
10248 * @extends OO.ui.Widget
10249 * @mixins OO.ui.GroupElement
10250 *
10251 * @constructor
10252 * @param {Object} [config] Configuration options
10253 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10254 */
10255 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
10256 // Configuration initialization
10257 config = config || {};
10258
10259 // Parent constructor
10260 OO.ui.ButtonGroupWidget.super.call( this, config );
10261
10262 // Mixin constructors
10263 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10264
10265 // Initialization
10266 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
10267 if ( Array.isArray( config.items ) ) {
10268 this.addItems( config.items );
10269 }
10270 };
10271
10272 /* Setup */
10273
10274 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
10275 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
10276
10277 /**
10278 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10279 * feels, and functionality can be customized via the class’s configuration options
10280 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10281 * and examples.
10282 *
10283 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10284 *
10285 * @example
10286 * // A button widget
10287 * var button = new OO.ui.ButtonWidget( {
10288 * label: 'Button with Icon',
10289 * icon: 'remove',
10290 * iconTitle: 'Remove'
10291 * } );
10292 * $( 'body' ).append( button.$element );
10293 *
10294 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10295 *
10296 * @class
10297 * @extends OO.ui.Widget
10298 * @mixins OO.ui.ButtonElement
10299 * @mixins OO.ui.IconElement
10300 * @mixins OO.ui.IndicatorElement
10301 * @mixins OO.ui.LabelElement
10302 * @mixins OO.ui.TitledElement
10303 * @mixins OO.ui.FlaggedElement
10304 * @mixins OO.ui.TabIndexedElement
10305 *
10306 * @constructor
10307 * @param {Object} [config] Configuration options
10308 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10309 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10310 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10311 */
10312 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
10313 // Configuration initialization
10314 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10315 config = $.extend( { noFollow: config && config.nofollow }, config );
10316
10317 // Parent constructor
10318 OO.ui.ButtonWidget.super.call( this, config );
10319
10320 // Mixin constructors
10321 OO.ui.ButtonElement.call( this, config );
10322 OO.ui.IconElement.call( this, config );
10323 OO.ui.IndicatorElement.call( this, config );
10324 OO.ui.LabelElement.call( this, config );
10325 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10326 OO.ui.FlaggedElement.call( this, config );
10327 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10328
10329 // Properties
10330 this.href = null;
10331 this.target = null;
10332 this.noFollow = false;
10333 this.isHyperlink = false;
10334
10335 // Initialization
10336 this.$button.append( this.$icon, this.$label, this.$indicator );
10337 this.$element
10338 .addClass( 'oo-ui-buttonWidget' )
10339 .append( this.$button );
10340 this.setHref( config.href );
10341 this.setTarget( config.target );
10342 this.setNoFollow( config.noFollow );
10343 };
10344
10345 /* Setup */
10346
10347 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10348 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10349 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10350 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10351 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10352 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10353 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10354 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10355
10356 /* Methods */
10357
10358 /**
10359 * @inheritdoc
10360 */
10361 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10362 if ( !this.isDisabled() ) {
10363 // Remove the tab-index while the button is down to prevent the button from stealing focus
10364 this.$button.removeAttr( 'tabindex' );
10365 }
10366
10367 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10368 };
10369
10370 /**
10371 * @inheritdoc
10372 */
10373 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10374 if ( !this.isDisabled() ) {
10375 // Restore the tab-index after the button is up to restore the button's accessibility
10376 this.$button.attr( 'tabindex', this.tabIndex );
10377 }
10378
10379 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10380 };
10381
10382 /**
10383 * @inheritdoc
10384 */
10385 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10386 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10387 if ( this.isHyperlink ) {
10388 return true;
10389 }
10390 return ret;
10391 };
10392
10393 /**
10394 * @inheritdoc
10395 */
10396 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10397 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10398 if ( this.isHyperlink ) {
10399 return true;
10400 }
10401 return ret;
10402 };
10403
10404 /**
10405 * Get hyperlink location.
10406 *
10407 * @return {string} Hyperlink location
10408 */
10409 OO.ui.ButtonWidget.prototype.getHref = function () {
10410 return this.href;
10411 };
10412
10413 /**
10414 * Get hyperlink target.
10415 *
10416 * @return {string} Hyperlink target
10417 */
10418 OO.ui.ButtonWidget.prototype.getTarget = function () {
10419 return this.target;
10420 };
10421
10422 /**
10423 * Get search engine traversal hint.
10424 *
10425 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10426 */
10427 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10428 return this.noFollow;
10429 };
10430
10431 /**
10432 * Set hyperlink location.
10433 *
10434 * @param {string|null} href Hyperlink location, null to remove
10435 */
10436 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10437 href = typeof href === 'string' ? href : null;
10438
10439 if ( href !== this.href ) {
10440 this.href = href;
10441 if ( href !== null ) {
10442 this.$button.attr( 'href', href );
10443 this.isHyperlink = true;
10444 } else {
10445 this.$button.removeAttr( 'href' );
10446 this.isHyperlink = false;
10447 }
10448 }
10449
10450 return this;
10451 };
10452
10453 /**
10454 * Set hyperlink target.
10455 *
10456 * @param {string|null} target Hyperlink target, null to remove
10457 */
10458 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10459 target = typeof target === 'string' ? target : null;
10460
10461 if ( target !== this.target ) {
10462 this.target = target;
10463 if ( target !== null ) {
10464 this.$button.attr( 'target', target );
10465 } else {
10466 this.$button.removeAttr( 'target' );
10467 }
10468 }
10469
10470 return this;
10471 };
10472
10473 /**
10474 * Set search engine traversal hint.
10475 *
10476 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10477 */
10478 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10479 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10480
10481 if ( noFollow !== this.noFollow ) {
10482 this.noFollow = noFollow;
10483 if ( noFollow ) {
10484 this.$button.attr( 'rel', 'nofollow' );
10485 } else {
10486 this.$button.removeAttr( 'rel' );
10487 }
10488 }
10489
10490 return this;
10491 };
10492
10493 /**
10494 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10495 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10496 * of the actions.
10497 *
10498 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10499 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10500 * and examples.
10501 *
10502 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10503 *
10504 * @class
10505 * @extends OO.ui.ButtonWidget
10506 * @mixins OO.ui.PendingElement
10507 *
10508 * @constructor
10509 * @param {Object} [config] Configuration options
10510 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10511 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10512 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10513 * for more information about setting modes.
10514 * @cfg {boolean} [framed=false] Render the action button with a frame
10515 */
10516 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10517 // Configuration initialization
10518 config = $.extend( { framed: false }, config );
10519
10520 // Parent constructor
10521 OO.ui.ActionWidget.super.call( this, config );
10522
10523 // Mixin constructors
10524 OO.ui.PendingElement.call( this, config );
10525
10526 // Properties
10527 this.action = config.action || '';
10528 this.modes = config.modes || [];
10529 this.width = 0;
10530 this.height = 0;
10531
10532 // Initialization
10533 this.$element.addClass( 'oo-ui-actionWidget' );
10534 };
10535
10536 /* Setup */
10537
10538 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10539 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10540
10541 /* Events */
10542
10543 /**
10544 * A resize event is emitted when the size of the widget changes.
10545 *
10546 * @event resize
10547 */
10548
10549 /* Methods */
10550
10551 /**
10552 * Check if the action is configured to be available in the specified `mode`.
10553 *
10554 * @param {string} mode Name of mode
10555 * @return {boolean} The action is configured with the mode
10556 */
10557 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10558 return this.modes.indexOf( mode ) !== -1;
10559 };
10560
10561 /**
10562 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10563 *
10564 * @return {string}
10565 */
10566 OO.ui.ActionWidget.prototype.getAction = function () {
10567 return this.action;
10568 };
10569
10570 /**
10571 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10572 *
10573 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10574 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10575 * are hidden.
10576 *
10577 * @return {string[]}
10578 */
10579 OO.ui.ActionWidget.prototype.getModes = function () {
10580 return this.modes.slice();
10581 };
10582
10583 /**
10584 * Emit a resize event if the size has changed.
10585 *
10586 * @private
10587 * @chainable
10588 */
10589 OO.ui.ActionWidget.prototype.propagateResize = function () {
10590 var width, height;
10591
10592 if ( this.isElementAttached() ) {
10593 width = this.$element.width();
10594 height = this.$element.height();
10595
10596 if ( width !== this.width || height !== this.height ) {
10597 this.width = width;
10598 this.height = height;
10599 this.emit( 'resize' );
10600 }
10601 }
10602
10603 return this;
10604 };
10605
10606 /**
10607 * @inheritdoc
10608 */
10609 OO.ui.ActionWidget.prototype.setIcon = function () {
10610 // Mixin method
10611 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10612 this.propagateResize();
10613
10614 return this;
10615 };
10616
10617 /**
10618 * @inheritdoc
10619 */
10620 OO.ui.ActionWidget.prototype.setLabel = function () {
10621 // Mixin method
10622 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10623 this.propagateResize();
10624
10625 return this;
10626 };
10627
10628 /**
10629 * @inheritdoc
10630 */
10631 OO.ui.ActionWidget.prototype.setFlags = function () {
10632 // Mixin method
10633 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10634 this.propagateResize();
10635
10636 return this;
10637 };
10638
10639 /**
10640 * @inheritdoc
10641 */
10642 OO.ui.ActionWidget.prototype.clearFlags = function () {
10643 // Mixin method
10644 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10645 this.propagateResize();
10646
10647 return this;
10648 };
10649
10650 /**
10651 * Toggle the visibility of the action button.
10652 *
10653 * @param {boolean} [show] Show button, omit to toggle visibility
10654 * @chainable
10655 */
10656 OO.ui.ActionWidget.prototype.toggle = function () {
10657 // Parent method
10658 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10659 this.propagateResize();
10660
10661 return this;
10662 };
10663
10664 /**
10665 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10666 * which is used to display additional information or options.
10667 *
10668 * @example
10669 * // Example of a popup button.
10670 * var popupButton = new OO.ui.PopupButtonWidget( {
10671 * label: 'Popup button with options',
10672 * icon: 'menu',
10673 * popup: {
10674 * $content: $( '<p>Additional options here.</p>' ),
10675 * padded: true,
10676 * align: 'left'
10677 * }
10678 * } );
10679 * // Append the button to the DOM.
10680 * $( 'body' ).append( popupButton.$element );
10681 *
10682 * @class
10683 * @extends OO.ui.ButtonWidget
10684 * @mixins OO.ui.PopupElement
10685 *
10686 * @constructor
10687 * @param {Object} [config] Configuration options
10688 */
10689 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10690 // Parent constructor
10691 OO.ui.PopupButtonWidget.super.call( this, config );
10692
10693 // Mixin constructors
10694 OO.ui.PopupElement.call( this, config );
10695
10696 // Events
10697 this.connect( this, { click: 'onAction' } );
10698
10699 // Initialization
10700 this.$element
10701 .addClass( 'oo-ui-popupButtonWidget' )
10702 .attr( 'aria-haspopup', 'true' )
10703 .append( this.popup.$element );
10704 };
10705
10706 /* Setup */
10707
10708 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10709 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10710
10711 /* Methods */
10712
10713 /**
10714 * Handle the button action being triggered.
10715 *
10716 * @private
10717 */
10718 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10719 this.popup.toggle();
10720 };
10721
10722 /**
10723 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10724 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10725 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10726 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10727 * and {@link OO.ui.LabelElement labels}. Please see
10728 * the [OOjs UI documentation][1] on MediaWiki for more information.
10729 *
10730 * @example
10731 * // Toggle buttons in the 'off' and 'on' state.
10732 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10733 * label: 'Toggle Button off'
10734 * } );
10735 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10736 * label: 'Toggle Button on',
10737 * value: true
10738 * } );
10739 * // Append the buttons to the DOM.
10740 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10741 *
10742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10743 *
10744 * @class
10745 * @extends OO.ui.ButtonWidget
10746 * @mixins OO.ui.ToggleWidget
10747 *
10748 * @constructor
10749 * @param {Object} [config] Configuration options
10750 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10751 * state. By default, the button is in the 'off' state.
10752 */
10753 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10754 // Configuration initialization
10755 config = config || {};
10756
10757 // Parent constructor
10758 OO.ui.ToggleButtonWidget.super.call( this, config );
10759
10760 // Mixin constructors
10761 OO.ui.ToggleWidget.call( this, config );
10762
10763 // Events
10764 this.connect( this, { click: 'onAction' } );
10765
10766 // Initialization
10767 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10768 };
10769
10770 /* Setup */
10771
10772 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10773 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10774
10775 /* Methods */
10776
10777 /**
10778 *
10779 * @private
10780 * Handle the button action being triggered.
10781 */
10782 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10783 this.setValue( !this.value );
10784 };
10785
10786 /**
10787 * @inheritdoc
10788 */
10789 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10790 value = !!value;
10791 if ( value !== this.value ) {
10792 this.$button.attr( 'aria-pressed', value.toString() );
10793 this.setActive( value );
10794 }
10795
10796 // Parent method (from mixin)
10797 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10798
10799 return this;
10800 };
10801
10802 /**
10803 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10804 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10805 * users can interact with it.
10806 *
10807 * @example
10808 * // Example: A DropdownWidget with a menu that contains three options
10809 * var dropDown = new OO.ui.DropdownWidget( {
10810 * label: 'Dropdown menu: Select a menu option',
10811 * menu: {
10812 * items: [
10813 * new OO.ui.MenuOptionWidget( {
10814 * data: 'a',
10815 * label: 'First'
10816 * } ),
10817 * new OO.ui.MenuOptionWidget( {
10818 * data: 'b',
10819 * label: 'Second'
10820 * } ),
10821 * new OO.ui.MenuOptionWidget( {
10822 * data: 'c',
10823 * label: 'Third'
10824 * } )
10825 * ]
10826 * }
10827 * } );
10828 *
10829 * $( 'body' ).append( dropDown.$element );
10830 *
10831 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10832 *
10833 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10834 *
10835 * @class
10836 * @extends OO.ui.Widget
10837 * @mixins OO.ui.IconElement
10838 * @mixins OO.ui.IndicatorElement
10839 * @mixins OO.ui.LabelElement
10840 * @mixins OO.ui.TitledElement
10841 * @mixins OO.ui.TabIndexedElement
10842 *
10843 * @constructor
10844 * @param {Object} [config] Configuration options
10845 * @cfg {Object} [menu] Configuration options to pass to menu widget
10846 */
10847 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10848 // Configuration initialization
10849 config = $.extend( { indicator: 'down' }, config );
10850
10851 // Parent constructor
10852 OO.ui.DropdownWidget.super.call( this, config );
10853
10854 // Properties (must be set before TabIndexedElement constructor call)
10855 this.$handle = this.$( '<span>' );
10856
10857 // Mixin constructors
10858 OO.ui.IconElement.call( this, config );
10859 OO.ui.IndicatorElement.call( this, config );
10860 OO.ui.LabelElement.call( this, config );
10861 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10862 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10863
10864 // Properties
10865 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
10866
10867 // Events
10868 this.$handle.on( {
10869 click: this.onClick.bind( this ),
10870 keypress: this.onKeyPress.bind( this )
10871 } );
10872 this.menu.connect( this, { select: 'onMenuSelect' } );
10873
10874 // Initialization
10875 this.$handle
10876 .addClass( 'oo-ui-dropdownWidget-handle' )
10877 .append( this.$icon, this.$label, this.$indicator );
10878 this.$element
10879 .addClass( 'oo-ui-dropdownWidget' )
10880 .append( this.$handle, this.menu.$element );
10881 };
10882
10883 /* Setup */
10884
10885 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10886 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10887 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10888 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10889 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10890 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
10891
10892 /* Methods */
10893
10894 /**
10895 * Get the menu.
10896 *
10897 * @return {OO.ui.MenuSelectWidget} Menu of widget
10898 */
10899 OO.ui.DropdownWidget.prototype.getMenu = function () {
10900 return this.menu;
10901 };
10902
10903 /**
10904 * Handles menu select events.
10905 *
10906 * @private
10907 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10908 */
10909 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10910 var selectedLabel;
10911
10912 if ( !item ) {
10913 return;
10914 }
10915
10916 selectedLabel = item.getLabel();
10917
10918 // If the label is a DOM element, clone it, because setLabel will append() it
10919 if ( selectedLabel instanceof jQuery ) {
10920 selectedLabel = selectedLabel.clone();
10921 }
10922
10923 this.setLabel( selectedLabel );
10924 };
10925
10926 /**
10927 * Handle mouse click events.
10928 *
10929 * @private
10930 * @param {jQuery.Event} e Mouse click event
10931 */
10932 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10933 if ( !this.isDisabled() && e.which === 1 ) {
10934 this.menu.toggle();
10935 }
10936 return false;
10937 };
10938
10939 /**
10940 * Handle key press events.
10941 *
10942 * @private
10943 * @param {jQuery.Event} e Key press event
10944 */
10945 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
10946 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10947 this.menu.toggle();
10948 return false;
10949 }
10950 };
10951
10952 /**
10953 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10954 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10955 * for a list of icons included in the library.
10956 *
10957 * @example
10958 * // An icon widget with a label
10959 * var myIcon = new OO.ui.IconWidget( {
10960 * icon: 'help',
10961 * iconTitle: 'Help'
10962 * } );
10963 * // Create a label.
10964 * var iconLabel = new OO.ui.LabelWidget( {
10965 * label: 'Help'
10966 * } );
10967 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10968 *
10969 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10970 *
10971 * @class
10972 * @extends OO.ui.Widget
10973 * @mixins OO.ui.IconElement
10974 * @mixins OO.ui.TitledElement
10975 * @mixins OO.ui.FlaggedElement
10976 *
10977 * @constructor
10978 * @param {Object} [config] Configuration options
10979 */
10980 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10981 // Configuration initialization
10982 config = config || {};
10983
10984 // Parent constructor
10985 OO.ui.IconWidget.super.call( this, config );
10986
10987 // Mixin constructors
10988 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10989 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10990 OO.ui.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
10991
10992 // Initialization
10993 this.$element.addClass( 'oo-ui-iconWidget' );
10994 };
10995
10996 /* Setup */
10997
10998 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10999 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
11000 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
11001 OO.mixinClass( OO.ui.IconWidget, OO.ui.FlaggedElement );
11002
11003 /* Static Properties */
11004
11005 OO.ui.IconWidget.static.tagName = 'span';
11006
11007 /**
11008 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
11009 * attention to the status of an item or to clarify the function of a control. For a list of
11010 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
11011 *
11012 * @example
11013 * // Example of an indicator widget
11014 * var indicator1 = new OO.ui.IndicatorWidget( {
11015 * indicator: 'alert'
11016 * } );
11017 *
11018 * // Create a fieldset layout to add a label
11019 * var fieldset = new OO.ui.FieldsetLayout();
11020 * fieldset.addItems( [
11021 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
11022 * ] );
11023 * $( 'body' ).append( fieldset.$element );
11024 *
11025 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
11026 *
11027 * @class
11028 * @extends OO.ui.Widget
11029 * @mixins OO.ui.IndicatorElement
11030 * @mixins OO.ui.TitledElement
11031 *
11032 * @constructor
11033 * @param {Object} [config] Configuration options
11034 */
11035 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
11036 // Configuration initialization
11037 config = config || {};
11038
11039 // Parent constructor
11040 OO.ui.IndicatorWidget.super.call( this, config );
11041
11042 // Mixin constructors
11043 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
11044 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11045
11046 // Initialization
11047 this.$element.addClass( 'oo-ui-indicatorWidget' );
11048 };
11049
11050 /* Setup */
11051
11052 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
11053 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
11054 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
11055
11056 /* Static Properties */
11057
11058 OO.ui.IndicatorWidget.static.tagName = 'span';
11059
11060 /**
11061 * InputWidget is the base class for all input widgets, which
11062 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11063 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11064 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11065 *
11066 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11067 *
11068 * @abstract
11069 * @class
11070 * @extends OO.ui.Widget
11071 * @mixins OO.ui.FlaggedElement
11072 * @mixins OO.ui.TabIndexedElement
11073 *
11074 * @constructor
11075 * @param {Object} [config] Configuration options
11076 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11077 * @cfg {string} [value=''] The value of the input.
11078 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11079 * before it is accepted.
11080 */
11081 OO.ui.InputWidget = function OoUiInputWidget( config ) {
11082 // Configuration initialization
11083 config = config || {};
11084
11085 // Parent constructor
11086 OO.ui.InputWidget.super.call( this, config );
11087
11088 // Properties
11089 this.$input = this.getInputElement( config );
11090 this.value = '';
11091 this.inputFilter = config.inputFilter;
11092
11093 // Mixin constructors
11094 OO.ui.FlaggedElement.call( this, config );
11095 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
11096
11097 // Events
11098 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
11099
11100 // Initialization
11101 this.$input
11102 .attr( 'name', config.name )
11103 .prop( 'disabled', this.isDisabled() );
11104 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
11105 this.setValue( config.value );
11106 };
11107
11108 /* Setup */
11109
11110 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
11111 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
11112 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
11113
11114 /* Events */
11115
11116 /**
11117 * @event change
11118 *
11119 * A change event is emitted when the value of the input changes.
11120 *
11121 * @param {string} value
11122 */
11123
11124 /* Methods */
11125
11126 /**
11127 * Get input element.
11128 *
11129 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11130 * different circumstances. The element must have a `value` property (like form elements).
11131 *
11132 * @private
11133 * @param {Object} config Configuration options
11134 * @return {jQuery} Input element
11135 */
11136 OO.ui.InputWidget.prototype.getInputElement = function () {
11137 return $( '<input>' );
11138 };
11139
11140 /**
11141 * Handle potentially value-changing events.
11142 *
11143 * @private
11144 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11145 */
11146 OO.ui.InputWidget.prototype.onEdit = function () {
11147 var widget = this;
11148 if ( !this.isDisabled() ) {
11149 // Allow the stack to clear so the value will be updated
11150 setTimeout( function () {
11151 widget.setValue( widget.$input.val() );
11152 } );
11153 }
11154 };
11155
11156 /**
11157 * Get the value of the input.
11158 *
11159 * @return {string} Input value
11160 */
11161 OO.ui.InputWidget.prototype.getValue = function () {
11162 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11163 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11164 var value = this.$input.val();
11165 if ( this.value !== value ) {
11166 this.setValue( value );
11167 }
11168 return this.value;
11169 };
11170
11171 /**
11172 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11173 *
11174 * @param {boolean} isRTL
11175 * Direction is right-to-left
11176 */
11177 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
11178 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
11179 };
11180
11181 /**
11182 * Set the value of the input.
11183 *
11184 * @param {string} value New value
11185 * @fires change
11186 * @chainable
11187 */
11188 OO.ui.InputWidget.prototype.setValue = function ( value ) {
11189 value = this.cleanUpValue( value );
11190 // Update the DOM if it has changed. Note that with cleanUpValue, it
11191 // is possible for the DOM value to change without this.value changing.
11192 if ( this.$input.val() !== value ) {
11193 this.$input.val( value );
11194 }
11195 if ( this.value !== value ) {
11196 this.value = value;
11197 this.emit( 'change', this.value );
11198 }
11199 return this;
11200 };
11201
11202 /**
11203 * Clean up incoming value.
11204 *
11205 * Ensures value is a string, and converts undefined and null to empty string.
11206 *
11207 * @private
11208 * @param {string} value Original value
11209 * @return {string} Cleaned up value
11210 */
11211 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
11212 if ( value === undefined || value === null ) {
11213 return '';
11214 } else if ( this.inputFilter ) {
11215 return this.inputFilter( String( value ) );
11216 } else {
11217 return String( value );
11218 }
11219 };
11220
11221 /**
11222 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11223 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11224 * called directly.
11225 */
11226 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
11227 if ( !this.isDisabled() ) {
11228 if ( this.$input.is( ':checkbox, :radio' ) ) {
11229 this.$input.click();
11230 }
11231 if ( this.$input.is( ':input' ) ) {
11232 this.$input[ 0 ].focus();
11233 }
11234 }
11235 };
11236
11237 /**
11238 * @inheritdoc
11239 */
11240 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
11241 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
11242 if ( this.$input ) {
11243 this.$input.prop( 'disabled', this.isDisabled() );
11244 }
11245 return this;
11246 };
11247
11248 /**
11249 * Focus the input.
11250 *
11251 * @chainable
11252 */
11253 OO.ui.InputWidget.prototype.focus = function () {
11254 this.$input[ 0 ].focus();
11255 return this;
11256 };
11257
11258 /**
11259 * Blur the input.
11260 *
11261 * @chainable
11262 */
11263 OO.ui.InputWidget.prototype.blur = function () {
11264 this.$input[ 0 ].blur();
11265 return this;
11266 };
11267
11268 /**
11269 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11270 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11271 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11272 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11273 * [OOjs UI documentation on MediaWiki] [1] for more information.
11274 *
11275 * @example
11276 * // A ButtonInputWidget rendered as an HTML button, the default.
11277 * var button = new OO.ui.ButtonInputWidget( {
11278 * label: 'Input button',
11279 * icon: 'check',
11280 * value: 'check'
11281 * } );
11282 * $( 'body' ).append( button.$element );
11283 *
11284 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11285 *
11286 * @class
11287 * @extends OO.ui.InputWidget
11288 * @mixins OO.ui.ButtonElement
11289 * @mixins OO.ui.IconElement
11290 * @mixins OO.ui.IndicatorElement
11291 * @mixins OO.ui.LabelElement
11292 * @mixins OO.ui.TitledElement
11293 * @mixins OO.ui.FlaggedElement
11294 *
11295 * @constructor
11296 * @param {Object} [config] Configuration options
11297 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11298 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11299 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11300 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11301 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11302 */
11303 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
11304 // Configuration initialization
11305 config = $.extend( { type: 'button', useInputTag: false }, config );
11306
11307 // Properties (must be set before parent constructor, which calls #setValue)
11308 this.useInputTag = config.useInputTag;
11309
11310 // Parent constructor
11311 OO.ui.ButtonInputWidget.super.call( this, config );
11312
11313 // Mixin constructors
11314 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
11315 OO.ui.IconElement.call( this, config );
11316 OO.ui.IndicatorElement.call( this, config );
11317 OO.ui.LabelElement.call( this, config );
11318 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
11319 OO.ui.FlaggedElement.call( this, config );
11320
11321 // Initialization
11322 if ( !config.useInputTag ) {
11323 this.$input.append( this.$icon, this.$label, this.$indicator );
11324 }
11325 this.$element.addClass( 'oo-ui-buttonInputWidget' );
11326 };
11327
11328 /* Setup */
11329
11330 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
11331 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
11332 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
11333 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
11334 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
11335 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
11336 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
11337
11338 /* Methods */
11339
11340 /**
11341 * @inheritdoc
11342 * @private
11343 */
11344 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
11345 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
11346 return $( html );
11347 };
11348
11349 /**
11350 * Set label value.
11351 *
11352 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11353 *
11354 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11355 * text, or `null` for no label
11356 * @chainable
11357 */
11358 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
11359 OO.ui.LabelElement.prototype.setLabel.call( this, label );
11360
11361 if ( this.useInputTag ) {
11362 if ( typeof label === 'function' ) {
11363 label = OO.ui.resolveMsg( label );
11364 }
11365 if ( label instanceof jQuery ) {
11366 label = label.text();
11367 }
11368 if ( !label ) {
11369 label = '';
11370 }
11371 this.$input.val( label );
11372 }
11373
11374 return this;
11375 };
11376
11377 /**
11378 * Set the value of the input.
11379 *
11380 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11381 * they do not support {@link #value values}.
11382 *
11383 * @param {string} value New value
11384 * @chainable
11385 */
11386 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11387 if ( !this.useInputTag ) {
11388 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11389 }
11390 return this;
11391 };
11392
11393 /**
11394 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11395 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11396 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11397 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11398 *
11399 * @example
11400 * // An example of selected, unselected, and disabled checkbox inputs
11401 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11402 * value: 'a',
11403 * selected: true
11404 * } );
11405 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11406 * value: 'b'
11407 * } );
11408 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11409 * value:'c',
11410 * disabled: true
11411 * } );
11412 * // Create a fieldset layout with fields for each checkbox.
11413 * var fieldset = new OO.ui.FieldsetLayout( {
11414 * label: 'Checkboxes'
11415 * } );
11416 * fieldset.addItems( [
11417 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11418 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11419 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11420 * ] );
11421 * $( 'body' ).append( fieldset.$element );
11422 *
11423 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11424 *
11425 * @class
11426 * @extends OO.ui.InputWidget
11427 *
11428 * @constructor
11429 * @param {Object} [config] Configuration options
11430 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11431 */
11432 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11433 // Configuration initialization
11434 config = config || {};
11435
11436 // Parent constructor
11437 OO.ui.CheckboxInputWidget.super.call( this, config );
11438
11439 // Initialization
11440 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11441 this.setSelected( config.selected !== undefined ? config.selected : false );
11442 };
11443
11444 /* Setup */
11445
11446 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11447
11448 /* Methods */
11449
11450 /**
11451 * @inheritdoc
11452 * @private
11453 */
11454 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11455 return $( '<input type="checkbox" />' );
11456 };
11457
11458 /**
11459 * @inheritdoc
11460 */
11461 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11462 var widget = this;
11463 if ( !this.isDisabled() ) {
11464 // Allow the stack to clear so the value will be updated
11465 setTimeout( function () {
11466 widget.setSelected( widget.$input.prop( 'checked' ) );
11467 } );
11468 }
11469 };
11470
11471 /**
11472 * Set selection state of this checkbox.
11473 *
11474 * @param {boolean} state `true` for selected
11475 * @chainable
11476 */
11477 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11478 state = !!state;
11479 if ( this.selected !== state ) {
11480 this.selected = state;
11481 this.$input.prop( 'checked', this.selected );
11482 this.emit( 'change', this.selected );
11483 }
11484 return this;
11485 };
11486
11487 /**
11488 * Check if this checkbox is selected.
11489 *
11490 * @return {boolean} Checkbox is selected
11491 */
11492 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11493 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11494 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11495 var selected = this.$input.prop( 'checked' );
11496 if ( this.selected !== selected ) {
11497 this.setSelected( selected );
11498 }
11499 return this.selected;
11500 };
11501
11502 /**
11503 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11504 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11505 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11506 * more information about input widgets.
11507 *
11508 * @example
11509 * // Example: A DropdownInputWidget with three options
11510 * var dropDown = new OO.ui.DropdownInputWidget( {
11511 * label: 'Dropdown menu: Select a menu option',
11512 * options: [
11513 * { data: 'a', label: 'First' } ,
11514 * { data: 'b', label: 'Second'} ,
11515 * { data: 'c', label: 'Third' }
11516 * ]
11517 * } );
11518 * $( 'body' ).append( dropDown.$element );
11519 *
11520 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11521 *
11522 * @class
11523 * @extends OO.ui.InputWidget
11524 *
11525 * @constructor
11526 * @param {Object} [config] Configuration options
11527 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11528 */
11529 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11530 // Configuration initialization
11531 config = config || {};
11532
11533 // Properties (must be done before parent constructor which calls #setDisabled)
11534 this.dropdownWidget = new OO.ui.DropdownWidget();
11535
11536 // Parent constructor
11537 OO.ui.DropdownInputWidget.super.call( this, config );
11538
11539 // Events
11540 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11541
11542 // Initialization
11543 this.setOptions( config.options || [] );
11544 this.$element
11545 .addClass( 'oo-ui-dropdownInputWidget' )
11546 .append( this.dropdownWidget.$element );
11547 };
11548
11549 /* Setup */
11550
11551 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11552
11553 /* Methods */
11554
11555 /**
11556 * @inheritdoc
11557 * @private
11558 */
11559 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11560 return $( '<input type="hidden">' );
11561 };
11562
11563 /**
11564 * Handles menu select events.
11565 *
11566 * @private
11567 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11568 */
11569 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11570 this.setValue( item.getData() );
11571 };
11572
11573 /**
11574 * @inheritdoc
11575 */
11576 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11577 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11578 if ( item ) {
11579 this.dropdownWidget.getMenu().selectItem( item );
11580 }
11581 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11582 return this;
11583 };
11584
11585 /**
11586 * @inheritdoc
11587 */
11588 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11589 this.dropdownWidget.setDisabled( state );
11590 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11591 return this;
11592 };
11593
11594 /**
11595 * Set the options available for this input.
11596 *
11597 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11598 * @chainable
11599 */
11600 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11601 var value = this.getValue();
11602
11603 // Rebuild the dropdown menu
11604 this.dropdownWidget.getMenu()
11605 .clearItems()
11606 .addItems( options.map( function ( opt ) {
11607 return new OO.ui.MenuOptionWidget( {
11608 data: opt.data,
11609 label: opt.label !== undefined ? opt.label : opt.data
11610 } );
11611 } ) );
11612
11613 // Restore the previous value, or reset to something sensible
11614 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11615 // Previous value is still available, ensure consistency with the dropdown
11616 this.setValue( value );
11617 } else {
11618 // No longer valid, reset
11619 if ( options.length ) {
11620 this.setValue( options[ 0 ].data );
11621 }
11622 }
11623
11624 return this;
11625 };
11626
11627 /**
11628 * @inheritdoc
11629 */
11630 OO.ui.DropdownInputWidget.prototype.focus = function () {
11631 this.dropdownWidget.getMenu().toggle( true );
11632 return this;
11633 };
11634
11635 /**
11636 * @inheritdoc
11637 */
11638 OO.ui.DropdownInputWidget.prototype.blur = function () {
11639 this.dropdownWidget.getMenu().toggle( false );
11640 return this;
11641 };
11642
11643 /**
11644 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11645 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11646 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11647 * please see the [OOjs UI documentation on MediaWiki][1].
11648 *
11649 * @example
11650 * // An example of selected, unselected, and disabled radio inputs
11651 * var radio1 = new OO.ui.RadioInputWidget( {
11652 * value: 'a',
11653 * selected: true
11654 * } );
11655 * var radio2 = new OO.ui.RadioInputWidget( {
11656 * value: 'b'
11657 * } );
11658 * var radio3 = new OO.ui.RadioInputWidget( {
11659 * value: 'c',
11660 * disabled: true
11661 * } );
11662 * // Create a fieldset layout with fields for each radio button.
11663 * var fieldset = new OO.ui.FieldsetLayout( {
11664 * label: 'Radio inputs'
11665 * } );
11666 * fieldset.addItems( [
11667 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11668 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11669 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11670 * ] );
11671 * $( 'body' ).append( fieldset.$element );
11672 *
11673 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11674 *
11675 * @class
11676 * @extends OO.ui.InputWidget
11677 *
11678 * @constructor
11679 * @param {Object} [config] Configuration options
11680 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11681 */
11682 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11683 // Configuration initialization
11684 config = config || {};
11685
11686 // Parent constructor
11687 OO.ui.RadioInputWidget.super.call( this, config );
11688
11689 // Initialization
11690 this.$element.addClass( 'oo-ui-radioInputWidget' );
11691 this.setSelected( config.selected !== undefined ? config.selected : false );
11692 };
11693
11694 /* Setup */
11695
11696 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11697
11698 /* Methods */
11699
11700 /**
11701 * @inheritdoc
11702 * @private
11703 */
11704 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11705 return $( '<input type="radio" />' );
11706 };
11707
11708 /**
11709 * @inheritdoc
11710 */
11711 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11712 // RadioInputWidget doesn't track its state.
11713 };
11714
11715 /**
11716 * Set selection state of this radio button.
11717 *
11718 * @param {boolean} state `true` for selected
11719 * @chainable
11720 */
11721 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11722 // RadioInputWidget doesn't track its state.
11723 this.$input.prop( 'checked', state );
11724 return this;
11725 };
11726
11727 /**
11728 * Check if this radio button is selected.
11729 *
11730 * @return {boolean} Radio is selected
11731 */
11732 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11733 return this.$input.prop( 'checked' );
11734 };
11735
11736 /**
11737 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11738 * size of the field as well as its presentation. In addition, these widgets can be configured
11739 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11740 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11741 * which modifies incoming values rather than validating them.
11742 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11743 *
11744 * @example
11745 * // Example of a text input widget
11746 * var textInput = new OO.ui.TextInputWidget( {
11747 * value: 'Text input'
11748 * } )
11749 * $( 'body' ).append( textInput.$element );
11750 *
11751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11752 *
11753 * @class
11754 * @extends OO.ui.InputWidget
11755 * @mixins OO.ui.IconElement
11756 * @mixins OO.ui.IndicatorElement
11757 * @mixins OO.ui.PendingElement
11758 * @mixins OO.ui.LabelElement
11759 *
11760 * @constructor
11761 * @param {Object} [config] Configuration options
11762 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11763 * @cfg {string} [placeholder] Placeholder text
11764 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11765 * instruct the browser to focus this widget.
11766 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11767 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11768 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11769 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11770 * Use the #maxRows config to specify a maximum number of displayed rows.
11771 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11772 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11773 * the value or placeholder text: `'before'` or `'after'`
11774 * @cfg {boolean} [required=false] Mark the field as required
11775 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11776 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11777 * or 'integer' (the value must contain only numbers).
11778 */
11779 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
11780 // Configuration initialization
11781 config = $.extend( {
11782 type: 'text',
11783 labelPosition: 'after',
11784 maxRows: 10
11785 }, config );
11786
11787 // Parent constructor
11788 OO.ui.TextInputWidget.super.call( this, config );
11789
11790 // Mixin constructors
11791 OO.ui.IconElement.call( this, config );
11792 OO.ui.IndicatorElement.call( this, config );
11793 OO.ui.PendingElement.call( this, config );
11794 OO.ui.LabelElement.call( this, config );
11795
11796 // Properties
11797 this.readOnly = false;
11798 this.multiline = !!config.multiline;
11799 this.autosize = !!config.autosize;
11800 this.maxRows = config.maxRows;
11801 this.validate = null;
11802
11803 // Clone for resizing
11804 if ( this.autosize ) {
11805 this.$clone = this.$input
11806 .clone()
11807 .insertAfter( this.$input )
11808 .attr( 'aria-hidden', 'true' )
11809 .addClass( 'oo-ui-element-hidden' );
11810 }
11811
11812 this.setValidation( config.validate );
11813 this.setLabelPosition( config.labelPosition );
11814
11815 // Events
11816 this.$input.on( {
11817 keypress: this.onKeyPress.bind( this ),
11818 blur: this.setValidityFlag.bind( this )
11819 } );
11820 this.$input.one( {
11821 focus: this.onElementAttach.bind( this )
11822 } );
11823 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11824 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11825 this.on( 'labelChange', this.updatePosition.bind( this ) );
11826
11827 // Initialization
11828 this.$element
11829 .addClass( 'oo-ui-textInputWidget' )
11830 .append( this.$icon, this.$indicator );
11831 this.setReadOnly( !!config.readOnly );
11832 if ( config.placeholder ) {
11833 this.$input.attr( 'placeholder', config.placeholder );
11834 }
11835 if ( config.maxLength !== undefined ) {
11836 this.$input.attr( 'maxlength', config.maxLength );
11837 }
11838 if ( config.autofocus ) {
11839 this.$input.attr( 'autofocus', 'autofocus' );
11840 }
11841 if ( config.required ) {
11842 this.$input.attr( 'required', 'true' );
11843 }
11844 if ( this.label || config.autosize ) {
11845 this.installParentChangeDetector();
11846 }
11847 };
11848
11849 /* Setup */
11850
11851 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11852 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11853 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11854 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11855 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11856
11857 /* Static properties */
11858
11859 OO.ui.TextInputWidget.static.validationPatterns = {
11860 'non-empty': /.+/,
11861 integer: /^\d+$/
11862 };
11863
11864 /* Events */
11865
11866 /**
11867 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11868 *
11869 * Not emitted if the input is multiline.
11870 *
11871 * @event enter
11872 */
11873
11874 /* Methods */
11875
11876 /**
11877 * Handle icon mouse down events.
11878 *
11879 * @private
11880 * @param {jQuery.Event} e Mouse down event
11881 * @fires icon
11882 */
11883 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11884 if ( e.which === 1 ) {
11885 this.$input[ 0 ].focus();
11886 return false;
11887 }
11888 };
11889
11890 /**
11891 * Handle indicator mouse down events.
11892 *
11893 * @private
11894 * @param {jQuery.Event} e Mouse down event
11895 * @fires indicator
11896 */
11897 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11898 if ( e.which === 1 ) {
11899 this.$input[ 0 ].focus();
11900 return false;
11901 }
11902 };
11903
11904 /**
11905 * Handle key press events.
11906 *
11907 * @private
11908 * @param {jQuery.Event} e Key press event
11909 * @fires enter If enter key is pressed and input is not multiline
11910 */
11911 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11912 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11913 this.emit( 'enter', e );
11914 }
11915 };
11916
11917 /**
11918 * Handle element attach events.
11919 *
11920 * @private
11921 * @param {jQuery.Event} e Element attach event
11922 */
11923 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11924 // Any previously calculated size is now probably invalid if we reattached elsewhere
11925 this.valCache = null;
11926 this.adjustSize();
11927 this.positionLabel();
11928 };
11929
11930 /**
11931 * @inheritdoc
11932 */
11933 OO.ui.TextInputWidget.prototype.onEdit = function () {
11934 this.adjustSize();
11935
11936 // Parent method
11937 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11938 };
11939
11940 /**
11941 * @inheritdoc
11942 */
11943 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11944 // Parent method
11945 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11946
11947 this.setValidityFlag();
11948 this.adjustSize();
11949 return this;
11950 };
11951
11952 /**
11953 * Check if the input is {@link #readOnly read-only}.
11954 *
11955 * @return {boolean}
11956 */
11957 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11958 return this.readOnly;
11959 };
11960
11961 /**
11962 * Set the {@link #readOnly read-only} state of the input.
11963 *
11964 * @param {boolean} state Make input read-only
11965 * @chainable
11966 */
11967 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11968 this.readOnly = !!state;
11969 this.$input.prop( 'readOnly', this.readOnly );
11970 return this;
11971 };
11972
11973 /**
11974 * Support function for making #onElementAttach work across browsers.
11975 *
11976 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11977 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11978 *
11979 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11980 * first time that the element gets attached to the documented.
11981 */
11982 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
11983 var mutationObserver, onRemove, topmostNode, fakeParentNode,
11984 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
11985 widget = this;
11986
11987 if ( MutationObserver ) {
11988 // The new way. If only it wasn't so ugly.
11989
11990 if ( this.$element.closest( 'html' ).length ) {
11991 // Widget is attached already, do nothing. This breaks the functionality of this function when
11992 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11993 // would require observation of the whole document, which would hurt performance of other,
11994 // more important code.
11995 return;
11996 }
11997
11998 // Find topmost node in the tree
11999 topmostNode = this.$element[0];
12000 while ( topmostNode.parentNode ) {
12001 topmostNode = topmostNode.parentNode;
12002 }
12003
12004 // We have no way to detect the $element being attached somewhere without observing the entire
12005 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
12006 // parent node of $element, and instead detect when $element is removed from it (and thus
12007 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
12008 // doesn't get attached, we end up back here and create the parent.
12009
12010 mutationObserver = new MutationObserver( function ( mutations ) {
12011 var i, j, removedNodes;
12012 for ( i = 0; i < mutations.length; i++ ) {
12013 removedNodes = mutations[ i ].removedNodes;
12014 for ( j = 0; j < removedNodes.length; j++ ) {
12015 if ( removedNodes[ j ] === topmostNode ) {
12016 setTimeout( onRemove, 0 );
12017 return;
12018 }
12019 }
12020 }
12021 } );
12022
12023 onRemove = function () {
12024 // If the node was attached somewhere else, report it
12025 if ( widget.$element.closest( 'html' ).length ) {
12026 widget.onElementAttach();
12027 }
12028 mutationObserver.disconnect();
12029 widget.installParentChangeDetector();
12030 };
12031
12032 // Create a fake parent and observe it
12033 fakeParentNode = $( '<div>' ).append( this.$element )[0];
12034 mutationObserver.observe( fakeParentNode, { childList: true } );
12035 } else {
12036 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12037 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12038 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
12039 }
12040 };
12041
12042 /**
12043 * Automatically adjust the size of the text input.
12044 *
12045 * This only affects #multiline inputs that are {@link #autosize autosized}.
12046 *
12047 * @chainable
12048 */
12049 OO.ui.TextInputWidget.prototype.adjustSize = function () {
12050 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
12051
12052 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
12053 this.$clone
12054 .val( this.$input.val() )
12055 .attr( 'rows', '' )
12056 // Set inline height property to 0 to measure scroll height
12057 .css( 'height', 0 );
12058
12059 this.$clone.removeClass( 'oo-ui-element-hidden' );
12060
12061 this.valCache = this.$input.val();
12062
12063 scrollHeight = this.$clone[ 0 ].scrollHeight;
12064
12065 // Remove inline height property to measure natural heights
12066 this.$clone.css( 'height', '' );
12067 innerHeight = this.$clone.innerHeight();
12068 outerHeight = this.$clone.outerHeight();
12069
12070 // Measure max rows height
12071 this.$clone
12072 .attr( 'rows', this.maxRows )
12073 .css( 'height', 'auto' )
12074 .val( '' );
12075 maxInnerHeight = this.$clone.innerHeight();
12076
12077 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12078 // Equals 1 on Blink-based browsers and 0 everywhere else
12079 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
12080 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
12081
12082 this.$clone.addClass( 'oo-ui-element-hidden' );
12083
12084 // Only apply inline height when expansion beyond natural height is needed
12085 if ( idealHeight > innerHeight ) {
12086 // Use the difference between the inner and outer height as a buffer
12087 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
12088 } else {
12089 this.$input.css( 'height', '' );
12090 }
12091 }
12092 return this;
12093 };
12094
12095 /**
12096 * @inheritdoc
12097 * @private
12098 */
12099 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
12100 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
12101 };
12102
12103 /**
12104 * Check if the input supports multiple lines.
12105 *
12106 * @return {boolean}
12107 */
12108 OO.ui.TextInputWidget.prototype.isMultiline = function () {
12109 return !!this.multiline;
12110 };
12111
12112 /**
12113 * Check if the input automatically adjusts its size.
12114 *
12115 * @return {boolean}
12116 */
12117 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
12118 return !!this.autosize;
12119 };
12120
12121 /**
12122 * Select the entire text of the input.
12123 *
12124 * @chainable
12125 */
12126 OO.ui.TextInputWidget.prototype.select = function () {
12127 this.$input.select();
12128 return this;
12129 };
12130
12131 /**
12132 * Set the validation pattern.
12133 *
12134 * The validation pattern is either a regular expression or the symbolic name of a pattern
12135 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12136 * value must contain only numbers).
12137 *
12138 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12139 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12140 */
12141 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
12142 if ( validate instanceof RegExp ) {
12143 this.validate = validate;
12144 } else {
12145 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
12146 }
12147 };
12148
12149 /**
12150 * Sets the 'invalid' flag appropriately.
12151 */
12152 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
12153 var widget = this;
12154 this.isValid().done( function ( valid ) {
12155 widget.setFlags( { invalid: !valid } );
12156 } );
12157 };
12158
12159 /**
12160 * Check if a value is valid.
12161 *
12162 * This method returns a promise that resolves with a boolean `true` if the current value is
12163 * considered valid according to the supplied {@link #validate validation pattern}.
12164 *
12165 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12166 */
12167 OO.ui.TextInputWidget.prototype.isValid = function () {
12168 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
12169 };
12170
12171 /**
12172 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12173 *
12174 * @param {string} labelPosition Label position, 'before' or 'after'
12175 * @chainable
12176 */
12177 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
12178 this.labelPosition = labelPosition;
12179 this.updatePosition();
12180 return this;
12181 };
12182
12183 /**
12184 * Deprecated alias of #setLabelPosition
12185 *
12186 * @deprecated Use setLabelPosition instead.
12187 */
12188 OO.ui.TextInputWidget.prototype.setPosition =
12189 OO.ui.TextInputWidget.prototype.setLabelPosition;
12190
12191 /**
12192 * Update the position of the inline label.
12193 *
12194 * This method is called by #setLabelPosition, and can also be called on its own if
12195 * something causes the label to be mispositioned.
12196 *
12197 *
12198 * @chainable
12199 */
12200 OO.ui.TextInputWidget.prototype.updatePosition = function () {
12201 var after = this.labelPosition === 'after';
12202
12203 this.$element
12204 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
12205 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
12206
12207 if ( this.label ) {
12208 this.positionLabel();
12209 }
12210
12211 return this;
12212 };
12213
12214 /**
12215 * Position the label by setting the correct padding on the input.
12216 *
12217 * @private
12218 * @chainable
12219 */
12220 OO.ui.TextInputWidget.prototype.positionLabel = function () {
12221 // Clear old values
12222 this.$input
12223 // Clear old values if present
12224 .css( {
12225 'padding-right': '',
12226 'padding-left': ''
12227 } );
12228
12229 if ( this.label ) {
12230 this.$element.append( this.$label );
12231 } else {
12232 this.$label.detach();
12233 return;
12234 }
12235
12236 var after = this.labelPosition === 'after',
12237 rtl = this.$element.css( 'direction' ) === 'rtl',
12238 property = after === rtl ? 'padding-left' : 'padding-right';
12239
12240 this.$input.css( property, this.$label.outerWidth( true ) );
12241
12242 return this;
12243 };
12244
12245 /**
12246 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12247 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12248 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12249 *
12250 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12251 * option, that option will appear to be selected.
12252 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12253 * input field.
12254 *
12255 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12256 *
12257 * @example
12258 * // Example: A ComboBoxWidget.
12259 * var comboBox = new OO.ui.ComboBoxWidget( {
12260 * label: 'ComboBoxWidget',
12261 * input: { value: 'Option One' },
12262 * menu: {
12263 * items: [
12264 * new OO.ui.MenuOptionWidget( {
12265 * data: 'Option 1',
12266 * label: 'Option One'
12267 * } ),
12268 * new OO.ui.MenuOptionWidget( {
12269 * data: 'Option 2',
12270 * label: 'Option Two'
12271 * } ),
12272 * new OO.ui.MenuOptionWidget( {
12273 * data: 'Option 3',
12274 * label: 'Option Three'
12275 * } ),
12276 * new OO.ui.MenuOptionWidget( {
12277 * data: 'Option 4',
12278 * label: 'Option Four'
12279 * } ),
12280 * new OO.ui.MenuOptionWidget( {
12281 * data: 'Option 5',
12282 * label: 'Option Five'
12283 * } )
12284 * ]
12285 * }
12286 * } );
12287 * $( 'body' ).append( comboBox.$element );
12288 *
12289 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12290 *
12291 * @class
12292 * @extends OO.ui.Widget
12293 * @mixins OO.ui.TabIndexedElement
12294 *
12295 * @constructor
12296 * @param {Object} [config] Configuration options
12297 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12298 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12299 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12300 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12301 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12302 */
12303 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
12304 // Configuration initialization
12305 config = config || {};
12306
12307 // Parent constructor
12308 OO.ui.ComboBoxWidget.super.call( this, config );
12309
12310 // Properties (must be set before TabIndexedElement constructor call)
12311 this.$indicator = this.$( '<span>' );
12312
12313 // Mixin constructors
12314 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
12315
12316 // Properties
12317 this.$overlay = config.$overlay || this.$element;
12318 this.input = new OO.ui.TextInputWidget( $.extend(
12319 {
12320 indicator: 'down',
12321 $indicator: this.$indicator,
12322 disabled: this.isDisabled()
12323 },
12324 config.input
12325 ) );
12326 this.input.$input.eq( 0 ).attr( {
12327 role: 'combobox',
12328 'aria-autocomplete': 'list'
12329 } );
12330 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
12331 {
12332 widget: this,
12333 input: this.input,
12334 disabled: this.isDisabled()
12335 },
12336 config.menu
12337 ) );
12338
12339 // Events
12340 this.$indicator.on( {
12341 click: this.onClick.bind( this ),
12342 keypress: this.onKeyPress.bind( this )
12343 } );
12344 this.input.connect( this, {
12345 change: 'onInputChange',
12346 enter: 'onInputEnter'
12347 } );
12348 this.menu.connect( this, {
12349 choose: 'onMenuChoose',
12350 add: 'onMenuItemsChange',
12351 remove: 'onMenuItemsChange'
12352 } );
12353
12354 // Initialization
12355 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
12356 this.$overlay.append( this.menu.$element );
12357 this.onMenuItemsChange();
12358 };
12359
12360 /* Setup */
12361
12362 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
12363 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
12364
12365 /* Methods */
12366
12367 /**
12368 * Get the combobox's menu.
12369 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12370 */
12371 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
12372 return this.menu;
12373 };
12374
12375 /**
12376 * Handle input change events.
12377 *
12378 * @private
12379 * @param {string} value New value
12380 */
12381 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
12382 var match = this.menu.getItemFromData( value );
12383
12384 this.menu.selectItem( match );
12385 if ( this.menu.getHighlightedItem() ) {
12386 this.menu.highlightItem( match );
12387 }
12388
12389 if ( !this.isDisabled() ) {
12390 this.menu.toggle( true );
12391 }
12392 };
12393
12394 /**
12395 * Handle mouse click events.
12396 *
12397 *
12398 * @private
12399 * @param {jQuery.Event} e Mouse click event
12400 */
12401 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
12402 if ( !this.isDisabled() && e.which === 1 ) {
12403 this.menu.toggle();
12404 this.input.$input[ 0 ].focus();
12405 }
12406 return false;
12407 };
12408
12409 /**
12410 * Handle key press events.
12411 *
12412 *
12413 * @private
12414 * @param {jQuery.Event} e Key press event
12415 */
12416 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
12417 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
12418 this.menu.toggle();
12419 this.input.$input[ 0 ].focus();
12420 return false;
12421 }
12422 };
12423
12424 /**
12425 * Handle input enter events.
12426 *
12427 * @private
12428 */
12429 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
12430 if ( !this.isDisabled() ) {
12431 this.menu.toggle( false );
12432 }
12433 };
12434
12435 /**
12436 * Handle menu choose events.
12437 *
12438 * @private
12439 * @param {OO.ui.OptionWidget} item Chosen item
12440 */
12441 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
12442 this.input.setValue( item.getData() );
12443 };
12444
12445 /**
12446 * Handle menu item change events.
12447 *
12448 * @private
12449 */
12450 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
12451 var match = this.menu.getItemFromData( this.input.getValue() );
12452 this.menu.selectItem( match );
12453 if ( this.menu.getHighlightedItem() ) {
12454 this.menu.highlightItem( match );
12455 }
12456 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
12457 };
12458
12459 /**
12460 * @inheritdoc
12461 */
12462 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
12463 // Parent method
12464 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
12465
12466 if ( this.input ) {
12467 this.input.setDisabled( this.isDisabled() );
12468 }
12469 if ( this.menu ) {
12470 this.menu.setDisabled( this.isDisabled() );
12471 }
12472
12473 return this;
12474 };
12475
12476 /**
12477 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12478 * be configured with a `label` option that is set to a string, a label node, or a function:
12479 *
12480 * - String: a plaintext string
12481 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12482 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12483 * - Function: a function that will produce a string in the future. Functions are used
12484 * in cases where the value of the label is not currently defined.
12485 *
12486 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12487 * will come into focus when the label is clicked.
12488 *
12489 * @example
12490 * // Examples of LabelWidgets
12491 * var label1 = new OO.ui.LabelWidget( {
12492 * label: 'plaintext label'
12493 * } );
12494 * var label2 = new OO.ui.LabelWidget( {
12495 * label: $( '<a href="default.html">jQuery label</a>' )
12496 * } );
12497 * // Create a fieldset layout with fields for each example
12498 * var fieldset = new OO.ui.FieldsetLayout();
12499 * fieldset.addItems( [
12500 * new OO.ui.FieldLayout( label1 ),
12501 * new OO.ui.FieldLayout( label2 )
12502 * ] );
12503 * $( 'body' ).append( fieldset.$element );
12504 *
12505 *
12506 * @class
12507 * @extends OO.ui.Widget
12508 * @mixins OO.ui.LabelElement
12509 *
12510 * @constructor
12511 * @param {Object} [config] Configuration options
12512 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12513 * Clicking the label will focus the specified input field.
12514 */
12515 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
12516 // Configuration initialization
12517 config = config || {};
12518
12519 // Parent constructor
12520 OO.ui.LabelWidget.super.call( this, config );
12521
12522 // Mixin constructors
12523 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
12524 OO.ui.TitledElement.call( this, config );
12525
12526 // Properties
12527 this.input = config.input;
12528
12529 // Events
12530 if ( this.input instanceof OO.ui.InputWidget ) {
12531 this.$element.on( 'click', this.onClick.bind( this ) );
12532 }
12533
12534 // Initialization
12535 this.$element.addClass( 'oo-ui-labelWidget' );
12536 };
12537
12538 /* Setup */
12539
12540 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
12541 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
12542 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
12543
12544 /* Static Properties */
12545
12546 OO.ui.LabelWidget.static.tagName = 'span';
12547
12548 /* Methods */
12549
12550 /**
12551 * Handles label mouse click events.
12552 *
12553 * @private
12554 * @param {jQuery.Event} e Mouse click event
12555 */
12556 OO.ui.LabelWidget.prototype.onClick = function () {
12557 this.input.simulateLabelClick();
12558 return false;
12559 };
12560
12561 /**
12562 * OptionWidgets are special elements that can be selected and configured with data. The
12563 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12564 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12565 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12566 *
12567 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12568 *
12569 * @class
12570 * @extends OO.ui.Widget
12571 * @mixins OO.ui.LabelElement
12572 * @mixins OO.ui.FlaggedElement
12573 *
12574 * @constructor
12575 * @param {Object} [config] Configuration options
12576 */
12577 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
12578 // Configuration initialization
12579 config = config || {};
12580
12581 // Parent constructor
12582 OO.ui.OptionWidget.super.call( this, config );
12583
12584 // Mixin constructors
12585 OO.ui.ItemWidget.call( this );
12586 OO.ui.LabelElement.call( this, config );
12587 OO.ui.FlaggedElement.call( this, config );
12588
12589 // Properties
12590 this.selected = false;
12591 this.highlighted = false;
12592 this.pressed = false;
12593
12594 // Initialization
12595 this.$element
12596 .data( 'oo-ui-optionWidget', this )
12597 .attr( 'role', 'option' )
12598 .addClass( 'oo-ui-optionWidget' )
12599 .append( this.$label );
12600 };
12601
12602 /* Setup */
12603
12604 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12605 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12606 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12607 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12608
12609 /* Static Properties */
12610
12611 OO.ui.OptionWidget.static.selectable = true;
12612
12613 OO.ui.OptionWidget.static.highlightable = true;
12614
12615 OO.ui.OptionWidget.static.pressable = true;
12616
12617 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12618
12619 /* Methods */
12620
12621 /**
12622 * Check if the option can be selected.
12623 *
12624 * @return {boolean} Item is selectable
12625 */
12626 OO.ui.OptionWidget.prototype.isSelectable = function () {
12627 return this.constructor.static.selectable && !this.isDisabled();
12628 };
12629
12630 /**
12631 * Check if the option can be highlighted. A highlight indicates that the option
12632 * may be selected when a user presses enter or clicks. Disabled items cannot
12633 * be highlighted.
12634 *
12635 * @return {boolean} Item is highlightable
12636 */
12637 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12638 return this.constructor.static.highlightable && !this.isDisabled();
12639 };
12640
12641 /**
12642 * Check if the option can be pressed. The pressed state occurs when a user mouses
12643 * down on an item, but has not yet let go of the mouse.
12644 *
12645 * @return {boolean} Item is pressable
12646 */
12647 OO.ui.OptionWidget.prototype.isPressable = function () {
12648 return this.constructor.static.pressable && !this.isDisabled();
12649 };
12650
12651 /**
12652 * Check if the option is selected.
12653 *
12654 * @return {boolean} Item is selected
12655 */
12656 OO.ui.OptionWidget.prototype.isSelected = function () {
12657 return this.selected;
12658 };
12659
12660 /**
12661 * Check if the option is highlighted. A highlight indicates that the
12662 * item may be selected when a user presses enter or clicks.
12663 *
12664 * @return {boolean} Item is highlighted
12665 */
12666 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12667 return this.highlighted;
12668 };
12669
12670 /**
12671 * Check if the option is pressed. The pressed state occurs when a user mouses
12672 * down on an item, but has not yet let go of the mouse. The item may appear
12673 * selected, but it will not be selected until the user releases the mouse.
12674 *
12675 * @return {boolean} Item is pressed
12676 */
12677 OO.ui.OptionWidget.prototype.isPressed = function () {
12678 return this.pressed;
12679 };
12680
12681 /**
12682 * Set the option’s selected state. In general, all modifications to the selection
12683 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12684 * method instead of this method.
12685 *
12686 * @param {boolean} [state=false] Select option
12687 * @chainable
12688 */
12689 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12690 if ( this.constructor.static.selectable ) {
12691 this.selected = !!state;
12692 this.$element
12693 .toggleClass( 'oo-ui-optionWidget-selected', state )
12694 .attr( 'aria-selected', state.toString() );
12695 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12696 this.scrollElementIntoView();
12697 }
12698 this.updateThemeClasses();
12699 }
12700 return this;
12701 };
12702
12703 /**
12704 * Set the option’s highlighted state. In general, all programmatic
12705 * modifications to the highlight should be handled by the
12706 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12707 * method instead of this method.
12708 *
12709 * @param {boolean} [state=false] Highlight option
12710 * @chainable
12711 */
12712 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12713 if ( this.constructor.static.highlightable ) {
12714 this.highlighted = !!state;
12715 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12716 this.updateThemeClasses();
12717 }
12718 return this;
12719 };
12720
12721 /**
12722 * Set the option’s pressed state. In general, all
12723 * programmatic modifications to the pressed state should be handled by the
12724 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12725 * method instead of this method.
12726 *
12727 * @param {boolean} [state=false] Press option
12728 * @chainable
12729 */
12730 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12731 if ( this.constructor.static.pressable ) {
12732 this.pressed = !!state;
12733 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12734 this.updateThemeClasses();
12735 }
12736 return this;
12737 };
12738
12739 /**
12740 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12741 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12742 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12743 * options. For more information about options and selects, please see the
12744 * [OOjs UI documentation on MediaWiki][1].
12745 *
12746 * @example
12747 * // Decorated options in a select widget
12748 * var select = new OO.ui.SelectWidget( {
12749 * items: [
12750 * new OO.ui.DecoratedOptionWidget( {
12751 * data: 'a',
12752 * label: 'Option with icon',
12753 * icon: 'help'
12754 * } ),
12755 * new OO.ui.DecoratedOptionWidget( {
12756 * data: 'b',
12757 * label: 'Option with indicator',
12758 * indicator: 'next'
12759 * } )
12760 * ]
12761 * } );
12762 * $( 'body' ).append( select.$element );
12763 *
12764 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12765 *
12766 * @class
12767 * @extends OO.ui.OptionWidget
12768 * @mixins OO.ui.IconElement
12769 * @mixins OO.ui.IndicatorElement
12770 *
12771 * @constructor
12772 * @param {Object} [config] Configuration options
12773 */
12774 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
12775 // Parent constructor
12776 OO.ui.DecoratedOptionWidget.super.call( this, config );
12777
12778 // Mixin constructors
12779 OO.ui.IconElement.call( this, config );
12780 OO.ui.IndicatorElement.call( this, config );
12781
12782 // Initialization
12783 this.$element
12784 .addClass( 'oo-ui-decoratedOptionWidget' )
12785 .prepend( this.$icon )
12786 .append( this.$indicator );
12787 };
12788
12789 /* Setup */
12790
12791 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
12792 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
12793 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
12794
12795 /**
12796 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12797 * can be selected and configured with data. The class is
12798 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12799 * [OOjs UI documentation on MediaWiki] [1] for more information.
12800 *
12801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12802 *
12803 * @class
12804 * @extends OO.ui.DecoratedOptionWidget
12805 * @mixins OO.ui.ButtonElement
12806 * @mixins OO.ui.TabIndexedElement
12807 *
12808 * @constructor
12809 * @param {Object} [config] Configuration options
12810 */
12811 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
12812 // Configuration initialization
12813 config = $.extend( { tabIndex: -1 }, config );
12814
12815 // Parent constructor
12816 OO.ui.ButtonOptionWidget.super.call( this, config );
12817
12818 // Mixin constructors
12819 OO.ui.ButtonElement.call( this, config );
12820 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12821
12822 // Initialization
12823 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
12824 this.$button.append( this.$element.contents() );
12825 this.$element.append( this.$button );
12826 };
12827
12828 /* Setup */
12829
12830 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
12831 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
12832 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
12833
12834 /* Static Properties */
12835
12836 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12837 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
12838
12839 OO.ui.ButtonOptionWidget.static.highlightable = false;
12840
12841 /* Methods */
12842
12843 /**
12844 * @inheritdoc
12845 */
12846 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
12847 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
12848
12849 if ( this.constructor.static.selectable ) {
12850 this.setActive( state );
12851 }
12852
12853 return this;
12854 };
12855
12856 /**
12857 * RadioOptionWidget is an option widget that looks like a radio button.
12858 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12859 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12860 *
12861 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12862 *
12863 * @class
12864 * @extends OO.ui.OptionWidget
12865 *
12866 * @constructor
12867 * @param {Object} [config] Configuration options
12868 */
12869 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
12870 // Configuration initialization
12871 config = config || {};
12872
12873 // Properties (must be done before parent constructor which calls #setDisabled)
12874 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
12875
12876 // Parent constructor
12877 OO.ui.RadioOptionWidget.super.call( this, config );
12878
12879 // Initialization
12880 this.$element
12881 .addClass( 'oo-ui-radioOptionWidget' )
12882 .prepend( this.radio.$element );
12883 };
12884
12885 /* Setup */
12886
12887 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
12888
12889 /* Static Properties */
12890
12891 OO.ui.RadioOptionWidget.static.highlightable = false;
12892
12893 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
12894
12895 OO.ui.RadioOptionWidget.static.pressable = false;
12896
12897 OO.ui.RadioOptionWidget.static.tagName = 'label';
12898
12899 /* Methods */
12900
12901 /**
12902 * @inheritdoc
12903 */
12904 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
12905 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
12906
12907 this.radio.setSelected( state );
12908
12909 return this;
12910 };
12911
12912 /**
12913 * @inheritdoc
12914 */
12915 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
12916 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
12917
12918 this.radio.setDisabled( this.isDisabled() );
12919
12920 return this;
12921 };
12922
12923 /**
12924 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12925 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12926 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12927 *
12928 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12929 *
12930 * @class
12931 * @extends OO.ui.DecoratedOptionWidget
12932 *
12933 * @constructor
12934 * @param {Object} [config] Configuration options
12935 */
12936 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
12937 // Configuration initialization
12938 config = $.extend( { icon: 'check' }, config );
12939
12940 // Parent constructor
12941 OO.ui.MenuOptionWidget.super.call( this, config );
12942
12943 // Initialization
12944 this.$element
12945 .attr( 'role', 'menuitem' )
12946 .addClass( 'oo-ui-menuOptionWidget' );
12947 };
12948
12949 /* Setup */
12950
12951 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
12952
12953 /* Static Properties */
12954
12955 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
12956
12957 /**
12958 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12959 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12960 *
12961 * @example
12962 * var myDropdown = new OO.ui.DropdownWidget( {
12963 * menu: {
12964 * items: [
12965 * new OO.ui.MenuSectionOptionWidget( {
12966 * label: 'Dogs'
12967 * } ),
12968 * new OO.ui.MenuOptionWidget( {
12969 * data: 'corgi',
12970 * label: 'Welsh Corgi'
12971 * } ),
12972 * new OO.ui.MenuOptionWidget( {
12973 * data: 'poodle',
12974 * label: 'Standard Poodle'
12975 * } ),
12976 * new OO.ui.MenuSectionOptionWidget( {
12977 * label: 'Cats'
12978 * } ),
12979 * new OO.ui.MenuOptionWidget( {
12980 * data: 'lion',
12981 * label: 'Lion'
12982 * } )
12983 * ]
12984 * }
12985 * } );
12986 * $( 'body' ).append( myDropdown.$element );
12987 *
12988 *
12989 * @class
12990 * @extends OO.ui.DecoratedOptionWidget
12991 *
12992 * @constructor
12993 * @param {Object} [config] Configuration options
12994 */
12995 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
12996 // Parent constructor
12997 OO.ui.MenuSectionOptionWidget.super.call( this, config );
12998
12999 // Initialization
13000 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
13001 };
13002
13003 /* Setup */
13004
13005 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
13006
13007 /* Static Properties */
13008
13009 OO.ui.MenuSectionOptionWidget.static.selectable = false;
13010
13011 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
13012
13013 /**
13014 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
13015 *
13016 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
13017 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
13018 * for an example.
13019 *
13020 * @class
13021 * @extends OO.ui.DecoratedOptionWidget
13022 *
13023 * @constructor
13024 * @param {Object} [config] Configuration options
13025 * @cfg {number} [level] Indentation level
13026 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
13027 */
13028 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
13029 // Configuration initialization
13030 config = config || {};
13031
13032 // Parent constructor
13033 OO.ui.OutlineOptionWidget.super.call( this, config );
13034
13035 // Properties
13036 this.level = 0;
13037 this.movable = !!config.movable;
13038 this.removable = !!config.removable;
13039
13040 // Initialization
13041 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
13042 this.setLevel( config.level );
13043 };
13044
13045 /* Setup */
13046
13047 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
13048
13049 /* Static Properties */
13050
13051 OO.ui.OutlineOptionWidget.static.highlightable = false;
13052
13053 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
13054
13055 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
13056
13057 OO.ui.OutlineOptionWidget.static.levels = 3;
13058
13059 /* Methods */
13060
13061 /**
13062 * Check if item is movable.
13063 *
13064 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13065 *
13066 * @return {boolean} Item is movable
13067 */
13068 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
13069 return this.movable;
13070 };
13071
13072 /**
13073 * Check if item is removable.
13074 *
13075 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13076 *
13077 * @return {boolean} Item is removable
13078 */
13079 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
13080 return this.removable;
13081 };
13082
13083 /**
13084 * Get indentation level.
13085 *
13086 * @return {number} Indentation level
13087 */
13088 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
13089 return this.level;
13090 };
13091
13092 /**
13093 * Set movability.
13094 *
13095 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13096 *
13097 * @param {boolean} movable Item is movable
13098 * @chainable
13099 */
13100 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
13101 this.movable = !!movable;
13102 this.updateThemeClasses();
13103 return this;
13104 };
13105
13106 /**
13107 * Set removability.
13108 *
13109 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13110 *
13111 * @param {boolean} movable Item is removable
13112 * @chainable
13113 */
13114 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
13115 this.removable = !!removable;
13116 this.updateThemeClasses();
13117 return this;
13118 };
13119
13120 /**
13121 * Set indentation level.
13122 *
13123 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13124 * @chainable
13125 */
13126 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
13127 var levels = this.constructor.static.levels,
13128 levelClass = this.constructor.static.levelClass,
13129 i = levels;
13130
13131 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
13132 while ( i-- ) {
13133 if ( this.level === i ) {
13134 this.$element.addClass( levelClass + i );
13135 } else {
13136 this.$element.removeClass( levelClass + i );
13137 }
13138 }
13139 this.updateThemeClasses();
13140
13141 return this;
13142 };
13143
13144 /**
13145 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13146 * By default, each popup has an anchor that points toward its origin.
13147 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13148 *
13149 * @example
13150 * // A popup widget.
13151 * var popup = new OO.ui.PopupWidget( {
13152 * $content: $( '<p>Hi there!</p>' ),
13153 * padded: true,
13154 * width: 300
13155 * } );
13156 *
13157 * $( 'body' ).append( popup.$element );
13158 * // To display the popup, toggle the visibility to 'true'.
13159 * popup.toggle( true );
13160 *
13161 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13162 *
13163 * @class
13164 * @extends OO.ui.Widget
13165 * @mixins OO.ui.LabelElement
13166 *
13167 * @constructor
13168 * @param {Object} [config] Configuration options
13169 * @cfg {number} [width=320] Width of popup in pixels
13170 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13171 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13172 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13173 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13174 * For left-aligned popups, the left edge is aligned to the anchor.
13175 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13176 * See the [OOjs UI docs on MediaWiki][3] for an example.
13177 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13178 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13179 * @cfg {jQuery} [$content] Content to append to the popup's body
13180 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13181 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13182 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13183 * for an example.
13184 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13185 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13186 * button.
13187 * @cfg {boolean} [padded] Add padding to the popup's body
13188 */
13189 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
13190 // Configuration initialization
13191 config = config || {};
13192
13193 // Parent constructor
13194 OO.ui.PopupWidget.super.call( this, config );
13195
13196 // Properties (must be set before ClippableElement constructor call)
13197 this.$body = $( '<div>' );
13198
13199 // Mixin constructors
13200 OO.ui.LabelElement.call( this, config );
13201 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
13202
13203 // Properties
13204 this.$popup = $( '<div>' );
13205 this.$head = $( '<div>' );
13206 this.$anchor = $( '<div>' );
13207 // If undefined, will be computed lazily in updateDimensions()
13208 this.$container = config.$container;
13209 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
13210 this.autoClose = !!config.autoClose;
13211 this.$autoCloseIgnore = config.$autoCloseIgnore;
13212 this.transitionTimeout = null;
13213 this.anchor = null;
13214 this.width = config.width !== undefined ? config.width : 320;
13215 this.height = config.height !== undefined ? config.height : null;
13216 this.align = config.align || 'center';
13217 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
13218 this.onMouseDownHandler = this.onMouseDown.bind( this );
13219 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
13220
13221 // Events
13222 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
13223
13224 // Initialization
13225 this.toggleAnchor( config.anchor === undefined || config.anchor );
13226 this.$body.addClass( 'oo-ui-popupWidget-body' );
13227 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
13228 this.$head
13229 .addClass( 'oo-ui-popupWidget-head' )
13230 .append( this.$label, this.closeButton.$element );
13231 if ( !config.head ) {
13232 this.$head.addClass( 'oo-ui-element-hidden' );
13233 }
13234 this.$popup
13235 .addClass( 'oo-ui-popupWidget-popup' )
13236 .append( this.$head, this.$body );
13237 this.$element
13238 .addClass( 'oo-ui-popupWidget' )
13239 .append( this.$popup, this.$anchor );
13240 // Move content, which was added to #$element by OO.ui.Widget, to the body
13241 if ( config.$content instanceof jQuery ) {
13242 this.$body.append( config.$content );
13243 }
13244 if ( config.padded ) {
13245 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
13246 }
13247
13248 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13249 // that reference properties not initialized at that time of parent class construction
13250 // TODO: Find a better way to handle post-constructor setup
13251 this.visible = false;
13252 this.$element.addClass( 'oo-ui-element-hidden' );
13253 };
13254
13255 /* Setup */
13256
13257 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
13258 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
13259 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
13260
13261 /* Methods */
13262
13263 /**
13264 * Handles mouse down events.
13265 *
13266 * @private
13267 * @param {MouseEvent} e Mouse down event
13268 */
13269 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
13270 if (
13271 this.isVisible() &&
13272 !$.contains( this.$element[ 0 ], e.target ) &&
13273 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
13274 ) {
13275 this.toggle( false );
13276 }
13277 };
13278
13279 /**
13280 * Bind mouse down listener.
13281 *
13282 * @private
13283 */
13284 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
13285 // Capture clicks outside popup
13286 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
13287 };
13288
13289 /**
13290 * Handles close button click events.
13291 *
13292 * @private
13293 */
13294 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
13295 if ( this.isVisible() ) {
13296 this.toggle( false );
13297 }
13298 };
13299
13300 /**
13301 * Unbind mouse down listener.
13302 *
13303 * @private
13304 */
13305 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
13306 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
13307 };
13308
13309 /**
13310 * Handles key down events.
13311 *
13312 * @private
13313 * @param {KeyboardEvent} e Key down event
13314 */
13315 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
13316 if (
13317 e.which === OO.ui.Keys.ESCAPE &&
13318 this.isVisible()
13319 ) {
13320 this.toggle( false );
13321 e.preventDefault();
13322 e.stopPropagation();
13323 }
13324 };
13325
13326 /**
13327 * Bind key down listener.
13328 *
13329 * @private
13330 */
13331 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
13332 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13333 };
13334
13335 /**
13336 * Unbind key down listener.
13337 *
13338 * @private
13339 */
13340 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
13341 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13342 };
13343
13344 /**
13345 * Show, hide, or toggle the visibility of the anchor.
13346 *
13347 * @param {boolean} [show] Show anchor, omit to toggle
13348 */
13349 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
13350 show = show === undefined ? !this.anchored : !!show;
13351
13352 if ( this.anchored !== show ) {
13353 if ( show ) {
13354 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
13355 } else {
13356 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
13357 }
13358 this.anchored = show;
13359 }
13360 };
13361
13362 /**
13363 * Check if the anchor is visible.
13364 *
13365 * @return {boolean} Anchor is visible
13366 */
13367 OO.ui.PopupWidget.prototype.hasAnchor = function () {
13368 return this.anchor;
13369 };
13370
13371 /**
13372 * @inheritdoc
13373 */
13374 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
13375 show = show === undefined ? !this.isVisible() : !!show;
13376
13377 var change = show !== this.isVisible();
13378
13379 // Parent method
13380 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
13381
13382 if ( change ) {
13383 if ( show ) {
13384 if ( this.autoClose ) {
13385 this.bindMouseDownListener();
13386 this.bindKeyDownListener();
13387 }
13388 this.updateDimensions();
13389 this.toggleClipping( true );
13390 } else {
13391 this.toggleClipping( false );
13392 if ( this.autoClose ) {
13393 this.unbindMouseDownListener();
13394 this.unbindKeyDownListener();
13395 }
13396 }
13397 }
13398
13399 return this;
13400 };
13401
13402 /**
13403 * Set the size of the popup.
13404 *
13405 * Changing the size may also change the popup's position depending on the alignment.
13406 *
13407 * @param {number} width Width in pixels
13408 * @param {number} height Height in pixels
13409 * @param {boolean} [transition=false] Use a smooth transition
13410 * @chainable
13411 */
13412 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
13413 this.width = width;
13414 this.height = height !== undefined ? height : null;
13415 if ( this.isVisible() ) {
13416 this.updateDimensions( transition );
13417 }
13418 };
13419
13420 /**
13421 * Update the size and position.
13422 *
13423 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13424 * be called automatically.
13425 *
13426 * @param {boolean} [transition=false] Use a smooth transition
13427 * @chainable
13428 */
13429 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
13430 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
13431 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
13432 widget = this;
13433
13434 if ( !this.$container ) {
13435 // Lazy-initialize $container if not specified in constructor
13436 this.$container = $( this.getClosestScrollableElementContainer() );
13437 }
13438
13439 // Set height and width before measuring things, since it might cause our measurements
13440 // to change (e.g. due to scrollbars appearing or disappearing)
13441 this.$popup.css( {
13442 width: this.width,
13443 height: this.height !== null ? this.height : 'auto'
13444 } );
13445
13446 // Compute initial popupOffset based on alignment
13447 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
13448
13449 // Figure out if this will cause the popup to go beyond the edge of the container
13450 originOffset = this.$element.offset().left;
13451 containerLeft = this.$container.offset().left;
13452 containerWidth = this.$container.innerWidth();
13453 containerRight = containerLeft + containerWidth;
13454 popupLeft = popupOffset - this.containerPadding;
13455 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
13456 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
13457 overlapRight = containerRight - ( originOffset + popupRight );
13458
13459 // Adjust offset to make the popup not go beyond the edge, if needed
13460 if ( overlapRight < 0 ) {
13461 popupOffset += overlapRight;
13462 } else if ( overlapLeft < 0 ) {
13463 popupOffset -= overlapLeft;
13464 }
13465
13466 // Adjust offset to avoid anchor being rendered too close to the edge
13467 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13468 // TODO: Find a measurement that works for CSS anchors and image anchors
13469 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
13470 if ( popupOffset + this.width < anchorWidth ) {
13471 popupOffset = anchorWidth - this.width;
13472 } else if ( -popupOffset < anchorWidth ) {
13473 popupOffset = -anchorWidth;
13474 }
13475
13476 // Prevent transition from being interrupted
13477 clearTimeout( this.transitionTimeout );
13478 if ( transition ) {
13479 // Enable transition
13480 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
13481 }
13482
13483 // Position body relative to anchor
13484 this.$popup.css( 'margin-left', popupOffset );
13485
13486 if ( transition ) {
13487 // Prevent transitioning after transition is complete
13488 this.transitionTimeout = setTimeout( function () {
13489 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13490 }, 200 );
13491 } else {
13492 // Prevent transitioning immediately
13493 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13494 }
13495
13496 // Reevaluate clipping state since we've relocated and resized the popup
13497 this.clip();
13498
13499 return this;
13500 };
13501
13502 /**
13503 * Progress bars visually display the status of an operation, such as a download,
13504 * and can be either determinate or indeterminate:
13505 *
13506 * - **determinate** process bars show the percent of an operation that is complete.
13507 *
13508 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13509 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13510 * not use percentages.
13511 *
13512 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13513 *
13514 * @example
13515 * // Examples of determinate and indeterminate progress bars.
13516 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13517 * progress: 33
13518 * } );
13519 * var progressBar2 = new OO.ui.ProgressBarWidget();
13520 *
13521 * // Create a FieldsetLayout to layout progress bars
13522 * var fieldset = new OO.ui.FieldsetLayout;
13523 * fieldset.addItems( [
13524 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13525 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13526 * ] );
13527 * $( 'body' ).append( fieldset.$element );
13528 *
13529 * @class
13530 * @extends OO.ui.Widget
13531 *
13532 * @constructor
13533 * @param {Object} [config] Configuration options
13534 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13535 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13536 * By default, the progress bar is indeterminate.
13537 */
13538 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
13539 // Configuration initialization
13540 config = config || {};
13541
13542 // Parent constructor
13543 OO.ui.ProgressBarWidget.super.call( this, config );
13544
13545 // Properties
13546 this.$bar = $( '<div>' );
13547 this.progress = null;
13548
13549 // Initialization
13550 this.setProgress( config.progress !== undefined ? config.progress : false );
13551 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
13552 this.$element
13553 .attr( {
13554 role: 'progressbar',
13555 'aria-valuemin': 0,
13556 'aria-valuemax': 100
13557 } )
13558 .addClass( 'oo-ui-progressBarWidget' )
13559 .append( this.$bar );
13560 };
13561
13562 /* Setup */
13563
13564 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
13565
13566 /* Static Properties */
13567
13568 OO.ui.ProgressBarWidget.static.tagName = 'div';
13569
13570 /* Methods */
13571
13572 /**
13573 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13574 *
13575 * @return {number|boolean} Progress percent
13576 */
13577 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
13578 return this.progress;
13579 };
13580
13581 /**
13582 * Set the percent of the process completed or `false` for an indeterminate process.
13583 *
13584 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13585 */
13586 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
13587 this.progress = progress;
13588
13589 if ( progress !== false ) {
13590 this.$bar.css( 'width', this.progress + '%' );
13591 this.$element.attr( 'aria-valuenow', this.progress );
13592 } else {
13593 this.$bar.css( 'width', '' );
13594 this.$element.removeAttr( 'aria-valuenow' );
13595 }
13596 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
13597 };
13598
13599 /**
13600 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13601 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13602 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13603 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13604 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13605 *
13606 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13607 * the [OOjs UI demos][1] for an example.
13608 *
13609 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13610 *
13611 * @class
13612 * @extends OO.ui.Widget
13613 *
13614 * @constructor
13615 * @param {Object} [config] Configuration options
13616 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13617 * @cfg {string} [value] Initial query value
13618 */
13619 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
13620 // Configuration initialization
13621 config = config || {};
13622
13623 // Parent constructor
13624 OO.ui.SearchWidget.super.call( this, config );
13625
13626 // Properties
13627 this.query = new OO.ui.TextInputWidget( {
13628 icon: 'search',
13629 placeholder: config.placeholder,
13630 value: config.value
13631 } );
13632 this.results = new OO.ui.SelectWidget();
13633 this.$query = $( '<div>' );
13634 this.$results = $( '<div>' );
13635
13636 // Events
13637 this.query.connect( this, {
13638 change: 'onQueryChange',
13639 enter: 'onQueryEnter'
13640 } );
13641 this.results.connect( this, {
13642 highlight: 'onResultsHighlight',
13643 select: 'onResultsSelect'
13644 } );
13645 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
13646
13647 // Initialization
13648 this.$query
13649 .addClass( 'oo-ui-searchWidget-query' )
13650 .append( this.query.$element );
13651 this.$results
13652 .addClass( 'oo-ui-searchWidget-results' )
13653 .append( this.results.$element );
13654 this.$element
13655 .addClass( 'oo-ui-searchWidget' )
13656 .append( this.$results, this.$query );
13657 };
13658
13659 /* Setup */
13660
13661 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
13662
13663 /* Events */
13664
13665 /**
13666 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13667 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13668 * string is typed into the query field instead, the first menu item that matches the query
13669 * will be highlighted.
13670
13671 * @event highlight
13672 * @deprecated Connect straight to getResults() events instead
13673 * @param {Object|null} item Item data or null if no item is highlighted
13674 */
13675
13676 /**
13677 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13678 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13679 *
13680 * @event select
13681 * @deprecated Connect straight to getResults() events instead
13682 * @param {Object|null} item Item data or null if no item is selected
13683 */
13684
13685 /* Methods */
13686
13687 /**
13688 * Handle query key down events.
13689 *
13690 * @private
13691 * @param {jQuery.Event} e Key down event
13692 */
13693 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
13694 var highlightedItem, nextItem,
13695 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
13696
13697 if ( dir ) {
13698 highlightedItem = this.results.getHighlightedItem();
13699 if ( !highlightedItem ) {
13700 highlightedItem = this.results.getSelectedItem();
13701 }
13702 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
13703 this.results.highlightItem( nextItem );
13704 nextItem.scrollElementIntoView();
13705 }
13706 };
13707
13708 /**
13709 * Handle select widget select events.
13710 *
13711 * Clears existing results. Subclasses should repopulate items according to new query.
13712 *
13713 * @private
13714 * @param {string} value New value
13715 */
13716 OO.ui.SearchWidget.prototype.onQueryChange = function () {
13717 // Reset
13718 this.results.clearItems();
13719 };
13720
13721 /**
13722 * Handle select widget enter key events.
13723 *
13724 * Selects highlighted item.
13725 *
13726 * @private
13727 * @param {string} value New value
13728 */
13729 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
13730 // Reset
13731 this.results.selectItem( this.results.getHighlightedItem() );
13732 };
13733
13734 /**
13735 * Handle select widget highlight events.
13736 *
13737 * @private
13738 * @deprecated Connect straight to getResults() events instead
13739 * @param {OO.ui.OptionWidget} item Highlighted item
13740 * @fires highlight
13741 */
13742 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
13743 this.emit( 'highlight', item ? item.getData() : null );
13744 };
13745
13746 /**
13747 * Handle select widget select events.
13748 *
13749 * @private
13750 * @deprecated Connect straight to getResults() events instead
13751 * @param {OO.ui.OptionWidget} item Selected item
13752 * @fires select
13753 */
13754 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
13755 this.emit( 'select', item ? item.getData() : null );
13756 };
13757
13758 /**
13759 * Get the query input.
13760 *
13761 * @return {OO.ui.TextInputWidget} Query input
13762 */
13763 OO.ui.SearchWidget.prototype.getQuery = function () {
13764 return this.query;
13765 };
13766
13767 /**
13768 * Get the search results menu.
13769 *
13770 * @return {OO.ui.SelectWidget} Menu of search results
13771 */
13772 OO.ui.SearchWidget.prototype.getResults = function () {
13773 return this.results;
13774 };
13775
13776 /**
13777 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13778 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13779 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13780 * menu selects}.
13781 *
13782 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13783 * information, please see the [OOjs UI documentation on MediaWiki][1].
13784 *
13785 * @example
13786 * // Example of a select widget with three options
13787 * var select = new OO.ui.SelectWidget( {
13788 * items: [
13789 * new OO.ui.OptionWidget( {
13790 * data: 'a',
13791 * label: 'Option One',
13792 * } ),
13793 * new OO.ui.OptionWidget( {
13794 * data: 'b',
13795 * label: 'Option Two',
13796 * } ),
13797 * new OO.ui.OptionWidget( {
13798 * data: 'c',
13799 * label: 'Option Three',
13800 * } )
13801 * ]
13802 * } );
13803 * $( 'body' ).append( select.$element );
13804 *
13805 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13806 *
13807 * @class
13808 * @extends OO.ui.Widget
13809 * @mixins OO.ui.GroupElement
13810 *
13811 * @constructor
13812 * @param {Object} [config] Configuration options
13813 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13814 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13815 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13816 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13817 */
13818 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
13819 // Configuration initialization
13820 config = config || {};
13821
13822 // Parent constructor
13823 OO.ui.SelectWidget.super.call( this, config );
13824
13825 // Mixin constructors
13826 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
13827
13828 // Properties
13829 this.pressed = false;
13830 this.selecting = null;
13831 this.onMouseUpHandler = this.onMouseUp.bind( this );
13832 this.onMouseMoveHandler = this.onMouseMove.bind( this );
13833 this.onKeyDownHandler = this.onKeyDown.bind( this );
13834
13835 // Events
13836 this.$element.on( {
13837 mousedown: this.onMouseDown.bind( this ),
13838 mouseover: this.onMouseOver.bind( this ),
13839 mouseleave: this.onMouseLeave.bind( this )
13840 } );
13841
13842 // Initialization
13843 this.$element
13844 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13845 .attr( 'role', 'listbox' );
13846 if ( Array.isArray( config.items ) ) {
13847 this.addItems( config.items );
13848 }
13849 };
13850
13851 /* Setup */
13852
13853 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
13854
13855 // Need to mixin base class as well
13856 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
13857 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
13858
13859 /* Events */
13860
13861 /**
13862 * @event highlight
13863 *
13864 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13865 *
13866 * @param {OO.ui.OptionWidget|null} item Highlighted item
13867 */
13868
13869 /**
13870 * @event press
13871 *
13872 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13873 * pressed state of an option.
13874 *
13875 * @param {OO.ui.OptionWidget|null} item Pressed item
13876 */
13877
13878 /**
13879 * @event select
13880 *
13881 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13882 *
13883 * @param {OO.ui.OptionWidget|null} item Selected item
13884 */
13885
13886 /**
13887 * @event choose
13888 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13889 * @param {OO.ui.OptionWidget} item Chosen item
13890 */
13891
13892 /**
13893 * @event add
13894 *
13895 * An `add` event is emitted when options are added to the select with the #addItems method.
13896 *
13897 * @param {OO.ui.OptionWidget[]} items Added items
13898 * @param {number} index Index of insertion point
13899 */
13900
13901 /**
13902 * @event remove
13903 *
13904 * A `remove` event is emitted when options are removed from the select with the #clearItems
13905 * or #removeItems methods.
13906 *
13907 * @param {OO.ui.OptionWidget[]} items Removed items
13908 */
13909
13910 /* Methods */
13911
13912 /**
13913 * Handle mouse down events.
13914 *
13915 * @private
13916 * @param {jQuery.Event} e Mouse down event
13917 */
13918 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
13919 var item;
13920
13921 if ( !this.isDisabled() && e.which === 1 ) {
13922 this.togglePressed( true );
13923 item = this.getTargetItem( e );
13924 if ( item && item.isSelectable() ) {
13925 this.pressItem( item );
13926 this.selecting = item;
13927 this.getElementDocument().addEventListener(
13928 'mouseup',
13929 this.onMouseUpHandler,
13930 true
13931 );
13932 this.getElementDocument().addEventListener(
13933 'mousemove',
13934 this.onMouseMoveHandler,
13935 true
13936 );
13937 }
13938 }
13939 return false;
13940 };
13941
13942 /**
13943 * Handle mouse up events.
13944 *
13945 * @private
13946 * @param {jQuery.Event} e Mouse up event
13947 */
13948 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
13949 var item;
13950
13951 this.togglePressed( false );
13952 if ( !this.selecting ) {
13953 item = this.getTargetItem( e );
13954 if ( item && item.isSelectable() ) {
13955 this.selecting = item;
13956 }
13957 }
13958 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
13959 this.pressItem( null );
13960 this.chooseItem( this.selecting );
13961 this.selecting = null;
13962 }
13963
13964 this.getElementDocument().removeEventListener(
13965 'mouseup',
13966 this.onMouseUpHandler,
13967 true
13968 );
13969 this.getElementDocument().removeEventListener(
13970 'mousemove',
13971 this.onMouseMoveHandler,
13972 true
13973 );
13974
13975 return false;
13976 };
13977
13978 /**
13979 * Handle mouse move events.
13980 *
13981 * @private
13982 * @param {jQuery.Event} e Mouse move event
13983 */
13984 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
13985 var item;
13986
13987 if ( !this.isDisabled() && this.pressed ) {
13988 item = this.getTargetItem( e );
13989 if ( item && item !== this.selecting && item.isSelectable() ) {
13990 this.pressItem( item );
13991 this.selecting = item;
13992 }
13993 }
13994 return false;
13995 };
13996
13997 /**
13998 * Handle mouse over events.
13999 *
14000 * @private
14001 * @param {jQuery.Event} e Mouse over event
14002 */
14003 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
14004 var item;
14005
14006 if ( !this.isDisabled() ) {
14007 item = this.getTargetItem( e );
14008 this.highlightItem( item && item.isHighlightable() ? item : null );
14009 }
14010 return false;
14011 };
14012
14013 /**
14014 * Handle mouse leave events.
14015 *
14016 * @private
14017 * @param {jQuery.Event} e Mouse over event
14018 */
14019 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
14020 if ( !this.isDisabled() ) {
14021 this.highlightItem( null );
14022 }
14023 return false;
14024 };
14025
14026 /**
14027 * Handle key down events.
14028 *
14029 * @protected
14030 * @param {jQuery.Event} e Key down event
14031 */
14032 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
14033 var nextItem,
14034 handled = false,
14035 currentItem = this.getHighlightedItem() || this.getSelectedItem();
14036
14037 if ( !this.isDisabled() && this.isVisible() ) {
14038 switch ( e.keyCode ) {
14039 case OO.ui.Keys.ENTER:
14040 if ( currentItem && currentItem.constructor.static.highlightable ) {
14041 // Was only highlighted, now let's select it. No-op if already selected.
14042 this.chooseItem( currentItem );
14043 handled = true;
14044 }
14045 break;
14046 case OO.ui.Keys.UP:
14047 case OO.ui.Keys.LEFT:
14048 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
14049 handled = true;
14050 break;
14051 case OO.ui.Keys.DOWN:
14052 case OO.ui.Keys.RIGHT:
14053 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
14054 handled = true;
14055 break;
14056 case OO.ui.Keys.ESCAPE:
14057 case OO.ui.Keys.TAB:
14058 if ( currentItem && currentItem.constructor.static.highlightable ) {
14059 currentItem.setHighlighted( false );
14060 }
14061 this.unbindKeyDownListener();
14062 // Don't prevent tabbing away / defocusing
14063 handled = false;
14064 break;
14065 }
14066
14067 if ( nextItem ) {
14068 if ( nextItem.constructor.static.highlightable ) {
14069 this.highlightItem( nextItem );
14070 } else {
14071 this.chooseItem( nextItem );
14072 }
14073 nextItem.scrollElementIntoView();
14074 }
14075
14076 if ( handled ) {
14077 // Can't just return false, because e is not always a jQuery event
14078 e.preventDefault();
14079 e.stopPropagation();
14080 }
14081 }
14082 };
14083
14084 /**
14085 * Bind key down listener.
14086 *
14087 * @protected
14088 */
14089 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
14090 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
14091 };
14092
14093 /**
14094 * Unbind key down listener.
14095 *
14096 * @protected
14097 */
14098 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
14099 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
14100 };
14101
14102 /**
14103 * Get the closest item to a jQuery.Event.
14104 *
14105 * @private
14106 * @param {jQuery.Event} e
14107 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14108 */
14109 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
14110 var $item = $( e.target ).closest( '.oo-ui-optionWidget' );
14111 if ( $item.length ) {
14112 return $item.data( 'oo-ui-optionWidget' );
14113 }
14114 return null;
14115 };
14116
14117 /**
14118 * Get selected item.
14119 *
14120 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14121 */
14122 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
14123 var i, len;
14124
14125 for ( i = 0, len = this.items.length; i < len; i++ ) {
14126 if ( this.items[ i ].isSelected() ) {
14127 return this.items[ i ];
14128 }
14129 }
14130 return null;
14131 };
14132
14133 /**
14134 * Get highlighted item.
14135 *
14136 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14137 */
14138 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
14139 var i, len;
14140
14141 for ( i = 0, len = this.items.length; i < len; i++ ) {
14142 if ( this.items[ i ].isHighlighted() ) {
14143 return this.items[ i ];
14144 }
14145 }
14146 return null;
14147 };
14148
14149 /**
14150 * Toggle pressed state.
14151 *
14152 * Press is a state that occurs when a user mouses down on an item, but
14153 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14154 * until the user releases the mouse.
14155 *
14156 * @param {boolean} pressed An option is being pressed
14157 */
14158 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
14159 if ( pressed === undefined ) {
14160 pressed = !this.pressed;
14161 }
14162 if ( pressed !== this.pressed ) {
14163 this.$element
14164 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
14165 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
14166 this.pressed = pressed;
14167 }
14168 };
14169
14170 /**
14171 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14172 * and any existing highlight will be removed. The highlight is mutually exclusive.
14173 *
14174 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14175 * @fires highlight
14176 * @chainable
14177 */
14178 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
14179 var i, len, highlighted,
14180 changed = false;
14181
14182 for ( i = 0, len = this.items.length; i < len; i++ ) {
14183 highlighted = this.items[ i ] === item;
14184 if ( this.items[ i ].isHighlighted() !== highlighted ) {
14185 this.items[ i ].setHighlighted( highlighted );
14186 changed = true;
14187 }
14188 }
14189 if ( changed ) {
14190 this.emit( 'highlight', item );
14191 }
14192
14193 return this;
14194 };
14195
14196 /**
14197 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14198 * all options will be deselected.
14199 *
14200 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14201 * @fires select
14202 * @chainable
14203 */
14204 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
14205 var i, len, selected,
14206 changed = false;
14207
14208 for ( i = 0, len = this.items.length; i < len; i++ ) {
14209 selected = this.items[ i ] === item;
14210 if ( this.items[ i ].isSelected() !== selected ) {
14211 this.items[ i ].setSelected( selected );
14212 changed = true;
14213 }
14214 }
14215 if ( changed ) {
14216 this.emit( 'select', item );
14217 }
14218
14219 return this;
14220 };
14221
14222 /**
14223 * Press an item.
14224 *
14225 * Press is a state that occurs when a user mouses down on an item, but has not
14226 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14227 * releases the mouse.
14228 *
14229 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14230 * @fires press
14231 * @chainable
14232 */
14233 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
14234 var i, len, pressed,
14235 changed = false;
14236
14237 for ( i = 0, len = this.items.length; i < len; i++ ) {
14238 pressed = this.items[ i ] === item;
14239 if ( this.items[ i ].isPressed() !== pressed ) {
14240 this.items[ i ].setPressed( pressed );
14241 changed = true;
14242 }
14243 }
14244 if ( changed ) {
14245 this.emit( 'press', item );
14246 }
14247
14248 return this;
14249 };
14250
14251 /**
14252 * Choose an item.
14253 *
14254 * Note that ‘choose’ should never be modified programmatically. A user can choose
14255 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14256 * use the #selectItem method.
14257 *
14258 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14259 * when users choose an item with the keyboard or mouse.
14260 *
14261 * @param {OO.ui.OptionWidget} item Item to choose
14262 * @fires choose
14263 * @chainable
14264 */
14265 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
14266 this.selectItem( item );
14267 this.emit( 'choose', item );
14268
14269 return this;
14270 };
14271
14272 /**
14273 * Get an option by its position relative to the specified item (or to the start of the option array,
14274 * if item is `null`). The direction in which to search through the option array is specified with a
14275 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14276 * `null` if there are no options in the array.
14277 *
14278 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14279 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14280 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14281 */
14282 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
14283 var currentIndex, nextIndex, i,
14284 increase = direction > 0 ? 1 : -1,
14285 len = this.items.length;
14286
14287 if ( item instanceof OO.ui.OptionWidget ) {
14288 currentIndex = $.inArray( item, this.items );
14289 nextIndex = ( currentIndex + increase + len ) % len;
14290 } else {
14291 // If no item is selected and moving forward, start at the beginning.
14292 // If moving backward, start at the end.
14293 nextIndex = direction > 0 ? 0 : len - 1;
14294 }
14295
14296 for ( i = 0; i < len; i++ ) {
14297 item = this.items[ nextIndex ];
14298 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14299 return item;
14300 }
14301 nextIndex = ( nextIndex + increase + len ) % len;
14302 }
14303 return null;
14304 };
14305
14306 /**
14307 * Get the next selectable item or `null` if there are no selectable items.
14308 * Disabled options and menu-section markers and breaks are not selectable.
14309 *
14310 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14311 */
14312 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
14313 var i, len, item;
14314
14315 for ( i = 0, len = this.items.length; i < len; i++ ) {
14316 item = this.items[ i ];
14317 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14318 return item;
14319 }
14320 }
14321
14322 return null;
14323 };
14324
14325 /**
14326 * Add an array of options to the select. Optionally, an index number can be used to
14327 * specify an insertion point.
14328 *
14329 * @param {OO.ui.OptionWidget[]} items Items to add
14330 * @param {number} [index] Index to insert items after
14331 * @fires add
14332 * @chainable
14333 */
14334 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
14335 // Mixin method
14336 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
14337
14338 // Always provide an index, even if it was omitted
14339 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
14340
14341 return this;
14342 };
14343
14344 /**
14345 * Remove the specified array of options from the select. Options will be detached
14346 * from the DOM, not removed, so they can be reused later. To remove all options from
14347 * the select, you may wish to use the #clearItems method instead.
14348 *
14349 * @param {OO.ui.OptionWidget[]} items Items to remove
14350 * @fires remove
14351 * @chainable
14352 */
14353 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
14354 var i, len, item;
14355
14356 // Deselect items being removed
14357 for ( i = 0, len = items.length; i < len; i++ ) {
14358 item = items[ i ];
14359 if ( item.isSelected() ) {
14360 this.selectItem( null );
14361 }
14362 }
14363
14364 // Mixin method
14365 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
14366
14367 this.emit( 'remove', items );
14368
14369 return this;
14370 };
14371
14372 /**
14373 * Clear all options from the select. Options will be detached from the DOM, not removed,
14374 * so that they can be reused later. To remove a subset of options from the select, use
14375 * the #removeItems method.
14376 *
14377 * @fires remove
14378 * @chainable
14379 */
14380 OO.ui.SelectWidget.prototype.clearItems = function () {
14381 var items = this.items.slice();
14382
14383 // Mixin method
14384 OO.ui.GroupWidget.prototype.clearItems.call( this );
14385
14386 // Clear selection
14387 this.selectItem( null );
14388
14389 this.emit( 'remove', items );
14390
14391 return this;
14392 };
14393
14394 /**
14395 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14396 * button options and is used together with
14397 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14398 * highlighting, choosing, and selecting mutually exclusive options. Please see
14399 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14400 *
14401 * @example
14402 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14403 * var option1 = new OO.ui.ButtonOptionWidget( {
14404 * data: 1,
14405 * label: 'Option 1',
14406 * title: 'Button option 1'
14407 * } );
14408 *
14409 * var option2 = new OO.ui.ButtonOptionWidget( {
14410 * data: 2,
14411 * label: 'Option 2',
14412 * title: 'Button option 2'
14413 * } );
14414 *
14415 * var option3 = new OO.ui.ButtonOptionWidget( {
14416 * data: 3,
14417 * label: 'Option 3',
14418 * title: 'Button option 3'
14419 * } );
14420 *
14421 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14422 * items: [ option1, option2, option3 ]
14423 * } );
14424 * $( 'body' ).append( buttonSelect.$element );
14425 *
14426 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14427 *
14428 * @class
14429 * @extends OO.ui.SelectWidget
14430 * @mixins OO.ui.TabIndexedElement
14431 *
14432 * @constructor
14433 * @param {Object} [config] Configuration options
14434 */
14435 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
14436 // Parent constructor
14437 OO.ui.ButtonSelectWidget.super.call( this, config );
14438
14439 // Mixin constructors
14440 OO.ui.TabIndexedElement.call( this, config );
14441
14442 // Events
14443 this.$element.on( {
14444 focus: this.bindKeyDownListener.bind( this ),
14445 blur: this.unbindKeyDownListener.bind( this )
14446 } );
14447
14448 // Initialization
14449 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
14450 };
14451
14452 /* Setup */
14453
14454 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
14455 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
14456
14457 /**
14458 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14459 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14460 * an interface for adding, removing and selecting options.
14461 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14462 *
14463 * @example
14464 * // A RadioSelectWidget with RadioOptions.
14465 * var option1 = new OO.ui.RadioOptionWidget( {
14466 * data: 'a',
14467 * label: 'Selected radio option'
14468 * } );
14469 *
14470 * var option2 = new OO.ui.RadioOptionWidget( {
14471 * data: 'b',
14472 * label: 'Unselected radio option'
14473 * } );
14474 *
14475 * var radioSelect=new OO.ui.RadioSelectWidget( {
14476 * items: [ option1, option2 ]
14477 * } );
14478 *
14479 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14480 * radioSelect.selectItem( option1 );
14481 *
14482 * $( 'body' ).append( radioSelect.$element );
14483 *
14484 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14485
14486 *
14487 * @class
14488 * @extends OO.ui.SelectWidget
14489 * @mixins OO.ui.TabIndexedElement
14490 *
14491 * @constructor
14492 * @param {Object} [config] Configuration options
14493 */
14494 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
14495 // Parent constructor
14496 OO.ui.RadioSelectWidget.super.call( this, config );
14497
14498 // Mixin constructors
14499 OO.ui.TabIndexedElement.call( this, config );
14500
14501 // Events
14502 this.$element.on( {
14503 focus: this.bindKeyDownListener.bind( this ),
14504 blur: this.unbindKeyDownListener.bind( this )
14505 } );
14506
14507 // Initialization
14508 this.$element.addClass( 'oo-ui-radioSelectWidget' );
14509 };
14510
14511 /* Setup */
14512
14513 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
14514 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
14515
14516 /**
14517 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14518 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14519 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14520 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14521 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14522 * and customized to be opened, closed, and displayed as needed.
14523 *
14524 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14525 * mouse outside the menu.
14526 *
14527 * Menus also have support for keyboard interaction:
14528 *
14529 * - Enter/Return key: choose and select a menu option
14530 * - Up-arrow key: highlight the previous menu option
14531 * - Down-arrow key: highlight the next menu option
14532 * - Esc key: hide the menu
14533 *
14534 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14536 *
14537 * @class
14538 * @extends OO.ui.SelectWidget
14539 * @mixins OO.ui.ClippableElement
14540 *
14541 * @constructor
14542 * @param {Object} [config] Configuration options
14543 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14544 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14545 * and {@link OO.ui.LookupElement LookupElement}
14546 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14547 * anywhere on the page outside of this widget, the menu is hidden.
14548 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14549 */
14550 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
14551 // Configuration initialization
14552 config = config || {};
14553
14554 // Parent constructor
14555 OO.ui.MenuSelectWidget.super.call( this, config );
14556
14557 // Mixin constructors
14558 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
14559
14560 // Properties
14561 this.newItems = null;
14562 this.autoHide = config.autoHide === undefined || !!config.autoHide;
14563 this.$input = config.input ? config.input.$input : null;
14564 this.$widget = config.widget ? config.widget.$element : null;
14565 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
14566
14567 // Initialization
14568 this.$element
14569 .addClass( 'oo-ui-menuSelectWidget' )
14570 .attr( 'role', 'menu' );
14571
14572 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14573 // that reference properties not initialized at that time of parent class construction
14574 // TODO: Find a better way to handle post-constructor setup
14575 this.visible = false;
14576 this.$element.addClass( 'oo-ui-element-hidden' );
14577 };
14578
14579 /* Setup */
14580
14581 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
14582 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
14583
14584 /* Methods */
14585
14586 /**
14587 * Handles document mouse down events.
14588 *
14589 * @protected
14590 * @param {jQuery.Event} e Key down event
14591 */
14592 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
14593 if (
14594 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
14595 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
14596 ) {
14597 this.toggle( false );
14598 }
14599 };
14600
14601 /**
14602 * @inheritdoc
14603 */
14604 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
14605 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
14606
14607 if ( !this.isDisabled() && this.isVisible() ) {
14608 switch ( e.keyCode ) {
14609 case OO.ui.Keys.LEFT:
14610 case OO.ui.Keys.RIGHT:
14611 // Do nothing if a text field is associated, arrow keys will be handled natively
14612 if ( !this.$input ) {
14613 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14614 }
14615 break;
14616 case OO.ui.Keys.ESCAPE:
14617 case OO.ui.Keys.TAB:
14618 if ( currentItem ) {
14619 currentItem.setHighlighted( false );
14620 }
14621 this.toggle( false );
14622 // Don't prevent tabbing away, prevent defocusing
14623 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
14624 e.preventDefault();
14625 e.stopPropagation();
14626 }
14627 break;
14628 default:
14629 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14630 return;
14631 }
14632 }
14633 };
14634
14635 /**
14636 * @inheritdoc
14637 */
14638 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
14639 if ( this.$input ) {
14640 this.$input.on( 'keydown', this.onKeyDownHandler );
14641 } else {
14642 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
14643 }
14644 };
14645
14646 /**
14647 * @inheritdoc
14648 */
14649 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
14650 if ( this.$input ) {
14651 this.$input.off( 'keydown', this.onKeyDownHandler );
14652 } else {
14653 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
14654 }
14655 };
14656
14657 /**
14658 * Choose an item.
14659 *
14660 * When a user chooses an item, the menu is closed.
14661 *
14662 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14663 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14664 * @param {OO.ui.OptionWidget} item Item to choose
14665 * @chainable
14666 */
14667 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
14668 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
14669 this.toggle( false );
14670 return this;
14671 };
14672
14673 /**
14674 * @inheritdoc
14675 */
14676 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
14677 var i, len, item;
14678
14679 // Parent method
14680 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
14681
14682 // Auto-initialize
14683 if ( !this.newItems ) {
14684 this.newItems = [];
14685 }
14686
14687 for ( i = 0, len = items.length; i < len; i++ ) {
14688 item = items[ i ];
14689 if ( this.isVisible() ) {
14690 // Defer fitting label until item has been attached
14691 item.fitLabel();
14692 } else {
14693 this.newItems.push( item );
14694 }
14695 }
14696
14697 // Reevaluate clipping
14698 this.clip();
14699
14700 return this;
14701 };
14702
14703 /**
14704 * @inheritdoc
14705 */
14706 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
14707 // Parent method
14708 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
14709
14710 // Reevaluate clipping
14711 this.clip();
14712
14713 return this;
14714 };
14715
14716 /**
14717 * @inheritdoc
14718 */
14719 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
14720 // Parent method
14721 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
14722
14723 // Reevaluate clipping
14724 this.clip();
14725
14726 return this;
14727 };
14728
14729 /**
14730 * @inheritdoc
14731 */
14732 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
14733 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
14734
14735 var i, len,
14736 change = visible !== this.isVisible();
14737
14738 // Parent method
14739 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
14740
14741 if ( change ) {
14742 if ( visible ) {
14743 this.bindKeyDownListener();
14744
14745 if ( this.newItems && this.newItems.length ) {
14746 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
14747 this.newItems[ i ].fitLabel();
14748 }
14749 this.newItems = null;
14750 }
14751 this.toggleClipping( true );
14752
14753 // Auto-hide
14754 if ( this.autoHide ) {
14755 this.getElementDocument().addEventListener(
14756 'mousedown', this.onDocumentMouseDownHandler, true
14757 );
14758 }
14759 } else {
14760 this.unbindKeyDownListener();
14761 this.getElementDocument().removeEventListener(
14762 'mousedown', this.onDocumentMouseDownHandler, true
14763 );
14764 this.toggleClipping( false );
14765 }
14766 }
14767
14768 return this;
14769 };
14770
14771 /**
14772 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14773 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14774 * calculated and maintained when the menu is toggled or the window is resized.
14775 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14776 *
14777 * @class
14778 * @extends OO.ui.MenuSelectWidget
14779 *
14780 * @constructor
14781 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14782 * @param {Object} [config] Configuration options
14783 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14784 */
14785 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
14786 // Allow passing positional parameters inside the config object
14787 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
14788 config = inputWidget;
14789 inputWidget = config.inputWidget;
14790 }
14791
14792 // Configuration initialization
14793 config = config || {};
14794
14795 // Parent constructor
14796 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
14797
14798 // Properties
14799 this.inputWidget = inputWidget;
14800 this.$container = config.$container || this.inputWidget.$element;
14801 this.onWindowResizeHandler = this.onWindowResize.bind( this );
14802
14803 // Initialization
14804 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
14805 };
14806
14807 /* Setup */
14808
14809 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
14810
14811 /* Methods */
14812
14813 /**
14814 * Handle window resize event.
14815 *
14816 * @private
14817 * @param {jQuery.Event} e Window resize event
14818 */
14819 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
14820 this.position();
14821 };
14822
14823 /**
14824 * @inheritdoc
14825 */
14826 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
14827 visible = visible === undefined ? !this.isVisible() : !!visible;
14828
14829 var change = visible !== this.isVisible();
14830
14831 if ( change && visible ) {
14832 // Make sure the width is set before the parent method runs.
14833 // After this we have to call this.position(); again to actually
14834 // position ourselves correctly.
14835 this.position();
14836 }
14837
14838 // Parent method
14839 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
14840
14841 if ( change ) {
14842 if ( this.isVisible() ) {
14843 this.position();
14844 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
14845 } else {
14846 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
14847 }
14848 }
14849
14850 return this;
14851 };
14852
14853 /**
14854 * Position the menu.
14855 *
14856 * @private
14857 * @chainable
14858 */
14859 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
14860 var $container = this.$container,
14861 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
14862
14863 // Position under input
14864 pos.top += $container.height();
14865 this.$element.css( pos );
14866
14867 // Set width
14868 this.setIdealSize( $container.width() );
14869 // We updated the position, so re-evaluate the clipping state
14870 this.clip();
14871
14872 return this;
14873 };
14874
14875 /**
14876 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14877 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14878 *
14879 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14880 *
14881 * @class
14882 * @extends OO.ui.SelectWidget
14883 * @mixins OO.ui.TabIndexedElement
14884 *
14885 * @constructor
14886 * @param {Object} [config] Configuration options
14887 */
14888 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
14889 // Parent constructor
14890 OO.ui.OutlineSelectWidget.super.call( this, config );
14891
14892 // Mixin constructors
14893 OO.ui.TabIndexedElement.call( this, config );
14894
14895 // Events
14896 this.$element.on( {
14897 focus: this.bindKeyDownListener.bind( this ),
14898 blur: this.unbindKeyDownListener.bind( this )
14899 } );
14900
14901 // Initialization
14902 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
14903 };
14904
14905 /* Setup */
14906
14907 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
14908 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
14909
14910 /**
14911 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14912 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14913 * visually by a slider in the leftmost position.
14914 *
14915 * @example
14916 * // Toggle switches in the 'off' and 'on' position.
14917 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14918 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14919 * value: true
14920 * } );
14921 *
14922 * // Create a FieldsetLayout to layout and label switches
14923 * var fieldset = new OO.ui.FieldsetLayout( {
14924 * label: 'Toggle switches'
14925 * } );
14926 * fieldset.addItems( [
14927 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14928 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14929 * ] );
14930 * $( 'body' ).append( fieldset.$element );
14931 *
14932 * @class
14933 * @extends OO.ui.Widget
14934 * @mixins OO.ui.ToggleWidget
14935 * @mixins OO.ui.TabIndexedElement
14936 *
14937 * @constructor
14938 * @param {Object} [config] Configuration options
14939 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14940 * By default, the toggle switch is in the 'off' position.
14941 */
14942 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
14943 // Parent constructor
14944 OO.ui.ToggleSwitchWidget.super.call( this, config );
14945
14946 // Mixin constructors
14947 OO.ui.ToggleWidget.call( this, config );
14948 OO.ui.TabIndexedElement.call( this, config );
14949
14950 // Properties
14951 this.dragging = false;
14952 this.dragStart = null;
14953 this.sliding = false;
14954 this.$glow = $( '<span>' );
14955 this.$grip = $( '<span>' );
14956
14957 // Events
14958 this.$element.on( {
14959 click: this.onClick.bind( this ),
14960 keypress: this.onKeyPress.bind( this )
14961 } );
14962
14963 // Initialization
14964 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14965 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14966 this.$element
14967 .addClass( 'oo-ui-toggleSwitchWidget' )
14968 .attr( 'role', 'checkbox' )
14969 .append( this.$glow, this.$grip );
14970 };
14971
14972 /* Setup */
14973
14974 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
14975 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
14976 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
14977
14978 /* Methods */
14979
14980 /**
14981 * Handle mouse click events.
14982 *
14983 * @private
14984 * @param {jQuery.Event} e Mouse click event
14985 */
14986 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
14987 if ( !this.isDisabled() && e.which === 1 ) {
14988 this.setValue( !this.value );
14989 }
14990 return false;
14991 };
14992
14993 /**
14994 * Handle key press events.
14995 *
14996 * @private
14997 * @param {jQuery.Event} e Key press event
14998 */
14999 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
15000 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
15001 this.setValue( !this.value );
15002 return false;
15003 }
15004 };
15005
15006 }( OO ) );