Merge "Use XML localName when importing"
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.9.7
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-03T21:01:28Z
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 * @class
3344 *
3345 * @constructor
3346 * @param {string|jQuery} message Description of error
3347 * @param {Object} [config] Configuration options
3348 * @cfg {boolean} [recoverable=true] Error is recoverable
3349 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3350 */
3351 OO.ui.Error = function OoUiError( message, config ) {
3352 // Allow passing positional parameters inside the config object
3353 if ( OO.isPlainObject( message ) && config === undefined ) {
3354 config = message;
3355 message = config.message;
3356 }
3357
3358 // Configuration initialization
3359 config = config || {};
3360
3361 // Properties
3362 this.message = message instanceof jQuery ? message : String( message );
3363 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3364 this.warning = !!config.warning;
3365 };
3366
3367 /* Setup */
3368
3369 OO.initClass( OO.ui.Error );
3370
3371 /* Methods */
3372
3373 /**
3374 * Check if error can be recovered from.
3375 *
3376 * @return {boolean} Error is recoverable
3377 */
3378 OO.ui.Error.prototype.isRecoverable = function () {
3379 return this.recoverable;
3380 };
3381
3382 /**
3383 * Check if the error is a warning
3384 *
3385 * @return {boolean} Error is warning
3386 */
3387 OO.ui.Error.prototype.isWarning = function () {
3388 return this.warning;
3389 };
3390
3391 /**
3392 * Get error message as DOM nodes.
3393 *
3394 * @return {jQuery} Error message in DOM nodes
3395 */
3396 OO.ui.Error.prototype.getMessage = function () {
3397 return this.message instanceof jQuery ?
3398 this.message.clone() :
3399 $( '<div>' ).text( this.message ).contents();
3400 };
3401
3402 /**
3403 * Get error message as text.
3404 *
3405 * @return {string} Error message
3406 */
3407 OO.ui.Error.prototype.getMessageText = function () {
3408 return this.message instanceof jQuery ? this.message.text() : this.message;
3409 };
3410
3411 /**
3412 * Wraps an HTML snippet for use with configuration values which default
3413 * to strings. This bypasses the default html-escaping done to string
3414 * values.
3415 *
3416 * @class
3417 *
3418 * @constructor
3419 * @param {string} [content] HTML content
3420 */
3421 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3422 // Properties
3423 this.content = content;
3424 };
3425
3426 /* Setup */
3427
3428 OO.initClass( OO.ui.HtmlSnippet );
3429
3430 /* Methods */
3431
3432 /**
3433 * Render into HTML.
3434 *
3435 * @return {string} Unchanged HTML snippet.
3436 */
3437 OO.ui.HtmlSnippet.prototype.toString = function () {
3438 return this.content;
3439 };
3440
3441 /**
3442 * A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
3443 * or a function:
3444 *
3445 * - **number**: the process will wait for the specified number of milliseconds before proceeding.
3446 * - **promise**: the process will continue to the next step when the promise is successfully resolved
3447 * or stop if the promise is rejected.
3448 * - **function**: the process will execute the function. The process will stop if the function returns
3449 * either a boolean `false` or a promise that is rejected; if the function returns a number, the process
3450 * will wait for that number of milliseconds before proceeding.
3451 *
3452 * If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
3453 * configured, users can dismiss the error and try the process again, or not. If a process is stopped,
3454 * its remaining steps will not be performed.
3455 *
3456 * @class
3457 *
3458 * @constructor
3459 * @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
3460 * that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
3461 * @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
3462 * a number or promise.
3463 * @return {Object} Step object, with `callback` and `context` properties
3464 */
3465 OO.ui.Process = function ( step, context ) {
3466 // Properties
3467 this.steps = [];
3468
3469 // Initialization
3470 if ( step !== undefined ) {
3471 this.next( step, context );
3472 }
3473 };
3474
3475 /* Setup */
3476
3477 OO.initClass( OO.ui.Process );
3478
3479 /* Methods */
3480
3481 /**
3482 * Start the process.
3483 *
3484 * @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
3485 * If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
3486 * and any remaining steps are not performed.
3487 */
3488 OO.ui.Process.prototype.execute = function () {
3489 var i, len, promise;
3490
3491 /**
3492 * Continue execution.
3493 *
3494 * @ignore
3495 * @param {Array} step A function and the context it should be called in
3496 * @return {Function} Function that continues the process
3497 */
3498 function proceed( step ) {
3499 return function () {
3500 // Execute step in the correct context
3501 var deferred,
3502 result = step.callback.call( step.context );
3503
3504 if ( result === false ) {
3505 // Use rejected promise for boolean false results
3506 return $.Deferred().reject( [] ).promise();
3507 }
3508 if ( typeof result === 'number' ) {
3509 if ( result < 0 ) {
3510 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3511 }
3512 // Use a delayed promise for numbers, expecting them to be in milliseconds
3513 deferred = $.Deferred();
3514 setTimeout( deferred.resolve, result );
3515 return deferred.promise();
3516 }
3517 if ( result instanceof OO.ui.Error ) {
3518 // Use rejected promise for error
3519 return $.Deferred().reject( [ result ] ).promise();
3520 }
3521 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3522 // Use rejected promise for list of errors
3523 return $.Deferred().reject( result ).promise();
3524 }
3525 // Duck-type the object to see if it can produce a promise
3526 if ( result && $.isFunction( result.promise ) ) {
3527 // Use a promise generated from the result
3528 return result.promise();
3529 }
3530 // Use resolved promise for other results
3531 return $.Deferred().resolve().promise();
3532 };
3533 }
3534
3535 if ( this.steps.length ) {
3536 // Generate a chain reaction of promises
3537 promise = proceed( this.steps[ 0 ] )();
3538 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3539 promise = promise.then( proceed( this.steps[ i ] ) );
3540 }
3541 } else {
3542 promise = $.Deferred().resolve().promise();
3543 }
3544
3545 return promise;
3546 };
3547
3548 /**
3549 * Create a process step.
3550 *
3551 * @private
3552 * @param {number|jQuery.Promise|Function} step
3553 *
3554 * - Number of milliseconds to wait before proceeding
3555 * - Promise that must be resolved before proceeding
3556 * - Function to execute
3557 * - If the function returns a boolean false the process will stop
3558 * - If the function returns a promise, the process will continue to the next
3559 * step when the promise is resolved or stop if the promise is rejected
3560 * - If the function returns a number, the process will wait for that number of
3561 * milliseconds before proceeding
3562 * @param {Object} [context=null] Execution context of the function. The context is
3563 * ignored if the step is a number or promise.
3564 * @return {Object} Step object, with `callback` and `context` properties
3565 */
3566 OO.ui.Process.prototype.createStep = function ( step, context ) {
3567 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3568 return {
3569 callback: function () {
3570 return step;
3571 },
3572 context: null
3573 };
3574 }
3575 if ( $.isFunction( step ) ) {
3576 return {
3577 callback: step,
3578 context: context
3579 };
3580 }
3581 throw new Error( 'Cannot create process step: number, promise or function expected' );
3582 };
3583
3584 /**
3585 * Add step to the beginning of the process.
3586 *
3587 * @inheritdoc #createStep
3588 * @return {OO.ui.Process} this
3589 * @chainable
3590 */
3591 OO.ui.Process.prototype.first = function ( step, context ) {
3592 this.steps.unshift( this.createStep( step, context ) );
3593 return this;
3594 };
3595
3596 /**
3597 * Add step to the end of the process.
3598 *
3599 * @inheritdoc #createStep
3600 * @return {OO.ui.Process} this
3601 * @chainable
3602 */
3603 OO.ui.Process.prototype.next = function ( step, context ) {
3604 this.steps.push( this.createStep( step, context ) );
3605 return this;
3606 };
3607
3608 /**
3609 * Factory for tools.
3610 *
3611 * @class
3612 * @extends OO.Factory
3613 * @constructor
3614 */
3615 OO.ui.ToolFactory = function OoUiToolFactory() {
3616 // Parent constructor
3617 OO.ui.ToolFactory.super.call( this );
3618 };
3619
3620 /* Setup */
3621
3622 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3623
3624 /* Methods */
3625
3626 /**
3627 * Get tools from the factory
3628 *
3629 * @param {Array} include Included tools
3630 * @param {Array} exclude Excluded tools
3631 * @param {Array} promote Promoted tools
3632 * @param {Array} demote Demoted tools
3633 * @return {string[]} List of tools
3634 */
3635 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3636 var i, len, included, promoted, demoted,
3637 auto = [],
3638 used = {};
3639
3640 // Collect included and not excluded tools
3641 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3642
3643 // Promotion
3644 promoted = this.extract( promote, used );
3645 demoted = this.extract( demote, used );
3646
3647 // Auto
3648 for ( i = 0, len = included.length; i < len; i++ ) {
3649 if ( !used[ included[ i ] ] ) {
3650 auto.push( included[ i ] );
3651 }
3652 }
3653
3654 return promoted.concat( auto ).concat( demoted );
3655 };
3656
3657 /**
3658 * Get a flat list of names from a list of names or groups.
3659 *
3660 * Tools can be specified in the following ways:
3661 *
3662 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3663 * - All tools in a group: `{ group: 'group-name' }`
3664 * - All tools: `'*'`
3665 *
3666 * @private
3667 * @param {Array|string} collection List of tools
3668 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3669 * names will be added as properties
3670 * @return {string[]} List of extracted names
3671 */
3672 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3673 var i, len, item, name, tool,
3674 names = [];
3675
3676 if ( collection === '*' ) {
3677 for ( name in this.registry ) {
3678 tool = this.registry[ name ];
3679 if (
3680 // Only add tools by group name when auto-add is enabled
3681 tool.static.autoAddToCatchall &&
3682 // Exclude already used tools
3683 ( !used || !used[ name ] )
3684 ) {
3685 names.push( name );
3686 if ( used ) {
3687 used[ name ] = true;
3688 }
3689 }
3690 }
3691 } else if ( Array.isArray( collection ) ) {
3692 for ( i = 0, len = collection.length; i < len; i++ ) {
3693 item = collection[ i ];
3694 // Allow plain strings as shorthand for named tools
3695 if ( typeof item === 'string' ) {
3696 item = { name: item };
3697 }
3698 if ( OO.isPlainObject( item ) ) {
3699 if ( item.group ) {
3700 for ( name in this.registry ) {
3701 tool = this.registry[ name ];
3702 if (
3703 // Include tools with matching group
3704 tool.static.group === item.group &&
3705 // Only add tools by group name when auto-add is enabled
3706 tool.static.autoAddToGroup &&
3707 // Exclude already used tools
3708 ( !used || !used[ name ] )
3709 ) {
3710 names.push( name );
3711 if ( used ) {
3712 used[ name ] = true;
3713 }
3714 }
3715 }
3716 // Include tools with matching name and exclude already used tools
3717 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3718 names.push( item.name );
3719 if ( used ) {
3720 used[ item.name ] = true;
3721 }
3722 }
3723 }
3724 }
3725 }
3726 return names;
3727 };
3728
3729 /**
3730 * Factory for tool groups.
3731 *
3732 * @class
3733 * @extends OO.Factory
3734 * @constructor
3735 */
3736 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3737 // Parent constructor
3738 OO.Factory.call( this );
3739
3740 var i, l,
3741 defaultClasses = this.constructor.static.getDefaultClasses();
3742
3743 // Register default toolgroups
3744 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3745 this.register( defaultClasses[ i ] );
3746 }
3747 };
3748
3749 /* Setup */
3750
3751 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3752
3753 /* Static Methods */
3754
3755 /**
3756 * Get a default set of classes to be registered on construction
3757 *
3758 * @return {Function[]} Default classes
3759 */
3760 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3761 return [
3762 OO.ui.BarToolGroup,
3763 OO.ui.ListToolGroup,
3764 OO.ui.MenuToolGroup
3765 ];
3766 };
3767
3768 /**
3769 * Theme logic.
3770 *
3771 * @abstract
3772 * @class
3773 *
3774 * @constructor
3775 * @param {Object} [config] Configuration options
3776 */
3777 OO.ui.Theme = function OoUiTheme( config ) {
3778 // Configuration initialization
3779 config = config || {};
3780 };
3781
3782 /* Setup */
3783
3784 OO.initClass( OO.ui.Theme );
3785
3786 /* Methods */
3787
3788 /**
3789 * Get a list of classes to be applied to a widget.
3790 *
3791 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3792 * otherwise state transitions will not work properly.
3793 *
3794 * @param {OO.ui.Element} element Element for which to get classes
3795 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3796 */
3797 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3798 return { on: [], off: [] };
3799 };
3800
3801 /**
3802 * Update CSS classes provided by the theme.
3803 *
3804 * For elements with theme logic hooks, this should be called any time there's a state change.
3805 *
3806 * @param {OO.ui.Element} element Element for which to update classes
3807 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3808 */
3809 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3810 var classes = this.getElementClasses( element );
3811
3812 element.$element
3813 .removeClass( classes.off.join( ' ' ) )
3814 .addClass( classes.on.join( ' ' ) );
3815 };
3816
3817 /**
3818 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3819 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3820 * order in which users will navigate through the focusable elements via the "tab" key.
3821 *
3822 * @example
3823 * // TabIndexedElement is mixed into the ButtonWidget class
3824 * // to provide a tabIndex property.
3825 * var button1 = new OO.ui.ButtonWidget( {
3826 * label: 'fourth',
3827 * tabIndex: 4
3828 * } );
3829 * var button2 = new OO.ui.ButtonWidget( {
3830 * label: 'second',
3831 * tabIndex: 2
3832 * } );
3833 * var button3 = new OO.ui.ButtonWidget( {
3834 * label: 'third',
3835 * tabIndex: 3
3836 * } );
3837 * var button4 = new OO.ui.ButtonWidget( {
3838 * label: 'first',
3839 * tabIndex: 1
3840 * } );
3841 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3842 *
3843 * @abstract
3844 * @class
3845 *
3846 * @constructor
3847 * @param {Object} [config] Configuration options
3848 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3849 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3850 * functionality will be applied to it instead.
3851 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3852 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3853 * to remove the element from the tab-navigation flow.
3854 */
3855 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3856 // Configuration initialization
3857 config = $.extend( { tabIndex: 0 }, config );
3858
3859 // Properties
3860 this.$tabIndexed = null;
3861 this.tabIndex = null;
3862
3863 // Events
3864 this.connect( this, { disable: 'onDisable' } );
3865
3866 // Initialization
3867 this.setTabIndex( config.tabIndex );
3868 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3869 };
3870
3871 /* Setup */
3872
3873 OO.initClass( OO.ui.TabIndexedElement );
3874
3875 /* Methods */
3876
3877 /**
3878 * Set the element that should use the tabindex functionality.
3879 *
3880 * This method is used to retarget a tabindex mixin so that its functionality applies
3881 * to the specified element. If an element is currently using the functionality, the mixin’s
3882 * effect on that element is removed before the new element is set up.
3883 *
3884 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3885 * @chainable
3886 */
3887 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3888 var tabIndex = this.tabIndex;
3889 // Remove attributes from old $tabIndexed
3890 this.setTabIndex( null );
3891 // Force update of new $tabIndexed
3892 this.$tabIndexed = $tabIndexed;
3893 this.tabIndex = tabIndex;
3894 return this.updateTabIndex();
3895 };
3896
3897 /**
3898 * Set the value of the tabindex.
3899 *
3900 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3901 * @chainable
3902 */
3903 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3904 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3905
3906 if ( this.tabIndex !== tabIndex ) {
3907 this.tabIndex = tabIndex;
3908 this.updateTabIndex();
3909 }
3910
3911 return this;
3912 };
3913
3914 /**
3915 * Update the `tabindex` attribute, in case of changes to tab index or
3916 * disabled state.
3917 *
3918 * @private
3919 * @chainable
3920 */
3921 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3922 if ( this.$tabIndexed ) {
3923 if ( this.tabIndex !== null ) {
3924 // Do not index over disabled elements
3925 this.$tabIndexed.attr( {
3926 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3927 // ChromeVox and NVDA do not seem to inherit this from parent elements
3928 'aria-disabled': this.isDisabled().toString()
3929 } );
3930 } else {
3931 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3932 }
3933 }
3934 return this;
3935 };
3936
3937 /**
3938 * Handle disable events.
3939 *
3940 * @private
3941 * @param {boolean} disabled Element is disabled
3942 */
3943 OO.ui.TabIndexedElement.prototype.onDisable = function () {
3944 this.updateTabIndex();
3945 };
3946
3947 /**
3948 * Get the value of the tabindex.
3949 *
3950 * @return {number|null} Tabindex value
3951 */
3952 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3953 return this.tabIndex;
3954 };
3955
3956 /**
3957 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3958 * interface element that can be configured with access keys for accessibility.
3959 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3960 *
3961 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3962 * @abstract
3963 * @class
3964 *
3965 * @constructor
3966 * @param {Object} [config] Configuration options
3967 * @cfg {jQuery} [$button] The button element created by the class.
3968 * If this configuration is omitted, the button element will use a generated `<a>`.
3969 * @cfg {boolean} [framed=true] Render the button with a frame
3970 * @cfg {string} [accessKey] Button's access key
3971 */
3972 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3973 // Configuration initialization
3974 config = config || {};
3975
3976 // Properties
3977 this.$button = null;
3978 this.framed = null;
3979 this.accessKey = null;
3980 this.active = false;
3981 this.onMouseUpHandler = this.onMouseUp.bind( this );
3982 this.onMouseDownHandler = this.onMouseDown.bind( this );
3983 this.onKeyDownHandler = this.onKeyDown.bind( this );
3984 this.onKeyUpHandler = this.onKeyUp.bind( this );
3985 this.onClickHandler = this.onClick.bind( this );
3986 this.onKeyPressHandler = this.onKeyPress.bind( this );
3987
3988 // Initialization
3989 this.$element.addClass( 'oo-ui-buttonElement' );
3990 this.toggleFramed( config.framed === undefined || config.framed );
3991 this.setAccessKey( config.accessKey );
3992 this.setButtonElement( config.$button || $( '<a>' ) );
3993 };
3994
3995 /* Setup */
3996
3997 OO.initClass( OO.ui.ButtonElement );
3998
3999 /* Static Properties */
4000
4001 /**
4002 * Cancel mouse down events.
4003 *
4004 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
4005 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
4006 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
4007 * parent widget.
4008 *
4009 * @static
4010 * @inheritable
4011 * @property {boolean}
4012 */
4013 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
4014
4015 /* Events */
4016
4017 /**
4018 * A 'click' event is emitted when the button element is clicked.
4019 *
4020 * @event click
4021 */
4022
4023 /* Methods */
4024
4025 /**
4026 * Set the button element.
4027 *
4028 * This method is used to retarget a button mixin so that its functionality applies to
4029 * the specified button element instead of the one created by the class. If a button element
4030 * is already set, the method will remove the mixin’s effect on that element.
4031 *
4032 * @param {jQuery} $button Element to use as button
4033 */
4034 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4035 if ( this.$button ) {
4036 this.$button
4037 .removeClass( 'oo-ui-buttonElement-button' )
4038 .removeAttr( 'role accesskey' )
4039 .off( {
4040 mousedown: this.onMouseDownHandler,
4041 keydown: this.onKeyDownHandler,
4042 click: this.onClickHandler,
4043 keypress: this.onKeyPressHandler
4044 } );
4045 }
4046
4047 this.$button = $button
4048 .addClass( 'oo-ui-buttonElement-button' )
4049 .attr( { role: 'button', accesskey: this.accessKey } )
4050 .on( {
4051 mousedown: this.onMouseDownHandler,
4052 keydown: this.onKeyDownHandler,
4053 click: this.onClickHandler,
4054 keypress: this.onKeyPressHandler
4055 } );
4056 };
4057
4058 /**
4059 * Handles mouse down events.
4060 *
4061 * @protected
4062 * @param {jQuery.Event} e Mouse down event
4063 */
4064 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4065 if ( this.isDisabled() || e.which !== 1 ) {
4066 return;
4067 }
4068 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4069 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4070 // reliably remove the pressed class
4071 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4072 // Prevent change of focus unless specifically configured otherwise
4073 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4074 return false;
4075 }
4076 };
4077
4078 /**
4079 * Handles mouse up events.
4080 *
4081 * @protected
4082 * @param {jQuery.Event} e Mouse up event
4083 */
4084 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4085 if ( this.isDisabled() || e.which !== 1 ) {
4086 return;
4087 }
4088 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4089 // Stop listening for mouseup, since we only needed this once
4090 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4091 };
4092
4093 /**
4094 * Handles mouse click events.
4095 *
4096 * @protected
4097 * @param {jQuery.Event} e Mouse click event
4098 * @fires click
4099 */
4100 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4101 if ( !this.isDisabled() && e.which === 1 ) {
4102 this.emit( 'click' );
4103 }
4104 return false;
4105 };
4106
4107 /**
4108 * Handles key down events.
4109 *
4110 * @protected
4111 * @param {jQuery.Event} e Key down event
4112 */
4113 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4114 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4115 return;
4116 }
4117 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4118 // Run the keyup handler no matter where the key is when the button is let go, so we can
4119 // reliably remove the pressed class
4120 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4121 };
4122
4123 /**
4124 * Handles key up events.
4125 *
4126 * @protected
4127 * @param {jQuery.Event} e Key up event
4128 */
4129 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4130 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4131 return;
4132 }
4133 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4134 // Stop listening for keyup, since we only needed this once
4135 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4136 };
4137
4138 /**
4139 * Handles key press events.
4140 *
4141 * @protected
4142 * @param {jQuery.Event} e Key press event
4143 * @fires click
4144 */
4145 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4146 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4147 this.emit( 'click' );
4148 return false;
4149 }
4150 };
4151
4152 /**
4153 * Check if button has a frame.
4154 *
4155 * @return {boolean} Button is framed
4156 */
4157 OO.ui.ButtonElement.prototype.isFramed = function () {
4158 return this.framed;
4159 };
4160
4161 /**
4162 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4163 *
4164 * @param {boolean} [framed] Make button framed, omit to toggle
4165 * @chainable
4166 */
4167 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4168 framed = framed === undefined ? !this.framed : !!framed;
4169 if ( framed !== this.framed ) {
4170 this.framed = framed;
4171 this.$element
4172 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4173 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4174 this.updateThemeClasses();
4175 }
4176
4177 return this;
4178 };
4179
4180 /**
4181 * Set the button's access key.
4182 *
4183 * @param {string} accessKey Button's access key, use empty string to remove
4184 * @chainable
4185 */
4186 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4187 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4188
4189 if ( this.accessKey !== accessKey ) {
4190 if ( this.$button ) {
4191 if ( accessKey !== null ) {
4192 this.$button.attr( 'accesskey', accessKey );
4193 } else {
4194 this.$button.removeAttr( 'accesskey' );
4195 }
4196 }
4197 this.accessKey = accessKey;
4198 }
4199
4200 return this;
4201 };
4202
4203 /**
4204 * Set the button to its 'active' state.
4205 *
4206 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4207 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4208 * for other button types.
4209 *
4210 * @param {boolean} [value] Make button active
4211 * @chainable
4212 */
4213 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4214 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4215 return this;
4216 };
4217
4218 /**
4219 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4220 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4221 * items from the group is done through the interface the class provides.
4222 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4223 *
4224 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4225 *
4226 * @abstract
4227 * @class
4228 *
4229 * @constructor
4230 * @param {Object} [config] Configuration options
4231 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4232 * is omitted, the group element will use a generated `<div>`.
4233 */
4234 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4235 // Configuration initialization
4236 config = config || {};
4237
4238 // Properties
4239 this.$group = null;
4240 this.items = [];
4241 this.aggregateItemEvents = {};
4242
4243 // Initialization
4244 this.setGroupElement( config.$group || $( '<div>' ) );
4245 };
4246
4247 /* Methods */
4248
4249 /**
4250 * Set the group element.
4251 *
4252 * If an element is already set, items will be moved to the new element.
4253 *
4254 * @param {jQuery} $group Element to use as group
4255 */
4256 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4257 var i, len;
4258
4259 this.$group = $group;
4260 for ( i = 0, len = this.items.length; i < len; i++ ) {
4261 this.$group.append( this.items[ i ].$element );
4262 }
4263 };
4264
4265 /**
4266 * Check if a group contains no items.
4267 *
4268 * @return {boolean} Group is empty
4269 */
4270 OO.ui.GroupElement.prototype.isEmpty = function () {
4271 return !this.items.length;
4272 };
4273
4274 /**
4275 * Get all items in the group.
4276 *
4277 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4278 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4279 * from a group).
4280 *
4281 * @return {OO.ui.Element[]} An array of items.
4282 */
4283 OO.ui.GroupElement.prototype.getItems = function () {
4284 return this.items.slice( 0 );
4285 };
4286
4287 /**
4288 * Get an item by its data.
4289 *
4290 * Only the first item with matching data will be returned. To return all matching items,
4291 * use the #getItemsFromData method.
4292 *
4293 * @param {Object} data Item data to search for
4294 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4295 */
4296 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4297 var i, len, item,
4298 hash = OO.getHash( data );
4299
4300 for ( i = 0, len = this.items.length; i < len; i++ ) {
4301 item = this.items[ i ];
4302 if ( hash === OO.getHash( item.getData() ) ) {
4303 return item;
4304 }
4305 }
4306
4307 return null;
4308 };
4309
4310 /**
4311 * Get items by their data.
4312 *
4313 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4314 *
4315 * @param {Object} data Item data to search for
4316 * @return {OO.ui.Element[]} Items with equivalent data
4317 */
4318 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4319 var i, len, item,
4320 hash = OO.getHash( data ),
4321 items = [];
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 items.push( item );
4327 }
4328 }
4329
4330 return items;
4331 };
4332
4333 /**
4334 * Aggregate the events emitted by the group.
4335 *
4336 * When events are aggregated, the group will listen to all contained items for the event,
4337 * and then emit the event under a new name. The new event will contain an additional leading
4338 * parameter containing the item that emitted the original event. Other arguments emitted from
4339 * the original event are passed through.
4340 *
4341 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4342 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4343 * A `null` value will remove aggregated events.
4344
4345 * @throws {Error} An error is thrown if aggregation already exists.
4346 */
4347 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4348 var i, len, item, add, remove, itemEvent, groupEvent;
4349
4350 for ( itemEvent in events ) {
4351 groupEvent = events[ itemEvent ];
4352
4353 // Remove existing aggregated event
4354 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4355 // Don't allow duplicate aggregations
4356 if ( groupEvent ) {
4357 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4358 }
4359 // Remove event aggregation from existing items
4360 for ( i = 0, len = this.items.length; i < len; i++ ) {
4361 item = this.items[ i ];
4362 if ( item.connect && item.disconnect ) {
4363 remove = {};
4364 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4365 item.disconnect( this, remove );
4366 }
4367 }
4368 // Prevent future items from aggregating event
4369 delete this.aggregateItemEvents[ itemEvent ];
4370 }
4371
4372 // Add new aggregate event
4373 if ( groupEvent ) {
4374 // Make future items aggregate event
4375 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4376 // Add event aggregation to existing items
4377 for ( i = 0, len = this.items.length; i < len; i++ ) {
4378 item = this.items[ i ];
4379 if ( item.connect && item.disconnect ) {
4380 add = {};
4381 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4382 item.connect( this, add );
4383 }
4384 }
4385 }
4386 }
4387 };
4388
4389 /**
4390 * Add items to the group.
4391 *
4392 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4393 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4394 *
4395 * @param {OO.ui.Element[]} items An array of items to add to the group
4396 * @param {number} [index] Index of the insertion point
4397 * @chainable
4398 */
4399 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4400 var i, len, item, event, events, currentIndex,
4401 itemElements = [];
4402
4403 for ( i = 0, len = items.length; i < len; i++ ) {
4404 item = items[ i ];
4405
4406 // Check if item exists then remove it first, effectively "moving" it
4407 currentIndex = $.inArray( item, this.items );
4408 if ( currentIndex >= 0 ) {
4409 this.removeItems( [ item ] );
4410 // Adjust index to compensate for removal
4411 if ( currentIndex < index ) {
4412 index--;
4413 }
4414 }
4415 // Add the item
4416 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4417 events = {};
4418 for ( event in this.aggregateItemEvents ) {
4419 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4420 }
4421 item.connect( this, events );
4422 }
4423 item.setElementGroup( this );
4424 itemElements.push( item.$element.get( 0 ) );
4425 }
4426
4427 if ( index === undefined || index < 0 || index >= this.items.length ) {
4428 this.$group.append( itemElements );
4429 this.items.push.apply( this.items, items );
4430 } else if ( index === 0 ) {
4431 this.$group.prepend( itemElements );
4432 this.items.unshift.apply( this.items, items );
4433 } else {
4434 this.items[ index ].$element.before( itemElements );
4435 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4436 }
4437
4438 return this;
4439 };
4440
4441 /**
4442 * Remove the specified items from a group.
4443 *
4444 * Removed items are detached (not removed) from the DOM so that they may be reused.
4445 * To remove all items from a group, you may wish to use the #clearItems method instead.
4446 *
4447 * @param {OO.ui.Element[]} items An array of items to remove
4448 * @chainable
4449 */
4450 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4451 var i, len, item, index, remove, itemEvent;
4452
4453 // Remove specific items
4454 for ( i = 0, len = items.length; i < len; i++ ) {
4455 item = items[ i ];
4456 index = $.inArray( item, this.items );
4457 if ( index !== -1 ) {
4458 if (
4459 item.connect && item.disconnect &&
4460 !$.isEmptyObject( this.aggregateItemEvents )
4461 ) {
4462 remove = {};
4463 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4464 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4465 }
4466 item.disconnect( this, remove );
4467 }
4468 item.setElementGroup( null );
4469 this.items.splice( index, 1 );
4470 item.$element.detach();
4471 }
4472 }
4473
4474 return this;
4475 };
4476
4477 /**
4478 * Clear all items from the group.
4479 *
4480 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4481 * To remove only a subset of items from a group, use the #removeItems method.
4482 *
4483 * @chainable
4484 */
4485 OO.ui.GroupElement.prototype.clearItems = function () {
4486 var i, len, item, remove, itemEvent;
4487
4488 // Remove all items
4489 for ( i = 0, len = this.items.length; i < len; i++ ) {
4490 item = this.items[ i ];
4491 if (
4492 item.connect && item.disconnect &&
4493 !$.isEmptyObject( this.aggregateItemEvents )
4494 ) {
4495 remove = {};
4496 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4497 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4498 }
4499 item.disconnect( this, remove );
4500 }
4501 item.setElementGroup( null );
4502 item.$element.detach();
4503 }
4504
4505 this.items = [];
4506 return this;
4507 };
4508
4509 /**
4510 * DraggableElement is a mixin class used to create elements that can be clicked
4511 * and dragged by a mouse to a new position within a group. This class must be used
4512 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4513 * the draggable elements.
4514 *
4515 * @abstract
4516 * @class
4517 *
4518 * @constructor
4519 */
4520 OO.ui.DraggableElement = function OoUiDraggableElement() {
4521 // Properties
4522 this.index = null;
4523
4524 // Initialize and events
4525 this.$element
4526 .attr( 'draggable', true )
4527 .addClass( 'oo-ui-draggableElement' )
4528 .on( {
4529 dragstart: this.onDragStart.bind( this ),
4530 dragover: this.onDragOver.bind( this ),
4531 dragend: this.onDragEnd.bind( this ),
4532 drop: this.onDrop.bind( this )
4533 } );
4534 };
4535
4536 OO.initClass( OO.ui.DraggableElement );
4537
4538 /* Events */
4539
4540 /**
4541 * @event dragstart
4542 *
4543 * A dragstart event is emitted when the user clicks and begins dragging an item.
4544 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4545 */
4546
4547 /**
4548 * @event dragend
4549 * A dragend event is emitted when the user drags an item and releases the mouse,
4550 * thus terminating the drag operation.
4551 */
4552
4553 /**
4554 * @event drop
4555 * A drop event is emitted when the user drags an item and then releases the mouse button
4556 * over a valid target.
4557 */
4558
4559 /* Static Properties */
4560
4561 /**
4562 * @inheritdoc OO.ui.ButtonElement
4563 */
4564 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4565
4566 /* Methods */
4567
4568 /**
4569 * Respond to dragstart event.
4570 *
4571 * @private
4572 * @param {jQuery.Event} event jQuery event
4573 * @fires dragstart
4574 */
4575 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4576 var dataTransfer = e.originalEvent.dataTransfer;
4577 // Define drop effect
4578 dataTransfer.dropEffect = 'none';
4579 dataTransfer.effectAllowed = 'move';
4580 // We must set up a dataTransfer data property or Firefox seems to
4581 // ignore the fact the element is draggable.
4582 try {
4583 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4584 } catch ( err ) {
4585 // The above is only for firefox. No need to set a catch clause
4586 // if it fails, move on.
4587 }
4588 // Add dragging class
4589 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4590 // Emit event
4591 this.emit( 'dragstart', this );
4592 return true;
4593 };
4594
4595 /**
4596 * Respond to dragend event.
4597 *
4598 * @private
4599 * @fires dragend
4600 */
4601 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4602 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4603 this.emit( 'dragend' );
4604 };
4605
4606 /**
4607 * Handle drop event.
4608 *
4609 * @private
4610 * @param {jQuery.Event} event jQuery event
4611 * @fires drop
4612 */
4613 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4614 e.preventDefault();
4615 this.emit( 'drop', e );
4616 };
4617
4618 /**
4619 * In order for drag/drop to work, the dragover event must
4620 * return false and stop propogation.
4621 *
4622 * @private
4623 */
4624 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4625 e.preventDefault();
4626 };
4627
4628 /**
4629 * Set item index.
4630 * Store it in the DOM so we can access from the widget drag event
4631 *
4632 * @private
4633 * @param {number} Item index
4634 */
4635 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4636 if ( this.index !== index ) {
4637 this.index = index;
4638 this.$element.data( 'index', index );
4639 }
4640 };
4641
4642 /**
4643 * Get item index
4644 *
4645 * @private
4646 * @return {number} Item index
4647 */
4648 OO.ui.DraggableElement.prototype.getIndex = function () {
4649 return this.index;
4650 };
4651
4652 /**
4653 * DraggableGroupElement is a mixin class used to create a group element to
4654 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4655 * The class is used with OO.ui.DraggableElement.
4656 *
4657 * @abstract
4658 * @class
4659 * @mixins OO.ui.GroupElement
4660 *
4661 * @constructor
4662 * @param {Object} [config] Configuration options
4663 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4664 * should match the layout of the items. Items displayed in a single row
4665 * or in several rows should use horizontal orientation. The vertical orientation should only be
4666 * used when the items are displayed in a single column. Defaults to 'vertical'
4667 */
4668 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4669 // Configuration initialization
4670 config = config || {};
4671
4672 // Parent constructor
4673 OO.ui.GroupElement.call( this, config );
4674
4675 // Properties
4676 this.orientation = config.orientation || 'vertical';
4677 this.dragItem = null;
4678 this.itemDragOver = null;
4679 this.itemKeys = {};
4680 this.sideInsertion = '';
4681
4682 // Events
4683 this.aggregate( {
4684 dragstart: 'itemDragStart',
4685 dragend: 'itemDragEnd',
4686 drop: 'itemDrop'
4687 } );
4688 this.connect( this, {
4689 itemDragStart: 'onItemDragStart',
4690 itemDrop: 'onItemDrop',
4691 itemDragEnd: 'onItemDragEnd'
4692 } );
4693 this.$element.on( {
4694 dragover: $.proxy( this.onDragOver, this ),
4695 dragleave: $.proxy( this.onDragLeave, this )
4696 } );
4697
4698 // Initialize
4699 if ( Array.isArray( config.items ) ) {
4700 this.addItems( config.items );
4701 }
4702 this.$placeholder = $( '<div>' )
4703 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4704 this.$element
4705 .addClass( 'oo-ui-draggableGroupElement' )
4706 .append( this.$status )
4707 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4708 .prepend( this.$placeholder );
4709 };
4710
4711 /* Setup */
4712 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4713
4714 /* Events */
4715
4716 /**
4717 * A 'reorder' event is emitted when the order of items in the group changes.
4718 *
4719 * @event reorder
4720 * @param {OO.ui.DraggableElement} item Reordered item
4721 * @param {number} [newIndex] New index for the item
4722 */
4723
4724 /* Methods */
4725
4726 /**
4727 * Respond to item drag start event
4728 *
4729 * @private
4730 * @param {OO.ui.DraggableElement} item Dragged item
4731 */
4732 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4733 var i, len;
4734
4735 // Map the index of each object
4736 for ( i = 0, len = this.items.length; i < len; i++ ) {
4737 this.items[ i ].setIndex( i );
4738 }
4739
4740 if ( this.orientation === 'horizontal' ) {
4741 // Set the height of the indicator
4742 this.$placeholder.css( {
4743 height: item.$element.outerHeight(),
4744 width: 2
4745 } );
4746 } else {
4747 // Set the width of the indicator
4748 this.$placeholder.css( {
4749 height: 2,
4750 width: item.$element.outerWidth()
4751 } );
4752 }
4753 this.setDragItem( item );
4754 };
4755
4756 /**
4757 * Respond to item drag end event
4758 *
4759 * @private
4760 */
4761 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4762 this.unsetDragItem();
4763 return false;
4764 };
4765
4766 /**
4767 * Handle drop event and switch the order of the items accordingly
4768 *
4769 * @private
4770 * @param {OO.ui.DraggableElement} item Dropped item
4771 * @fires reorder
4772 */
4773 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4774 var toIndex = item.getIndex();
4775 // Check if the dropped item is from the current group
4776 // TODO: Figure out a way to configure a list of legally droppable
4777 // elements even if they are not yet in the list
4778 if ( this.getDragItem() ) {
4779 // If the insertion point is 'after', the insertion index
4780 // is shifted to the right (or to the left in RTL, hence 'after')
4781 if ( this.sideInsertion === 'after' ) {
4782 toIndex++;
4783 }
4784 // Emit change event
4785 this.emit( 'reorder', this.getDragItem(), toIndex );
4786 }
4787 this.unsetDragItem();
4788 // Return false to prevent propogation
4789 return false;
4790 };
4791
4792 /**
4793 * Handle dragleave event.
4794 *
4795 * @private
4796 */
4797 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4798 // This means the item was dragged outside the widget
4799 this.$placeholder
4800 .css( 'left', 0 )
4801 .addClass( 'oo-ui-element-hidden' );
4802 };
4803
4804 /**
4805 * Respond to dragover event
4806 *
4807 * @private
4808 * @param {jQuery.Event} event Event details
4809 */
4810 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4811 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4812 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4813 clientX = e.originalEvent.clientX,
4814 clientY = e.originalEvent.clientY;
4815
4816 // Get the OptionWidget item we are dragging over
4817 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4818 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4819 if ( $optionWidget[ 0 ] ) {
4820 itemOffset = $optionWidget.offset();
4821 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4822 itemPosition = $optionWidget.position();
4823 itemIndex = $optionWidget.data( 'index' );
4824 }
4825
4826 if (
4827 itemOffset &&
4828 this.isDragging() &&
4829 itemIndex !== this.getDragItem().getIndex()
4830 ) {
4831 if ( this.orientation === 'horizontal' ) {
4832 // Calculate where the mouse is relative to the item width
4833 itemSize = itemBoundingRect.width;
4834 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4835 dragPosition = clientX;
4836 // Which side of the item we hover over will dictate
4837 // where the placeholder will appear, on the left or
4838 // on the right
4839 cssOutput = {
4840 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4841 top: itemPosition.top
4842 };
4843 } else {
4844 // Calculate where the mouse is relative to the item height
4845 itemSize = itemBoundingRect.height;
4846 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4847 dragPosition = clientY;
4848 // Which side of the item we hover over will dictate
4849 // where the placeholder will appear, on the top or
4850 // on the bottom
4851 cssOutput = {
4852 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4853 left: itemPosition.left
4854 };
4855 }
4856 // Store whether we are before or after an item to rearrange
4857 // For horizontal layout, we need to account for RTL, as this is flipped
4858 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4859 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4860 } else {
4861 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4862 }
4863 // Add drop indicator between objects
4864 this.$placeholder
4865 .css( cssOutput )
4866 .removeClass( 'oo-ui-element-hidden' );
4867 } else {
4868 // This means the item was dragged outside the widget
4869 this.$placeholder
4870 .css( 'left', 0 )
4871 .addClass( 'oo-ui-element-hidden' );
4872 }
4873 // Prevent default
4874 e.preventDefault();
4875 };
4876
4877 /**
4878 * Set a dragged item
4879 *
4880 * @param {OO.ui.DraggableElement} item Dragged item
4881 */
4882 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4883 this.dragItem = item;
4884 };
4885
4886 /**
4887 * Unset the current dragged item
4888 */
4889 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4890 this.dragItem = null;
4891 this.itemDragOver = null;
4892 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4893 this.sideInsertion = '';
4894 };
4895
4896 /**
4897 * Get the item that is currently being dragged.
4898 *
4899 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4900 */
4901 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4902 return this.dragItem;
4903 };
4904
4905 /**
4906 * Check if an item in the group is currently being dragged.
4907 *
4908 * @return {Boolean} Item is being dragged
4909 */
4910 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4911 return this.getDragItem() !== null;
4912 };
4913
4914 /**
4915 * IconElement is often mixed into other classes to generate an icon.
4916 * Icons are graphics, about the size of normal text. They are used to aid the user
4917 * in locating a control or to convey information in a space-efficient way. See the
4918 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4919 * included in the library.
4920 *
4921 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4922 *
4923 * @abstract
4924 * @class
4925 *
4926 * @constructor
4927 * @param {Object} [config] Configuration options
4928 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4929 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4930 * the icon element be set to an existing icon instead of the one generated by this class, set a
4931 * value using a jQuery selection. For example:
4932 *
4933 * // Use a <div> tag instead of a <span>
4934 * $icon: $("<div>")
4935 * // Use an existing icon element instead of the one generated by the class
4936 * $icon: this.$element
4937 * // Use an icon element from a child widget
4938 * $icon: this.childwidget.$element
4939 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4940 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4941 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4942 * by the user's language.
4943 *
4944 * Example of an i18n map:
4945 *
4946 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4947 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4948 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4949 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4950 * text. The icon title is displayed when users move the mouse over the icon.
4951 */
4952 OO.ui.IconElement = function OoUiIconElement( config ) {
4953 // Configuration initialization
4954 config = config || {};
4955
4956 // Properties
4957 this.$icon = null;
4958 this.icon = null;
4959 this.iconTitle = null;
4960
4961 // Initialization
4962 this.setIcon( config.icon || this.constructor.static.icon );
4963 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4964 this.setIconElement( config.$icon || $( '<span>' ) );
4965 };
4966
4967 /* Setup */
4968
4969 OO.initClass( OO.ui.IconElement );
4970
4971 /* Static Properties */
4972
4973 /**
4974 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4975 * for i18n purposes and contains a `default` icon name and additional names keyed by
4976 * language code. The `default` name is used when no icon is keyed by the user's language.
4977 *
4978 * Example of an i18n map:
4979 *
4980 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4981 *
4982 * Note: the static property will be overridden if the #icon configuration is used.
4983 *
4984 * @static
4985 * @inheritable
4986 * @property {Object|string}
4987 */
4988 OO.ui.IconElement.static.icon = null;
4989
4990 /**
4991 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4992 * function that returns title text, or `null` for no title.
4993 *
4994 * The static property will be overridden if the #iconTitle configuration is used.
4995 *
4996 * @static
4997 * @inheritable
4998 * @property {string|Function|null}
4999 */
5000 OO.ui.IconElement.static.iconTitle = null;
5001
5002 /* Methods */
5003
5004 /**
5005 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
5006 * applies to the specified icon element instead of the one created by the class. If an icon
5007 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5008 * and mixin methods will no longer affect the element.
5009 *
5010 * @param {jQuery} $icon Element to use as icon
5011 */
5012 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5013 if ( this.$icon ) {
5014 this.$icon
5015 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5016 .removeAttr( 'title' );
5017 }
5018
5019 this.$icon = $icon
5020 .addClass( 'oo-ui-iconElement-icon' )
5021 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5022 if ( this.iconTitle !== null ) {
5023 this.$icon.attr( 'title', this.iconTitle );
5024 }
5025 };
5026
5027 /**
5028 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5029 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5030 * for an example.
5031 *
5032 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5033 * by language code, or `null` to remove the icon.
5034 * @chainable
5035 */
5036 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5037 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5038 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5039
5040 if ( this.icon !== icon ) {
5041 if ( this.$icon ) {
5042 if ( this.icon !== null ) {
5043 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5044 }
5045 if ( icon !== null ) {
5046 this.$icon.addClass( 'oo-ui-icon-' + icon );
5047 }
5048 }
5049 this.icon = icon;
5050 }
5051
5052 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5053 this.updateThemeClasses();
5054
5055 return this;
5056 };
5057
5058 /**
5059 * Set the icon title. Use `null` to remove the title.
5060 *
5061 * @param {string|Function|null} iconTitle A text string used as the icon title,
5062 * a function that returns title text, or `null` for no title.
5063 * @chainable
5064 */
5065 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5066 iconTitle = typeof iconTitle === 'function' ||
5067 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5068 OO.ui.resolveMsg( iconTitle ) : null;
5069
5070 if ( this.iconTitle !== iconTitle ) {
5071 this.iconTitle = iconTitle;
5072 if ( this.$icon ) {
5073 if ( this.iconTitle !== null ) {
5074 this.$icon.attr( 'title', iconTitle );
5075 } else {
5076 this.$icon.removeAttr( 'title' );
5077 }
5078 }
5079 }
5080
5081 return this;
5082 };
5083
5084 /**
5085 * Get the symbolic name of the icon.
5086 *
5087 * @return {string} Icon name
5088 */
5089 OO.ui.IconElement.prototype.getIcon = function () {
5090 return this.icon;
5091 };
5092
5093 /**
5094 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5095 *
5096 * @return {string} Icon title text
5097 */
5098 OO.ui.IconElement.prototype.getIconTitle = function () {
5099 return this.iconTitle;
5100 };
5101
5102 /**
5103 * IndicatorElement is often mixed into other classes to generate an indicator.
5104 * Indicators are small graphics that are generally used in two ways:
5105 *
5106 * - To draw attention to the status of an item. For example, an indicator might be
5107 * used to show that an item in a list has errors that need to be resolved.
5108 * - To clarify the function of a control that acts in an exceptional way (a button
5109 * that opens a menu instead of performing an action directly, for example).
5110 *
5111 * For a list of indicators included in the library, please see the
5112 * [OOjs UI documentation on MediaWiki] [1].
5113 *
5114 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5115 *
5116 * @abstract
5117 * @class
5118 *
5119 * @constructor
5120 * @param {Object} [config] Configuration options
5121 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5122 * configuration is omitted, the indicator element will use a generated `<span>`.
5123 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5124 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5125 * in the library.
5126 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5127 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5128 * or a function that returns title text. The indicator title is displayed when users move
5129 * the mouse over the indicator.
5130 */
5131 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5132 // Configuration initialization
5133 config = config || {};
5134
5135 // Properties
5136 this.$indicator = null;
5137 this.indicator = null;
5138 this.indicatorTitle = null;
5139
5140 // Initialization
5141 this.setIndicator( config.indicator || this.constructor.static.indicator );
5142 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5143 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5144 };
5145
5146 /* Setup */
5147
5148 OO.initClass( OO.ui.IndicatorElement );
5149
5150 /* Static Properties */
5151
5152 /**
5153 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5154 * The static property will be overridden if the #indicator configuration is used.
5155 *
5156 * @static
5157 * @inheritable
5158 * @property {string|null}
5159 */
5160 OO.ui.IndicatorElement.static.indicator = null;
5161
5162 /**
5163 * A text string used as the indicator title, a function that returns title text, or `null`
5164 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5165 *
5166 * @static
5167 * @inheritable
5168 * @property {string|Function|null}
5169 */
5170 OO.ui.IndicatorElement.static.indicatorTitle = null;
5171
5172 /* Methods */
5173
5174 /**
5175 * Set the indicator element.
5176 *
5177 * If an element is already set, it will be cleaned up before setting up the new element.
5178 *
5179 * @param {jQuery} $indicator Element to use as indicator
5180 */
5181 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5182 if ( this.$indicator ) {
5183 this.$indicator
5184 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5185 .removeAttr( 'title' );
5186 }
5187
5188 this.$indicator = $indicator
5189 .addClass( 'oo-ui-indicatorElement-indicator' )
5190 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5191 if ( this.indicatorTitle !== null ) {
5192 this.$indicator.attr( 'title', this.indicatorTitle );
5193 }
5194 };
5195
5196 /**
5197 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5198 *
5199 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5200 * @chainable
5201 */
5202 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5203 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5204
5205 if ( this.indicator !== indicator ) {
5206 if ( this.$indicator ) {
5207 if ( this.indicator !== null ) {
5208 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5209 }
5210 if ( indicator !== null ) {
5211 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5212 }
5213 }
5214 this.indicator = indicator;
5215 }
5216
5217 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5218 this.updateThemeClasses();
5219
5220 return this;
5221 };
5222
5223 /**
5224 * Set the indicator title.
5225 *
5226 * The title is displayed when a user moves the mouse over the indicator.
5227 *
5228 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5229 * `null` for no indicator title
5230 * @chainable
5231 */
5232 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5233 indicatorTitle = typeof indicatorTitle === 'function' ||
5234 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5235 OO.ui.resolveMsg( indicatorTitle ) : null;
5236
5237 if ( this.indicatorTitle !== indicatorTitle ) {
5238 this.indicatorTitle = indicatorTitle;
5239 if ( this.$indicator ) {
5240 if ( this.indicatorTitle !== null ) {
5241 this.$indicator.attr( 'title', indicatorTitle );
5242 } else {
5243 this.$indicator.removeAttr( 'title' );
5244 }
5245 }
5246 }
5247
5248 return this;
5249 };
5250
5251 /**
5252 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5253 *
5254 * @return {string} Symbolic name of indicator
5255 */
5256 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5257 return this.indicator;
5258 };
5259
5260 /**
5261 * Get the indicator title.
5262 *
5263 * The title is displayed when a user moves the mouse over the indicator.
5264 *
5265 * @return {string} Indicator title text
5266 */
5267 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5268 return this.indicatorTitle;
5269 };
5270
5271 /**
5272 * LabelElement is often mixed into other classes to generate a label, which
5273 * helps identify the function of an interface element.
5274 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5275 *
5276 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5277 *
5278 * @abstract
5279 * @class
5280 *
5281 * @constructor
5282 * @param {Object} [config] Configuration options
5283 * @cfg {jQuery} [$label] The label element created by the class. If this
5284 * configuration is omitted, the label element will use a generated `<span>`.
5285 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5286 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5287 * [OOjs UI documentation on MediaWiki] [2] for examples.
5288 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5289 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5290 * The label will be truncated to fit if necessary.
5291 */
5292 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5293 // Configuration initialization
5294 config = config || {};
5295
5296 // Properties
5297 this.$label = null;
5298 this.label = null;
5299 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5300
5301 // Initialization
5302 this.setLabel( config.label || this.constructor.static.label );
5303 this.setLabelElement( config.$label || $( '<span>' ) );
5304 };
5305
5306 /* Setup */
5307
5308 OO.initClass( OO.ui.LabelElement );
5309
5310 /* Events */
5311
5312 /**
5313 * @event labelChange
5314 * @param {string} value
5315 */
5316
5317 /* Static Properties */
5318
5319 /**
5320 * The label text. The label can be specified as a plaintext string, a function that will
5321 * produce a string in the future, or `null` for no label. The static value will
5322 * be overridden if a label is specified with the #label config option.
5323 *
5324 * @static
5325 * @inheritable
5326 * @property {string|Function|null}
5327 */
5328 OO.ui.LabelElement.static.label = null;
5329
5330 /* Methods */
5331
5332 /**
5333 * Set the label element.
5334 *
5335 * If an element is already set, it will be cleaned up before setting up the new element.
5336 *
5337 * @param {jQuery} $label Element to use as label
5338 */
5339 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5340 if ( this.$label ) {
5341 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5342 }
5343
5344 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5345 this.setLabelContent( this.label );
5346 };
5347
5348 /**
5349 * Set the label.
5350 *
5351 * An empty string will result in the label being hidden. A string containing only whitespace will
5352 * be converted to a single `&nbsp;`.
5353 *
5354 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5355 * text; or null for no label
5356 * @chainable
5357 */
5358 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5359 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5360 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5361
5362 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5363
5364 if ( this.label !== label ) {
5365 if ( this.$label ) {
5366 this.setLabelContent( label );
5367 }
5368 this.label = label;
5369 this.emit( 'labelChange' );
5370 }
5371
5372 return this;
5373 };
5374
5375 /**
5376 * Get the label.
5377 *
5378 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5379 * text; or null for no label
5380 */
5381 OO.ui.LabelElement.prototype.getLabel = function () {
5382 return this.label;
5383 };
5384
5385 /**
5386 * Fit the label.
5387 *
5388 * @chainable
5389 */
5390 OO.ui.LabelElement.prototype.fitLabel = function () {
5391 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5392 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5393 }
5394
5395 return this;
5396 };
5397
5398 /**
5399 * Set the content of the label.
5400 *
5401 * Do not call this method until after the label element has been set by #setLabelElement.
5402 *
5403 * @private
5404 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5405 * text; or null for no label
5406 */
5407 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5408 if ( typeof label === 'string' ) {
5409 if ( label.match( /^\s*$/ ) ) {
5410 // Convert whitespace only string to a single non-breaking space
5411 this.$label.html( '&nbsp;' );
5412 } else {
5413 this.$label.text( label );
5414 }
5415 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5416 this.$label.html( label.toString() );
5417 } else if ( label instanceof jQuery ) {
5418 this.$label.empty().append( label );
5419 } else {
5420 this.$label.empty();
5421 }
5422 };
5423
5424 /**
5425 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5426 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5427 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5428 * from the lookup menu, that value becomes the value of the input field.
5429 *
5430 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5431 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5432 * re-enable lookups.
5433 *
5434 * See the [OOjs UI demos][1] for an example.
5435 *
5436 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5437 *
5438 * @class
5439 * @abstract
5440 *
5441 * @constructor
5442 * @param {Object} [config] Configuration options
5443 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5444 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5445 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5446 * By default, the lookup menu is not generated and displayed until the user begins to type.
5447 */
5448 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5449 // Configuration initialization
5450 config = config || {};
5451
5452 // Properties
5453 this.$overlay = config.$overlay || this.$element;
5454 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5455 widget: this,
5456 input: this,
5457 $container: config.$container
5458 } );
5459
5460 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5461
5462 this.lookupCache = {};
5463 this.lookupQuery = null;
5464 this.lookupRequest = null;
5465 this.lookupsDisabled = false;
5466 this.lookupInputFocused = false;
5467
5468 // Events
5469 this.$input.on( {
5470 focus: this.onLookupInputFocus.bind( this ),
5471 blur: this.onLookupInputBlur.bind( this ),
5472 mousedown: this.onLookupInputMouseDown.bind( this )
5473 } );
5474 this.connect( this, { change: 'onLookupInputChange' } );
5475 this.lookupMenu.connect( this, {
5476 toggle: 'onLookupMenuToggle',
5477 choose: 'onLookupMenuItemChoose'
5478 } );
5479
5480 // Initialization
5481 this.$element.addClass( 'oo-ui-lookupElement' );
5482 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5483 this.$overlay.append( this.lookupMenu.$element );
5484 };
5485
5486 /* Methods */
5487
5488 /**
5489 * Handle input focus event.
5490 *
5491 * @protected
5492 * @param {jQuery.Event} e Input focus event
5493 */
5494 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5495 this.lookupInputFocused = true;
5496 this.populateLookupMenu();
5497 };
5498
5499 /**
5500 * Handle input blur event.
5501 *
5502 * @protected
5503 * @param {jQuery.Event} e Input blur event
5504 */
5505 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5506 this.closeLookupMenu();
5507 this.lookupInputFocused = false;
5508 };
5509
5510 /**
5511 * Handle input mouse down event.
5512 *
5513 * @protected
5514 * @param {jQuery.Event} e Input mouse down event
5515 */
5516 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5517 // Only open the menu if the input was already focused.
5518 // This way we allow the user to open the menu again after closing it with Esc
5519 // by clicking in the input. Opening (and populating) the menu when initially
5520 // clicking into the input is handled by the focus handler.
5521 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5522 this.populateLookupMenu();
5523 }
5524 };
5525
5526 /**
5527 * Handle input change event.
5528 *
5529 * @protected
5530 * @param {string} value New input value
5531 */
5532 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5533 if ( this.lookupInputFocused ) {
5534 this.populateLookupMenu();
5535 }
5536 };
5537
5538 /**
5539 * Handle the lookup menu being shown/hidden.
5540 *
5541 * @protected
5542 * @param {boolean} visible Whether the lookup menu is now visible.
5543 */
5544 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5545 if ( !visible ) {
5546 // When the menu is hidden, abort any active request and clear the menu.
5547 // This has to be done here in addition to closeLookupMenu(), because
5548 // MenuSelectWidget will close itself when the user presses Esc.
5549 this.abortLookupRequest();
5550 this.lookupMenu.clearItems();
5551 }
5552 };
5553
5554 /**
5555 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5556 *
5557 * @protected
5558 * @param {OO.ui.MenuOptionWidget} item Selected item
5559 */
5560 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5561 this.setValue( item.getData() );
5562 };
5563
5564 /**
5565 * Get lookup menu.
5566 *
5567 * @private
5568 * @return {OO.ui.TextInputMenuSelectWidget}
5569 */
5570 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5571 return this.lookupMenu;
5572 };
5573
5574 /**
5575 * Disable or re-enable lookups.
5576 *
5577 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5578 *
5579 * @param {boolean} disabled Disable lookups
5580 */
5581 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5582 this.lookupsDisabled = !!disabled;
5583 };
5584
5585 /**
5586 * Open the menu. If there are no entries in the menu, this does nothing.
5587 *
5588 * @private
5589 * @chainable
5590 */
5591 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5592 if ( !this.lookupMenu.isEmpty() ) {
5593 this.lookupMenu.toggle( true );
5594 }
5595 return this;
5596 };
5597
5598 /**
5599 * Close the menu, empty it, and abort any pending request.
5600 *
5601 * @private
5602 * @chainable
5603 */
5604 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5605 this.lookupMenu.toggle( false );
5606 this.abortLookupRequest();
5607 this.lookupMenu.clearItems();
5608 return this;
5609 };
5610
5611 /**
5612 * Request menu items based on the input's current value, and when they arrive,
5613 * populate the menu with these items and show the menu.
5614 *
5615 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5616 *
5617 * @private
5618 * @chainable
5619 */
5620 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5621 var widget = this,
5622 value = this.getValue();
5623
5624 if ( this.lookupsDisabled ) {
5625 return;
5626 }
5627
5628 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5629 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5630 this.closeLookupMenu();
5631 // Skip population if there is already a request pending for the current value
5632 } else if ( value !== this.lookupQuery ) {
5633 this.getLookupMenuItems()
5634 .done( function ( items ) {
5635 widget.lookupMenu.clearItems();
5636 if ( items.length ) {
5637 widget.lookupMenu
5638 .addItems( items )
5639 .toggle( true );
5640 widget.initializeLookupMenuSelection();
5641 } else {
5642 widget.lookupMenu.toggle( false );
5643 }
5644 } )
5645 .fail( function () {
5646 widget.lookupMenu.clearItems();
5647 } );
5648 }
5649
5650 return this;
5651 };
5652
5653 /**
5654 * Select and highlight the first selectable item in the menu.
5655 *
5656 * @private
5657 * @chainable
5658 */
5659 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5660 if ( !this.lookupMenu.getSelectedItem() ) {
5661 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5662 }
5663 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5664 };
5665
5666 /**
5667 * Get lookup menu items for the current query.
5668 *
5669 * @private
5670 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5671 * the done event. If the request was aborted to make way for a subsequent request, this promise
5672 * will not be rejected: it will remain pending forever.
5673 */
5674 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5675 var widget = this,
5676 value = this.getValue(),
5677 deferred = $.Deferred(),
5678 ourRequest;
5679
5680 this.abortLookupRequest();
5681 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5682 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5683 } else {
5684 this.pushPending();
5685 this.lookupQuery = value;
5686 ourRequest = this.lookupRequest = this.getLookupRequest();
5687 ourRequest
5688 .always( function () {
5689 // We need to pop pending even if this is an old request, otherwise
5690 // the widget will remain pending forever.
5691 // TODO: this assumes that an aborted request will fail or succeed soon after
5692 // being aborted, or at least eventually. It would be nice if we could popPending()
5693 // at abort time, but only if we knew that we hadn't already called popPending()
5694 // for that request.
5695 widget.popPending();
5696 } )
5697 .done( function ( response ) {
5698 // If this is an old request (and aborting it somehow caused it to still succeed),
5699 // ignore its success completely
5700 if ( ourRequest === widget.lookupRequest ) {
5701 widget.lookupQuery = null;
5702 widget.lookupRequest = null;
5703 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5704 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5705 }
5706 } )
5707 .fail( function () {
5708 // If this is an old request (or a request failing because it's being aborted),
5709 // ignore its failure completely
5710 if ( ourRequest === widget.lookupRequest ) {
5711 widget.lookupQuery = null;
5712 widget.lookupRequest = null;
5713 deferred.reject();
5714 }
5715 } );
5716 }
5717 return deferred.promise();
5718 };
5719
5720 /**
5721 * Abort the currently pending lookup request, if any.
5722 *
5723 * @private
5724 */
5725 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5726 var oldRequest = this.lookupRequest;
5727 if ( oldRequest ) {
5728 // First unset this.lookupRequest to the fail handler will notice
5729 // that the request is no longer current
5730 this.lookupRequest = null;
5731 this.lookupQuery = null;
5732 oldRequest.abort();
5733 }
5734 };
5735
5736 /**
5737 * Get a new request object of the current lookup query value.
5738 *
5739 * @protected
5740 * @abstract
5741 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5742 */
5743 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5744 // Stub, implemented in subclass
5745 return null;
5746 };
5747
5748 /**
5749 * Pre-process data returned by the request from #getLookupRequest.
5750 *
5751 * The return value of this function will be cached, and any further queries for the given value
5752 * will use the cache rather than doing API requests.
5753 *
5754 * @protected
5755 * @abstract
5756 * @param {Mixed} response Response from server
5757 * @return {Mixed} Cached result data
5758 */
5759 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5760 // Stub, implemented in subclass
5761 return [];
5762 };
5763
5764 /**
5765 * Get a list of menu option widgets from the (possibly cached) data returned by
5766 * #getLookupCacheDataFromResponse.
5767 *
5768 * @protected
5769 * @abstract
5770 * @param {Mixed} data Cached result data, usually an array
5771 * @return {OO.ui.MenuOptionWidget[]} Menu items
5772 */
5773 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5774 // Stub, implemented in subclass
5775 return [];
5776 };
5777
5778 /**
5779 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5780 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5781 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5782 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5783 *
5784 * @abstract
5785 * @class
5786 *
5787 * @constructor
5788 * @param {Object} [config] Configuration options
5789 * @cfg {Object} [popup] Configuration to pass to popup
5790 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5791 */
5792 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5793 // Configuration initialization
5794 config = config || {};
5795
5796 // Properties
5797 this.popup = new OO.ui.PopupWidget( $.extend(
5798 { autoClose: true },
5799 config.popup,
5800 { $autoCloseIgnore: this.$element }
5801 ) );
5802 };
5803
5804 /* Methods */
5805
5806 /**
5807 * Get popup.
5808 *
5809 * @return {OO.ui.PopupWidget} Popup widget
5810 */
5811 OO.ui.PopupElement.prototype.getPopup = function () {
5812 return this.popup;
5813 };
5814
5815 /**
5816 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5817 * additional functionality to an element created by another class. The class provides
5818 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5819 * which are used to customize the look and feel of a widget to better describe its
5820 * importance and functionality.
5821 *
5822 * The library currently contains the following styling flags for general use:
5823 *
5824 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5825 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5826 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5827 *
5828 * The flags affect the appearance of the buttons:
5829 *
5830 * @example
5831 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5832 * var button1 = new OO.ui.ButtonWidget( {
5833 * label: 'Constructive',
5834 * flags: 'constructive'
5835 * } );
5836 * var button2 = new OO.ui.ButtonWidget( {
5837 * label: 'Destructive',
5838 * flags: 'destructive'
5839 * } );
5840 * var button3 = new OO.ui.ButtonWidget( {
5841 * label: 'Progressive',
5842 * flags: 'progressive'
5843 * } );
5844 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5845 *
5846 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5847 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5848 *
5849 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5850 *
5851 * @abstract
5852 * @class
5853 *
5854 * @constructor
5855 * @param {Object} [config] Configuration options
5856 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5857 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5858 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5859 * @cfg {jQuery} [$flagged] The flagged element. By default,
5860 * the flagged functionality is applied to the element created by the class ($element).
5861 * If a different element is specified, the flagged functionality will be applied to it instead.
5862 */
5863 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5864 // Configuration initialization
5865 config = config || {};
5866
5867 // Properties
5868 this.flags = {};
5869 this.$flagged = null;
5870
5871 // Initialization
5872 this.setFlags( config.flags );
5873 this.setFlaggedElement( config.$flagged || this.$element );
5874 };
5875
5876 /* Events */
5877
5878 /**
5879 * @event flag
5880 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5881 * parameter contains the name of each modified flag and indicates whether it was
5882 * added or removed.
5883 *
5884 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5885 * that the flag was added, `false` that the flag was removed.
5886 */
5887
5888 /* Methods */
5889
5890 /**
5891 * Set the flagged element.
5892 *
5893 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5894 * If an element is already set, the method will remove the mixin’s effect on that element.
5895 *
5896 * @param {jQuery} $flagged Element that should be flagged
5897 */
5898 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5899 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5900 return 'oo-ui-flaggedElement-' + flag;
5901 } ).join( ' ' );
5902
5903 if ( this.$flagged ) {
5904 this.$flagged.removeClass( classNames );
5905 }
5906
5907 this.$flagged = $flagged.addClass( classNames );
5908 };
5909
5910 /**
5911 * Check if the specified flag is set.
5912 *
5913 * @param {string} flag Name of flag
5914 * @return {boolean} The flag is set
5915 */
5916 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5917 return flag in this.flags;
5918 };
5919
5920 /**
5921 * Get the names of all flags set.
5922 *
5923 * @return {string[]} Flag names
5924 */
5925 OO.ui.FlaggedElement.prototype.getFlags = function () {
5926 return Object.keys( this.flags );
5927 };
5928
5929 /**
5930 * Clear all flags.
5931 *
5932 * @chainable
5933 * @fires flag
5934 */
5935 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5936 var flag, className,
5937 changes = {},
5938 remove = [],
5939 classPrefix = 'oo-ui-flaggedElement-';
5940
5941 for ( flag in this.flags ) {
5942 className = classPrefix + flag;
5943 changes[ flag ] = false;
5944 delete this.flags[ flag ];
5945 remove.push( className );
5946 }
5947
5948 if ( this.$flagged ) {
5949 this.$flagged.removeClass( remove.join( ' ' ) );
5950 }
5951
5952 this.updateThemeClasses();
5953 this.emit( 'flag', changes );
5954
5955 return this;
5956 };
5957
5958 /**
5959 * Add one or more flags.
5960 *
5961 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5962 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5963 * be added (`true`) or removed (`false`).
5964 * @chainable
5965 * @fires flag
5966 */
5967 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5968 var i, len, flag, className,
5969 changes = {},
5970 add = [],
5971 remove = [],
5972 classPrefix = 'oo-ui-flaggedElement-';
5973
5974 if ( typeof flags === 'string' ) {
5975 className = classPrefix + flags;
5976 // Set
5977 if ( !this.flags[ flags ] ) {
5978 this.flags[ flags ] = true;
5979 add.push( className );
5980 }
5981 } else if ( Array.isArray( flags ) ) {
5982 for ( i = 0, len = flags.length; i < len; i++ ) {
5983 flag = flags[ i ];
5984 className = classPrefix + flag;
5985 // Set
5986 if ( !this.flags[ flag ] ) {
5987 changes[ flag ] = true;
5988 this.flags[ flag ] = true;
5989 add.push( className );
5990 }
5991 }
5992 } else if ( OO.isPlainObject( flags ) ) {
5993 for ( flag in flags ) {
5994 className = classPrefix + flag;
5995 if ( flags[ flag ] ) {
5996 // Set
5997 if ( !this.flags[ flag ] ) {
5998 changes[ flag ] = true;
5999 this.flags[ flag ] = true;
6000 add.push( className );
6001 }
6002 } else {
6003 // Remove
6004 if ( this.flags[ flag ] ) {
6005 changes[ flag ] = false;
6006 delete this.flags[ flag ];
6007 remove.push( className );
6008 }
6009 }
6010 }
6011 }
6012
6013 if ( this.$flagged ) {
6014 this.$flagged
6015 .addClass( add.join( ' ' ) )
6016 .removeClass( remove.join( ' ' ) );
6017 }
6018
6019 this.updateThemeClasses();
6020 this.emit( 'flag', changes );
6021
6022 return this;
6023 };
6024
6025 /**
6026 * TitledElement is mixed into other classes to provide a `title` attribute.
6027 * Titles are rendered by the browser and are made visible when the user moves
6028 * the mouse over the element. Titles are not visible on touch devices.
6029 *
6030 * @example
6031 * // TitledElement provides a 'title' attribute to the
6032 * // ButtonWidget class
6033 * var button = new OO.ui.ButtonWidget( {
6034 * label: 'Button with Title',
6035 * title: 'I am a button'
6036 * } );
6037 * $( 'body' ).append( button.$element );
6038 *
6039 * @abstract
6040 * @class
6041 *
6042 * @constructor
6043 * @param {Object} [config] Configuration options
6044 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6045 * If this config is omitted, the title functionality is applied to $element, the
6046 * element created by the class.
6047 * @cfg {string|Function} [title] The title text or a function that returns text. If
6048 * this config is omitted, the value of the {@link #static-title static title} property is used.
6049 */
6050 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6051 // Configuration initialization
6052 config = config || {};
6053
6054 // Properties
6055 this.$titled = null;
6056 this.title = null;
6057
6058 // Initialization
6059 this.setTitle( config.title || this.constructor.static.title );
6060 this.setTitledElement( config.$titled || this.$element );
6061 };
6062
6063 /* Setup */
6064
6065 OO.initClass( OO.ui.TitledElement );
6066
6067 /* Static Properties */
6068
6069 /**
6070 * The title text, a function that returns text, or `null` for no title. The value of the static property
6071 * is overridden if the #title config option is used.
6072 *
6073 * @static
6074 * @inheritable
6075 * @property {string|Function|null}
6076 */
6077 OO.ui.TitledElement.static.title = null;
6078
6079 /* Methods */
6080
6081 /**
6082 * Set the titled element.
6083 *
6084 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6085 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6086 *
6087 * @param {jQuery} $titled Element that should use the 'titled' functionality
6088 */
6089 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6090 if ( this.$titled ) {
6091 this.$titled.removeAttr( 'title' );
6092 }
6093
6094 this.$titled = $titled;
6095 if ( this.title ) {
6096 this.$titled.attr( 'title', this.title );
6097 }
6098 };
6099
6100 /**
6101 * Set title.
6102 *
6103 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6104 * @chainable
6105 */
6106 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6107 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6108
6109 if ( this.title !== title ) {
6110 if ( this.$titled ) {
6111 if ( title !== null ) {
6112 this.$titled.attr( 'title', title );
6113 } else {
6114 this.$titled.removeAttr( 'title' );
6115 }
6116 }
6117 this.title = title;
6118 }
6119
6120 return this;
6121 };
6122
6123 /**
6124 * Get title.
6125 *
6126 * @return {string} Title string
6127 */
6128 OO.ui.TitledElement.prototype.getTitle = function () {
6129 return this.title;
6130 };
6131
6132 /**
6133 * Element that can be automatically clipped to visible boundaries.
6134 *
6135 * Whenever the element's natural height changes, you have to call
6136 * #clip to make sure it's still clipping correctly.
6137 *
6138 * @abstract
6139 * @class
6140 *
6141 * @constructor
6142 * @param {Object} [config] Configuration options
6143 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6144 */
6145 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6146 // Configuration initialization
6147 config = config || {};
6148
6149 // Properties
6150 this.$clippable = null;
6151 this.clipping = false;
6152 this.clippedHorizontally = false;
6153 this.clippedVertically = false;
6154 this.$clippableContainer = null;
6155 this.$clippableScroller = null;
6156 this.$clippableWindow = null;
6157 this.idealWidth = null;
6158 this.idealHeight = null;
6159 this.onClippableContainerScrollHandler = this.clip.bind( this );
6160 this.onClippableWindowResizeHandler = this.clip.bind( this );
6161
6162 // Initialization
6163 this.setClippableElement( config.$clippable || this.$element );
6164 };
6165
6166 /* Methods */
6167
6168 /**
6169 * Set clippable element.
6170 *
6171 * If an element is already set, it will be cleaned up before setting up the new element.
6172 *
6173 * @param {jQuery} $clippable Element to make clippable
6174 */
6175 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6176 if ( this.$clippable ) {
6177 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6178 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6179 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6180 }
6181
6182 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6183 this.clip();
6184 };
6185
6186 /**
6187 * Toggle clipping.
6188 *
6189 * Do not turn clipping on until after the element is attached to the DOM and visible.
6190 *
6191 * @param {boolean} [clipping] Enable clipping, omit to toggle
6192 * @chainable
6193 */
6194 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6195 clipping = clipping === undefined ? !this.clipping : !!clipping;
6196
6197 if ( this.clipping !== clipping ) {
6198 this.clipping = clipping;
6199 if ( clipping ) {
6200 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6201 // If the clippable container is the root, we have to listen to scroll events and check
6202 // jQuery.scrollTop on the window because of browser inconsistencies
6203 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6204 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6205 this.$clippableContainer;
6206 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6207 this.$clippableWindow = $( this.getElementWindow() )
6208 .on( 'resize', this.onClippableWindowResizeHandler );
6209 // Initial clip after visible
6210 this.clip();
6211 } else {
6212 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6213 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6214
6215 this.$clippableContainer = null;
6216 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6217 this.$clippableScroller = null;
6218 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6219 this.$clippableWindow = null;
6220 }
6221 }
6222
6223 return this;
6224 };
6225
6226 /**
6227 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6228 *
6229 * @return {boolean} Element will be clipped to the visible area
6230 */
6231 OO.ui.ClippableElement.prototype.isClipping = function () {
6232 return this.clipping;
6233 };
6234
6235 /**
6236 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6237 *
6238 * @return {boolean} Part of the element is being clipped
6239 */
6240 OO.ui.ClippableElement.prototype.isClipped = function () {
6241 return this.clippedHorizontally || this.clippedVertically;
6242 };
6243
6244 /**
6245 * Check if the right of the element is being clipped by the nearest scrollable container.
6246 *
6247 * @return {boolean} Part of the element is being clipped
6248 */
6249 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6250 return this.clippedHorizontally;
6251 };
6252
6253 /**
6254 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6255 *
6256 * @return {boolean} Part of the element is being clipped
6257 */
6258 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6259 return this.clippedVertically;
6260 };
6261
6262 /**
6263 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6264 *
6265 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6266 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6267 */
6268 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6269 this.idealWidth = width;
6270 this.idealHeight = height;
6271
6272 if ( !this.clipping ) {
6273 // Update dimensions
6274 this.$clippable.css( { width: width, height: height } );
6275 }
6276 // While clipping, idealWidth and idealHeight are not considered
6277 };
6278
6279 /**
6280 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6281 * the element's natural height changes.
6282 *
6283 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6284 * overlapped by, the visible area of the nearest scrollable container.
6285 *
6286 * @chainable
6287 */
6288 OO.ui.ClippableElement.prototype.clip = function () {
6289 if ( !this.clipping ) {
6290 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6291 return this;
6292 }
6293
6294 var buffer = 7, // Chosen by fair dice roll
6295 cOffset = this.$clippable.offset(),
6296 $container = this.$clippableContainer.is( 'html, body' ) ?
6297 this.$clippableWindow : this.$clippableContainer,
6298 ccOffset = $container.offset() || { top: 0, left: 0 },
6299 ccHeight = $container.innerHeight() - buffer,
6300 ccWidth = $container.innerWidth() - buffer,
6301 cHeight = this.$clippable.outerHeight() + buffer,
6302 cWidth = this.$clippable.outerWidth() + buffer,
6303 scrollTop = this.$clippableScroller.scrollTop(),
6304 scrollLeft = this.$clippableScroller.scrollLeft(),
6305 desiredWidth = cOffset.left < 0 ?
6306 cWidth + cOffset.left :
6307 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6308 desiredHeight = cOffset.top < 0 ?
6309 cHeight + cOffset.top :
6310 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6311 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6312 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6313 clipWidth = desiredWidth < naturalWidth,
6314 clipHeight = desiredHeight < naturalHeight;
6315
6316 if ( clipWidth ) {
6317 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6318 } else {
6319 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6320 }
6321 if ( clipHeight ) {
6322 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6323 } else {
6324 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6325 }
6326
6327 // If we stopped clipping in at least one of the dimensions
6328 if ( !clipWidth || !clipHeight ) {
6329 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6330 }
6331
6332 this.clippedHorizontally = clipWidth;
6333 this.clippedVertically = clipHeight;
6334
6335 return this;
6336 };
6337
6338 /**
6339 * Generic toolbar tool.
6340 *
6341 * @abstract
6342 * @class
6343 * @extends OO.ui.Widget
6344 * @mixins OO.ui.IconElement
6345 * @mixins OO.ui.FlaggedElement
6346 *
6347 * @constructor
6348 * @param {OO.ui.ToolGroup} toolGroup
6349 * @param {Object} [config] Configuration options
6350 * @cfg {string|Function} [title] Title text or a function that returns text
6351 */
6352 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6353 // Allow passing positional parameters inside the config object
6354 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6355 config = toolGroup;
6356 toolGroup = config.toolGroup;
6357 }
6358
6359 // Configuration initialization
6360 config = config || {};
6361
6362 // Parent constructor
6363 OO.ui.Tool.super.call( this, config );
6364
6365 // Mixin constructors
6366 OO.ui.IconElement.call( this, config );
6367 OO.ui.FlaggedElement.call( this, config );
6368
6369 // Properties
6370 this.toolGroup = toolGroup;
6371 this.toolbar = this.toolGroup.getToolbar();
6372 this.active = false;
6373 this.$title = $( '<span>' );
6374 this.$accel = $( '<span>' );
6375 this.$link = $( '<a>' );
6376 this.title = null;
6377
6378 // Events
6379 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6380
6381 // Initialization
6382 this.$title.addClass( 'oo-ui-tool-title' );
6383 this.$accel
6384 .addClass( 'oo-ui-tool-accel' )
6385 .prop( {
6386 // This may need to be changed if the key names are ever localized,
6387 // but for now they are essentially written in English
6388 dir: 'ltr',
6389 lang: 'en'
6390 } );
6391 this.$link
6392 .addClass( 'oo-ui-tool-link' )
6393 .append( this.$icon, this.$title, this.$accel )
6394 .prop( 'tabIndex', 0 )
6395 .attr( 'role', 'button' );
6396 this.$element
6397 .data( 'oo-ui-tool', this )
6398 .addClass(
6399 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6400 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6401 )
6402 .append( this.$link );
6403 this.setTitle( config.title || this.constructor.static.title );
6404 };
6405
6406 /* Setup */
6407
6408 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6409 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6410 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6411
6412 /* Events */
6413
6414 /**
6415 * @event select
6416 */
6417
6418 /* Static Properties */
6419
6420 /**
6421 * @static
6422 * @inheritdoc
6423 */
6424 OO.ui.Tool.static.tagName = 'span';
6425
6426 /**
6427 * Symbolic name of tool.
6428 *
6429 * @abstract
6430 * @static
6431 * @inheritable
6432 * @property {string}
6433 */
6434 OO.ui.Tool.static.name = '';
6435
6436 /**
6437 * Tool group.
6438 *
6439 * @abstract
6440 * @static
6441 * @inheritable
6442 * @property {string}
6443 */
6444 OO.ui.Tool.static.group = '';
6445
6446 /**
6447 * Tool title.
6448 *
6449 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6450 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6451 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6452 * appended to the title if the tool is part of a bar tool group.
6453 *
6454 * @abstract
6455 * @static
6456 * @inheritable
6457 * @property {string|Function} Title text or a function that returns text
6458 */
6459 OO.ui.Tool.static.title = '';
6460
6461 /**
6462 * Tool can be automatically added to catch-all groups.
6463 *
6464 * @static
6465 * @inheritable
6466 * @property {boolean}
6467 */
6468 OO.ui.Tool.static.autoAddToCatchall = true;
6469
6470 /**
6471 * Tool can be automatically added to named groups.
6472 *
6473 * @static
6474 * @property {boolean}
6475 * @inheritable
6476 */
6477 OO.ui.Tool.static.autoAddToGroup = true;
6478
6479 /**
6480 * Check if this tool is compatible with given data.
6481 *
6482 * @static
6483 * @inheritable
6484 * @param {Mixed} data Data to check
6485 * @return {boolean} Tool can be used with data
6486 */
6487 OO.ui.Tool.static.isCompatibleWith = function () {
6488 return false;
6489 };
6490
6491 /* Methods */
6492
6493 /**
6494 * Handle the toolbar state being updated.
6495 *
6496 * This is an abstract method that must be overridden in a concrete subclass.
6497 *
6498 * @abstract
6499 */
6500 OO.ui.Tool.prototype.onUpdateState = function () {
6501 throw new Error(
6502 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6503 );
6504 };
6505
6506 /**
6507 * Handle the tool being selected.
6508 *
6509 * This is an abstract method that must be overridden in a concrete subclass.
6510 *
6511 * @abstract
6512 */
6513 OO.ui.Tool.prototype.onSelect = function () {
6514 throw new Error(
6515 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6516 );
6517 };
6518
6519 /**
6520 * Check if the button is active.
6521 *
6522 * @return {boolean} Button is active
6523 */
6524 OO.ui.Tool.prototype.isActive = function () {
6525 return this.active;
6526 };
6527
6528 /**
6529 * Make the button appear active or inactive.
6530 *
6531 * @param {boolean} state Make button appear active
6532 */
6533 OO.ui.Tool.prototype.setActive = function ( state ) {
6534 this.active = !!state;
6535 if ( this.active ) {
6536 this.$element.addClass( 'oo-ui-tool-active' );
6537 } else {
6538 this.$element.removeClass( 'oo-ui-tool-active' );
6539 }
6540 };
6541
6542 /**
6543 * Get the tool title.
6544 *
6545 * @param {string|Function} title Title text or a function that returns text
6546 * @chainable
6547 */
6548 OO.ui.Tool.prototype.setTitle = function ( title ) {
6549 this.title = OO.ui.resolveMsg( title );
6550 this.updateTitle();
6551 return this;
6552 };
6553
6554 /**
6555 * Get the tool title.
6556 *
6557 * @return {string} Title text
6558 */
6559 OO.ui.Tool.prototype.getTitle = function () {
6560 return this.title;
6561 };
6562
6563 /**
6564 * Get the tool's symbolic name.
6565 *
6566 * @return {string} Symbolic name of tool
6567 */
6568 OO.ui.Tool.prototype.getName = function () {
6569 return this.constructor.static.name;
6570 };
6571
6572 /**
6573 * Update the title.
6574 */
6575 OO.ui.Tool.prototype.updateTitle = function () {
6576 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6577 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6578 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6579 tooltipParts = [];
6580
6581 this.$title.text( this.title );
6582 this.$accel.text( accel );
6583
6584 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6585 tooltipParts.push( this.title );
6586 }
6587 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6588 tooltipParts.push( accel );
6589 }
6590 if ( tooltipParts.length ) {
6591 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6592 } else {
6593 this.$link.removeAttr( 'title' );
6594 }
6595 };
6596
6597 /**
6598 * Destroy tool.
6599 */
6600 OO.ui.Tool.prototype.destroy = function () {
6601 this.toolbar.disconnect( this );
6602 this.$element.remove();
6603 };
6604
6605 /**
6606 * Collection of tool groups.
6607 *
6608 * @class
6609 * @extends OO.ui.Element
6610 * @mixins OO.EventEmitter
6611 * @mixins OO.ui.GroupElement
6612 *
6613 * @constructor
6614 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6615 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6616 * @param {Object} [config] Configuration options
6617 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6618 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6619 */
6620 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6621 // Allow passing positional parameters inside the config object
6622 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6623 config = toolFactory;
6624 toolFactory = config.toolFactory;
6625 toolGroupFactory = config.toolGroupFactory;
6626 }
6627
6628 // Configuration initialization
6629 config = config || {};
6630
6631 // Parent constructor
6632 OO.ui.Toolbar.super.call( this, config );
6633
6634 // Mixin constructors
6635 OO.EventEmitter.call( this );
6636 OO.ui.GroupElement.call( this, config );
6637
6638 // Properties
6639 this.toolFactory = toolFactory;
6640 this.toolGroupFactory = toolGroupFactory;
6641 this.groups = [];
6642 this.tools = {};
6643 this.$bar = $( '<div>' );
6644 this.$actions = $( '<div>' );
6645 this.initialized = false;
6646 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6647
6648 // Events
6649 this.$element
6650 .add( this.$bar ).add( this.$group ).add( this.$actions )
6651 .on( 'mousedown', this.onPointerDown.bind( this ) );
6652
6653 // Initialization
6654 this.$group.addClass( 'oo-ui-toolbar-tools' );
6655 if ( config.actions ) {
6656 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6657 }
6658 this.$bar
6659 .addClass( 'oo-ui-toolbar-bar' )
6660 .append( this.$group, '<div style="clear:both"></div>' );
6661 if ( config.shadow ) {
6662 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6663 }
6664 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6665 };
6666
6667 /* Setup */
6668
6669 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6670 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6671 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6672
6673 /* Methods */
6674
6675 /**
6676 * Get the tool factory.
6677 *
6678 * @return {OO.ui.ToolFactory} Tool factory
6679 */
6680 OO.ui.Toolbar.prototype.getToolFactory = function () {
6681 return this.toolFactory;
6682 };
6683
6684 /**
6685 * Get the tool group factory.
6686 *
6687 * @return {OO.Factory} Tool group factory
6688 */
6689 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6690 return this.toolGroupFactory;
6691 };
6692
6693 /**
6694 * Handles mouse down events.
6695 *
6696 * @param {jQuery.Event} e Mouse down event
6697 */
6698 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6699 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6700 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6701 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6702 return false;
6703 }
6704 };
6705
6706 /**
6707 * Handle window resize event.
6708 *
6709 * @private
6710 * @param {jQuery.Event} e Window resize event
6711 */
6712 OO.ui.Toolbar.prototype.onWindowResize = function () {
6713 this.$element.toggleClass(
6714 'oo-ui-toolbar-narrow',
6715 this.$bar.width() <= this.narrowThreshold
6716 );
6717 };
6718
6719 /**
6720 * Sets up handles and preloads required information for the toolbar to work.
6721 * This must be called after it is attached to a visible document and before doing anything else.
6722 */
6723 OO.ui.Toolbar.prototype.initialize = function () {
6724 this.initialized = true;
6725 this.narrowThreshold = this.$group.width() + this.$actions.width();
6726 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6727 this.onWindowResize();
6728 };
6729
6730 /**
6731 * Setup toolbar.
6732 *
6733 * Tools can be specified in the following ways:
6734 *
6735 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6736 * - All tools in a group: `{ group: 'group-name' }`
6737 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6738 *
6739 * @param {Object.<string,Array>} groups List of tool group configurations
6740 * @param {Array|string} [groups.include] Tools to include
6741 * @param {Array|string} [groups.exclude] Tools to exclude
6742 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6743 * @param {Array|string} [groups.demote] Tools to demote to the end
6744 */
6745 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6746 var i, len, type, group,
6747 items = [],
6748 defaultType = 'bar';
6749
6750 // Cleanup previous groups
6751 this.reset();
6752
6753 // Build out new groups
6754 for ( i = 0, len = groups.length; i < len; i++ ) {
6755 group = groups[ i ];
6756 if ( group.include === '*' ) {
6757 // Apply defaults to catch-all groups
6758 if ( group.type === undefined ) {
6759 group.type = 'list';
6760 }
6761 if ( group.label === undefined ) {
6762 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6763 }
6764 }
6765 // Check type has been registered
6766 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6767 items.push(
6768 this.getToolGroupFactory().create( type, this, group )
6769 );
6770 }
6771 this.addItems( items );
6772 };
6773
6774 /**
6775 * Remove all tools and groups from the toolbar.
6776 */
6777 OO.ui.Toolbar.prototype.reset = function () {
6778 var i, len;
6779
6780 this.groups = [];
6781 this.tools = {};
6782 for ( i = 0, len = this.items.length; i < len; i++ ) {
6783 this.items[ i ].destroy();
6784 }
6785 this.clearItems();
6786 };
6787
6788 /**
6789 * Destroys toolbar, removing event handlers and DOM elements.
6790 *
6791 * Call this whenever you are done using a toolbar.
6792 */
6793 OO.ui.Toolbar.prototype.destroy = function () {
6794 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
6795 this.reset();
6796 this.$element.remove();
6797 };
6798
6799 /**
6800 * Check if tool has not been used yet.
6801 *
6802 * @param {string} name Symbolic name of tool
6803 * @return {boolean} Tool is available
6804 */
6805 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6806 return !this.tools[ name ];
6807 };
6808
6809 /**
6810 * Prevent tool from being used again.
6811 *
6812 * @param {OO.ui.Tool} tool Tool to reserve
6813 */
6814 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6815 this.tools[ tool.getName() ] = tool;
6816 };
6817
6818 /**
6819 * Allow tool to be used again.
6820 *
6821 * @param {OO.ui.Tool} tool Tool to release
6822 */
6823 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6824 delete this.tools[ tool.getName() ];
6825 };
6826
6827 /**
6828 * Get accelerator label for tool.
6829 *
6830 * This is a stub that should be overridden to provide access to accelerator information.
6831 *
6832 * @param {string} name Symbolic name of tool
6833 * @return {string|undefined} Tool accelerator label if available
6834 */
6835 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6836 return undefined;
6837 };
6838
6839 /**
6840 * Collection of tools.
6841 *
6842 * Tools can be specified in the following ways:
6843 *
6844 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6845 * - All tools in a group: `{ group: 'group-name' }`
6846 * - All tools: `'*'`
6847 *
6848 * @abstract
6849 * @class
6850 * @extends OO.ui.Widget
6851 * @mixins OO.ui.GroupElement
6852 *
6853 * @constructor
6854 * @param {OO.ui.Toolbar} toolbar
6855 * @param {Object} [config] Configuration options
6856 * @cfg {Array|string} [include=[]] List of tools to include
6857 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6858 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6859 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6860 */
6861 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6862 // Allow passing positional parameters inside the config object
6863 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
6864 config = toolbar;
6865 toolbar = config.toolbar;
6866 }
6867
6868 // Configuration initialization
6869 config = config || {};
6870
6871 // Parent constructor
6872 OO.ui.ToolGroup.super.call( this, config );
6873
6874 // Mixin constructors
6875 OO.ui.GroupElement.call( this, config );
6876
6877 // Properties
6878 this.toolbar = toolbar;
6879 this.tools = {};
6880 this.pressed = null;
6881 this.autoDisabled = false;
6882 this.include = config.include || [];
6883 this.exclude = config.exclude || [];
6884 this.promote = config.promote || [];
6885 this.demote = config.demote || [];
6886 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6887
6888 // Events
6889 this.$element.on( {
6890 mousedown: this.onPointerDown.bind( this ),
6891 mouseup: this.onPointerUp.bind( this ),
6892 mouseover: this.onMouseOver.bind( this ),
6893 mouseout: this.onMouseOut.bind( this )
6894 } );
6895 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6896 this.aggregate( { disable: 'itemDisable' } );
6897 this.connect( this, { itemDisable: 'updateDisabled' } );
6898
6899 // Initialization
6900 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6901 this.$element
6902 .addClass( 'oo-ui-toolGroup' )
6903 .append( this.$group );
6904 this.populate();
6905 };
6906
6907 /* Setup */
6908
6909 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6910 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6911
6912 /* Events */
6913
6914 /**
6915 * @event update
6916 */
6917
6918 /* Static Properties */
6919
6920 /**
6921 * Show labels in tooltips.
6922 *
6923 * @static
6924 * @inheritable
6925 * @property {boolean}
6926 */
6927 OO.ui.ToolGroup.static.titleTooltips = false;
6928
6929 /**
6930 * Show acceleration labels in tooltips.
6931 *
6932 * @static
6933 * @inheritable
6934 * @property {boolean}
6935 */
6936 OO.ui.ToolGroup.static.accelTooltips = false;
6937
6938 /**
6939 * Automatically disable the toolgroup when all tools are disabled
6940 *
6941 * @static
6942 * @inheritable
6943 * @property {boolean}
6944 */
6945 OO.ui.ToolGroup.static.autoDisable = true;
6946
6947 /* Methods */
6948
6949 /**
6950 * @inheritdoc
6951 */
6952 OO.ui.ToolGroup.prototype.isDisabled = function () {
6953 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6954 };
6955
6956 /**
6957 * @inheritdoc
6958 */
6959 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6960 var i, item, allDisabled = true;
6961
6962 if ( this.constructor.static.autoDisable ) {
6963 for ( i = this.items.length - 1; i >= 0; i-- ) {
6964 item = this.items[ i ];
6965 if ( !item.isDisabled() ) {
6966 allDisabled = false;
6967 break;
6968 }
6969 }
6970 this.autoDisabled = allDisabled;
6971 }
6972 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6973 };
6974
6975 /**
6976 * Handle mouse down events.
6977 *
6978 * @param {jQuery.Event} e Mouse down event
6979 */
6980 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6981 if ( !this.isDisabled() && e.which === 1 ) {
6982 this.pressed = this.getTargetTool( e );
6983 if ( this.pressed ) {
6984 this.pressed.setActive( true );
6985 this.getElementDocument().addEventListener(
6986 'mouseup', this.onCapturedMouseUpHandler, true
6987 );
6988 }
6989 }
6990 return false;
6991 };
6992
6993 /**
6994 * Handle captured mouse up events.
6995 *
6996 * @param {Event} e Mouse up event
6997 */
6998 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6999 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
7000 // onPointerUp may be called a second time, depending on where the mouse is when the button is
7001 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
7002 this.onPointerUp( e );
7003 };
7004
7005 /**
7006 * Handle mouse up events.
7007 *
7008 * @param {jQuery.Event} e Mouse up event
7009 */
7010 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
7011 var tool = this.getTargetTool( e );
7012
7013 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
7014 this.pressed.onSelect();
7015 }
7016
7017 this.pressed = null;
7018 return false;
7019 };
7020
7021 /**
7022 * Handle mouse over events.
7023 *
7024 * @param {jQuery.Event} e Mouse over event
7025 */
7026 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
7027 var tool = this.getTargetTool( e );
7028
7029 if ( this.pressed && this.pressed === tool ) {
7030 this.pressed.setActive( true );
7031 }
7032 };
7033
7034 /**
7035 * Handle mouse out events.
7036 *
7037 * @param {jQuery.Event} e Mouse out event
7038 */
7039 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
7040 var tool = this.getTargetTool( e );
7041
7042 if ( this.pressed && this.pressed === tool ) {
7043 this.pressed.setActive( false );
7044 }
7045 };
7046
7047 /**
7048 * Get the closest tool to a jQuery.Event.
7049 *
7050 * Only tool links are considered, which prevents other elements in the tool such as popups from
7051 * triggering tool group interactions.
7052 *
7053 * @private
7054 * @param {jQuery.Event} e
7055 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7056 */
7057 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7058 var tool,
7059 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7060
7061 if ( $item.length ) {
7062 tool = $item.parent().data( 'oo-ui-tool' );
7063 }
7064
7065 return tool && !tool.isDisabled() ? tool : null;
7066 };
7067
7068 /**
7069 * Handle tool registry register events.
7070 *
7071 * If a tool is registered after the group is created, we must repopulate the list to account for:
7072 *
7073 * - a tool being added that may be included
7074 * - a tool already included being overridden
7075 *
7076 * @param {string} name Symbolic name of tool
7077 */
7078 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7079 this.populate();
7080 };
7081
7082 /**
7083 * Get the toolbar this group is in.
7084 *
7085 * @return {OO.ui.Toolbar} Toolbar of group
7086 */
7087 OO.ui.ToolGroup.prototype.getToolbar = function () {
7088 return this.toolbar;
7089 };
7090
7091 /**
7092 * Add and remove tools based on configuration.
7093 */
7094 OO.ui.ToolGroup.prototype.populate = function () {
7095 var i, len, name, tool,
7096 toolFactory = this.toolbar.getToolFactory(),
7097 names = {},
7098 add = [],
7099 remove = [],
7100 list = this.toolbar.getToolFactory().getTools(
7101 this.include, this.exclude, this.promote, this.demote
7102 );
7103
7104 // Build a list of needed tools
7105 for ( i = 0, len = list.length; i < len; i++ ) {
7106 name = list[ i ];
7107 if (
7108 // Tool exists
7109 toolFactory.lookup( name ) &&
7110 // Tool is available or is already in this group
7111 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7112 ) {
7113 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7114 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7115 this.toolbar.tools[ name ] = true;
7116 tool = this.tools[ name ];
7117 if ( !tool ) {
7118 // Auto-initialize tools on first use
7119 this.tools[ name ] = tool = toolFactory.create( name, this );
7120 tool.updateTitle();
7121 }
7122 this.toolbar.reserveTool( tool );
7123 add.push( tool );
7124 names[ name ] = true;
7125 }
7126 }
7127 // Remove tools that are no longer needed
7128 for ( name in this.tools ) {
7129 if ( !names[ name ] ) {
7130 this.tools[ name ].destroy();
7131 this.toolbar.releaseTool( this.tools[ name ] );
7132 remove.push( this.tools[ name ] );
7133 delete this.tools[ name ];
7134 }
7135 }
7136 if ( remove.length ) {
7137 this.removeItems( remove );
7138 }
7139 // Update emptiness state
7140 if ( add.length ) {
7141 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7142 } else {
7143 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7144 }
7145 // Re-add tools (moving existing ones to new locations)
7146 this.addItems( add );
7147 // Disabled state may depend on items
7148 this.updateDisabled();
7149 };
7150
7151 /**
7152 * Destroy tool group.
7153 */
7154 OO.ui.ToolGroup.prototype.destroy = function () {
7155 var name;
7156
7157 this.clearItems();
7158 this.toolbar.getToolFactory().disconnect( this );
7159 for ( name in this.tools ) {
7160 this.toolbar.releaseTool( this.tools[ name ] );
7161 this.tools[ name ].disconnect( this ).destroy();
7162 delete this.tools[ name ];
7163 }
7164 this.$element.remove();
7165 };
7166
7167 /**
7168 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7169 * consists of a header that contains the dialog title, a body with the message, and a footer that
7170 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7171 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7172 *
7173 * There are two basic types of message dialogs, confirmation and alert:
7174 *
7175 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7176 * more details about the consequences.
7177 * - **alert**: the dialog title describes which event occurred and the message provides more information
7178 * about why the event occurred.
7179 *
7180 * The MessageDialog class specifies two actions: ‘accept’, the primary
7181 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7182 * passing along the selected action.
7183 *
7184 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7185 *
7186 * @example
7187 * // Example: Creating and opening a message dialog window.
7188 * var messageDialog = new OO.ui.MessageDialog();
7189 *
7190 * // Create and append a window manager.
7191 * var windowManager = new OO.ui.WindowManager();
7192 * $( 'body' ).append( windowManager.$element );
7193 * windowManager.addWindows( [ messageDialog ] );
7194 * // Open the window.
7195 * windowManager.openWindow( messageDialog, {
7196 * title: 'Basic message dialog',
7197 * message: 'This is the message'
7198 * } );
7199 *
7200 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7201 *
7202 * @class
7203 * @extends OO.ui.Dialog
7204 *
7205 * @constructor
7206 * @param {Object} [config] Configuration options
7207 */
7208 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7209 // Parent constructor
7210 OO.ui.MessageDialog.super.call( this, config );
7211
7212 // Properties
7213 this.verticalActionLayout = null;
7214
7215 // Initialization
7216 this.$element.addClass( 'oo-ui-messageDialog' );
7217 };
7218
7219 /* Inheritance */
7220
7221 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7222
7223 /* Static Properties */
7224
7225 OO.ui.MessageDialog.static.name = 'message';
7226
7227 OO.ui.MessageDialog.static.size = 'small';
7228
7229 OO.ui.MessageDialog.static.verbose = false;
7230
7231 /**
7232 * Dialog title.
7233 *
7234 * The title of a confirmation dialog describes what a progressive action will do. The
7235 * title of an alert dialog describes which event occurred.
7236 *
7237 * @static
7238 * @inheritable
7239 * @property {jQuery|string|Function|null}
7240 */
7241 OO.ui.MessageDialog.static.title = null;
7242
7243 /**
7244 * The message displayed in the dialog body.
7245 *
7246 * A confirmation message describes the consequences of a progressive action. An alert
7247 * message describes why an event occurred.
7248 *
7249 * @static
7250 * @inheritable
7251 * @property {jQuery|string|Function|null}
7252 */
7253 OO.ui.MessageDialog.static.message = null;
7254
7255 OO.ui.MessageDialog.static.actions = [
7256 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7257 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7258 ];
7259
7260 /* Methods */
7261
7262 /**
7263 * @inheritdoc
7264 */
7265 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7266 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7267
7268 // Events
7269 this.manager.connect( this, {
7270 resize: 'onResize'
7271 } );
7272
7273 return this;
7274 };
7275
7276 /**
7277 * @inheritdoc
7278 */
7279 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7280 this.fitActions();
7281 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7282 };
7283
7284 /**
7285 * Handle window resized events.
7286 *
7287 * @private
7288 */
7289 OO.ui.MessageDialog.prototype.onResize = function () {
7290 var dialog = this;
7291 dialog.fitActions();
7292 // Wait for CSS transition to finish and do it again :(
7293 setTimeout( function () {
7294 dialog.fitActions();
7295 }, 300 );
7296 };
7297
7298 /**
7299 * Toggle action layout between vertical and horizontal.
7300 *
7301 *
7302 * @private
7303 * @param {boolean} [value] Layout actions vertically, omit to toggle
7304 * @chainable
7305 */
7306 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7307 value = value === undefined ? !this.verticalActionLayout : !!value;
7308
7309 if ( value !== this.verticalActionLayout ) {
7310 this.verticalActionLayout = value;
7311 this.$actions
7312 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7313 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7314 }
7315
7316 return this;
7317 };
7318
7319 /**
7320 * @inheritdoc
7321 */
7322 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7323 if ( action ) {
7324 return new OO.ui.Process( function () {
7325 this.close( { action: action } );
7326 }, this );
7327 }
7328 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7329 };
7330
7331 /**
7332 * @inheritdoc
7333 *
7334 * @param {Object} [data] Dialog opening data
7335 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7336 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7337 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7338 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7339 * action item
7340 */
7341 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7342 data = data || {};
7343
7344 // Parent method
7345 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7346 .next( function () {
7347 this.title.setLabel(
7348 data.title !== undefined ? data.title : this.constructor.static.title
7349 );
7350 this.message.setLabel(
7351 data.message !== undefined ? data.message : this.constructor.static.message
7352 );
7353 this.message.$element.toggleClass(
7354 'oo-ui-messageDialog-message-verbose',
7355 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7356 );
7357 }, this );
7358 };
7359
7360 /**
7361 * @inheritdoc
7362 */
7363 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7364 var bodyHeight, oldOverflow,
7365 $scrollable = this.container.$element;
7366
7367 oldOverflow = $scrollable[ 0 ].style.overflow;
7368 $scrollable[ 0 ].style.overflow = 'hidden';
7369
7370 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7371
7372 bodyHeight = this.text.$element.outerHeight( true );
7373 $scrollable[ 0 ].style.overflow = oldOverflow;
7374
7375 return bodyHeight;
7376 };
7377
7378 /**
7379 * @inheritdoc
7380 */
7381 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7382 var $scrollable = this.container.$element;
7383 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7384
7385 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7386 // Need to do it after transition completes (250ms), add 50ms just in case.
7387 setTimeout( function () {
7388 var oldOverflow = $scrollable[ 0 ].style.overflow;
7389 $scrollable[ 0 ].style.overflow = 'hidden';
7390
7391 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7392
7393 $scrollable[ 0 ].style.overflow = oldOverflow;
7394 }, 300 );
7395
7396 return this;
7397 };
7398
7399 /**
7400 * @inheritdoc
7401 */
7402 OO.ui.MessageDialog.prototype.initialize = function () {
7403 // Parent method
7404 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7405
7406 // Properties
7407 this.$actions = $( '<div>' );
7408 this.container = new OO.ui.PanelLayout( {
7409 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7410 } );
7411 this.text = new OO.ui.PanelLayout( {
7412 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7413 } );
7414 this.message = new OO.ui.LabelWidget( {
7415 classes: [ 'oo-ui-messageDialog-message' ]
7416 } );
7417
7418 // Initialization
7419 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7420 this.$content.addClass( 'oo-ui-messageDialog-content' );
7421 this.container.$element.append( this.text.$element );
7422 this.text.$element.append( this.title.$element, this.message.$element );
7423 this.$body.append( this.container.$element );
7424 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7425 this.$foot.append( this.$actions );
7426 };
7427
7428 /**
7429 * @inheritdoc
7430 */
7431 OO.ui.MessageDialog.prototype.attachActions = function () {
7432 var i, len, other, special, others;
7433
7434 // Parent method
7435 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7436
7437 special = this.actions.getSpecial();
7438 others = this.actions.getOthers();
7439 if ( special.safe ) {
7440 this.$actions.append( special.safe.$element );
7441 special.safe.toggleFramed( false );
7442 }
7443 if ( others.length ) {
7444 for ( i = 0, len = others.length; i < len; i++ ) {
7445 other = others[ i ];
7446 this.$actions.append( other.$element );
7447 other.toggleFramed( false );
7448 }
7449 }
7450 if ( special.primary ) {
7451 this.$actions.append( special.primary.$element );
7452 special.primary.toggleFramed( false );
7453 }
7454
7455 if ( !this.isOpening() ) {
7456 // If the dialog is currently opening, this will be called automatically soon.
7457 // This also calls #fitActions.
7458 this.updateSize();
7459 }
7460 };
7461
7462 /**
7463 * Fit action actions into columns or rows.
7464 *
7465 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7466 *
7467 * @private
7468 */
7469 OO.ui.MessageDialog.prototype.fitActions = function () {
7470 var i, len, action,
7471 previous = this.verticalActionLayout,
7472 actions = this.actions.get();
7473
7474 // Detect clipping
7475 this.toggleVerticalActionLayout( false );
7476 for ( i = 0, len = actions.length; i < len; i++ ) {
7477 action = actions[ i ];
7478 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7479 this.toggleVerticalActionLayout( true );
7480 break;
7481 }
7482 }
7483
7484 // Move the body out of the way of the foot
7485 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7486
7487 if ( this.verticalActionLayout !== previous ) {
7488 // We changed the layout, window height might need to be updated.
7489 this.updateSize();
7490 }
7491 };
7492
7493 /**
7494 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7495 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7496 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7497 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7498 * required for each process.
7499 *
7500 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7501 * processes with an animation. The header contains the dialog title as well as
7502 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7503 * a ‘primary’ action on the right (e.g., ‘Done’).
7504 *
7505 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7506 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7507 *
7508 * @example
7509 * // Example: Creating and opening a process dialog window.
7510 * function MyProcessDialog( config ) {
7511 * MyProcessDialog.super.call( this, config );
7512 * }
7513 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7514 *
7515 * MyProcessDialog.static.title = 'Process dialog';
7516 * MyProcessDialog.static.actions = [
7517 * { action: 'save', label: 'Done', flags: 'primary' },
7518 * { label: 'Cancel', flags: 'safe' }
7519 * ];
7520 *
7521 * MyProcessDialog.prototype.initialize = function () {
7522 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7523 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7524 * 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>' );
7525 * this.$body.append( this.content.$element );
7526 * };
7527 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7528 * var dialog = this;
7529 * if ( action ) {
7530 * return new OO.ui.Process( function () {
7531 * dialog.close( { action: action } );
7532 * } );
7533 * }
7534 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7535 * };
7536 *
7537 * var windowManager = new OO.ui.WindowManager();
7538 * $( 'body' ).append( windowManager.$element );
7539 *
7540 * var dialog = new MyProcessDialog();
7541 * windowManager.addWindows( [ dialog ] );
7542 * windowManager.openWindow( dialog );
7543 *
7544 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7545 *
7546 * @abstract
7547 * @class
7548 * @extends OO.ui.Dialog
7549 *
7550 * @constructor
7551 * @param {Object} [config] Configuration options
7552 */
7553 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7554 // Parent constructor
7555 OO.ui.ProcessDialog.super.call( this, config );
7556
7557 // Initialization
7558 this.$element.addClass( 'oo-ui-processDialog' );
7559 };
7560
7561 /* Setup */
7562
7563 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7564
7565 /* Methods */
7566
7567 /**
7568 * Handle dismiss button click events.
7569 *
7570 * Hides errors.
7571 *
7572 * @private
7573 */
7574 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7575 this.hideErrors();
7576 };
7577
7578 /**
7579 * Handle retry button click events.
7580 *
7581 * Hides errors and then tries again.
7582 *
7583 * @private
7584 */
7585 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7586 this.hideErrors();
7587 this.executeAction( this.currentAction );
7588 };
7589
7590 /**
7591 * @inheritdoc
7592 */
7593 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7594 if ( this.actions.isSpecial( action ) ) {
7595 this.fitLabel();
7596 }
7597 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7598 };
7599
7600 /**
7601 * @inheritdoc
7602 */
7603 OO.ui.ProcessDialog.prototype.initialize = function () {
7604 // Parent method
7605 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7606
7607 // Properties
7608 this.$navigation = $( '<div>' );
7609 this.$location = $( '<div>' );
7610 this.$safeActions = $( '<div>' );
7611 this.$primaryActions = $( '<div>' );
7612 this.$otherActions = $( '<div>' );
7613 this.dismissButton = new OO.ui.ButtonWidget( {
7614 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7615 } );
7616 this.retryButton = new OO.ui.ButtonWidget();
7617 this.$errors = $( '<div>' );
7618 this.$errorsTitle = $( '<div>' );
7619
7620 // Events
7621 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7622 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7623
7624 // Initialization
7625 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7626 this.$location
7627 .append( this.title.$element )
7628 .addClass( 'oo-ui-processDialog-location' );
7629 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7630 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7631 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7632 this.$errorsTitle
7633 .addClass( 'oo-ui-processDialog-errors-title' )
7634 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7635 this.$errors
7636 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7637 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7638 this.$content
7639 .addClass( 'oo-ui-processDialog-content' )
7640 .append( this.$errors );
7641 this.$navigation
7642 .addClass( 'oo-ui-processDialog-navigation' )
7643 .append( this.$safeActions, this.$location, this.$primaryActions );
7644 this.$head.append( this.$navigation );
7645 this.$foot.append( this.$otherActions );
7646 };
7647
7648 /**
7649 * @inheritdoc
7650 */
7651 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7652 var i, len, widgets = [];
7653 for ( i = 0, len = actions.length; i < len; i++ ) {
7654 widgets.push(
7655 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7656 );
7657 }
7658 return widgets;
7659 };
7660
7661 /**
7662 * @inheritdoc
7663 */
7664 OO.ui.ProcessDialog.prototype.attachActions = function () {
7665 var i, len, other, special, others;
7666
7667 // Parent method
7668 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7669
7670 special = this.actions.getSpecial();
7671 others = this.actions.getOthers();
7672 if ( special.primary ) {
7673 this.$primaryActions.append( special.primary.$element );
7674 }
7675 for ( i = 0, len = others.length; i < len; i++ ) {
7676 other = others[ i ];
7677 this.$otherActions.append( other.$element );
7678 }
7679 if ( special.safe ) {
7680 this.$safeActions.append( special.safe.$element );
7681 }
7682
7683 this.fitLabel();
7684 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7685 };
7686
7687 /**
7688 * @inheritdoc
7689 */
7690 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7691 var process = this;
7692 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7693 .fail( function ( errors ) {
7694 process.showErrors( errors || [] );
7695 } );
7696 };
7697
7698 /**
7699 * Fit label between actions.
7700 *
7701 * @private
7702 * @chainable
7703 */
7704 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7705 var width = Math.max(
7706 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7707 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7708 );
7709 this.$location.css( { paddingLeft: width, paddingRight: width } );
7710
7711 return this;
7712 };
7713
7714 /**
7715 * Handle errors that occurred during accept or reject processes.
7716 *
7717 * @private
7718 * @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
7719 */
7720 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7721 var i, len, $item, actions,
7722 items = [],
7723 abilities = {},
7724 recoverable = true,
7725 warning = false;
7726
7727 if ( errors instanceof OO.ui.Error ) {
7728 errors = [ errors ];
7729 }
7730
7731 for ( i = 0, len = errors.length; i < len; i++ ) {
7732 if ( !errors[ i ].isRecoverable() ) {
7733 recoverable = false;
7734 }
7735 if ( errors[ i ].isWarning() ) {
7736 warning = true;
7737 }
7738 $item = $( '<div>' )
7739 .addClass( 'oo-ui-processDialog-error' )
7740 .append( errors[ i ].getMessage() );
7741 items.push( $item[ 0 ] );
7742 }
7743 this.$errorItems = $( items );
7744 if ( recoverable ) {
7745 abilities[this.currentAction] = true;
7746 // Copy the flags from the first matching action
7747 actions = this.actions.get( { actions: this.currentAction } );
7748 if ( actions.length ) {
7749 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7750 }
7751 } else {
7752 abilities[this.currentAction] = false;
7753 this.actions.setAbilities( abilities );
7754 }
7755 if ( warning ) {
7756 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7757 } else {
7758 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7759 }
7760 this.retryButton.toggle( recoverable );
7761 this.$errorsTitle.after( this.$errorItems );
7762 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7763 };
7764
7765 /**
7766 * Hide errors.
7767 *
7768 * @private
7769 */
7770 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7771 this.$errors.addClass( 'oo-ui-element-hidden' );
7772 if ( this.$errorItems ) {
7773 this.$errorItems.remove();
7774 this.$errorItems = null;
7775 }
7776 };
7777
7778 /**
7779 * @inheritdoc
7780 */
7781 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
7782 // Parent method
7783 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
7784 .first( function () {
7785 // Make sure to hide errors
7786 this.hideErrors();
7787 }, this );
7788 };
7789
7790 /**
7791 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7792 * which is a widget that is specified by reference before any optional configuration settings.
7793 *
7794 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7795 *
7796 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7797 * A left-alignment is used for forms with many fields.
7798 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7799 * A right-alignment is used for long but familiar forms which users tab through,
7800 * verifying the current field with a quick glance at the label.
7801 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7802 * that users fill out from top to bottom.
7803 * - **inline**: The label is placed after the field-widget and aligned to the left.
7804 * An inline-alignment is best used with checkboxes or radio buttons.
7805 *
7806 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7807 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7808 *
7809 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7810 * @class
7811 * @extends OO.ui.Layout
7812 * @mixins OO.ui.LabelElement
7813 *
7814 * @constructor
7815 * @param {OO.ui.Widget} fieldWidget Field widget
7816 * @param {Object} [config] Configuration options
7817 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7818 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7819 * in the upper-right corner of the rendered field.
7820 */
7821 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7822 // Allow passing positional parameters inside the config object
7823 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7824 config = fieldWidget;
7825 fieldWidget = config.fieldWidget;
7826 }
7827
7828 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7829
7830 // Configuration initialization
7831 config = $.extend( { align: 'left' }, config );
7832
7833 // Parent constructor
7834 OO.ui.FieldLayout.super.call( this, config );
7835
7836 // Mixin constructors
7837 OO.ui.LabelElement.call( this, config );
7838
7839 // Properties
7840 this.fieldWidget = fieldWidget;
7841 this.$field = $( '<div>' );
7842 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7843 this.align = null;
7844 if ( config.help ) {
7845 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7846 classes: [ 'oo-ui-fieldLayout-help' ],
7847 framed: false,
7848 icon: 'info'
7849 } );
7850
7851 this.popupButtonWidget.getPopup().$body.append(
7852 $( '<div>' )
7853 .text( config.help )
7854 .addClass( 'oo-ui-fieldLayout-help-content' )
7855 );
7856 this.$help = this.popupButtonWidget.$element;
7857 } else {
7858 this.$help = $( [] );
7859 }
7860
7861 // Events
7862 if ( hasInputWidget ) {
7863 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7864 }
7865 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7866
7867 // Initialization
7868 this.$element
7869 .addClass( 'oo-ui-fieldLayout' )
7870 .append( this.$help, this.$body );
7871 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7872 this.$field
7873 .addClass( 'oo-ui-fieldLayout-field' )
7874 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7875 .append( this.fieldWidget.$element );
7876
7877 this.setAlignment( config.align );
7878 };
7879
7880 /* Setup */
7881
7882 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7883 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7884
7885 /* Methods */
7886
7887 /**
7888 * Handle field disable events.
7889 *
7890 * @private
7891 * @param {boolean} value Field is disabled
7892 */
7893 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7894 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7895 };
7896
7897 /**
7898 * Handle label mouse click events.
7899 *
7900 * @private
7901 * @param {jQuery.Event} e Mouse click event
7902 */
7903 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7904 this.fieldWidget.simulateLabelClick();
7905 return false;
7906 };
7907
7908 /**
7909 * Get the widget contained by the field.
7910 *
7911 * @return {OO.ui.Widget} Field widget
7912 */
7913 OO.ui.FieldLayout.prototype.getField = function () {
7914 return this.fieldWidget;
7915 };
7916
7917 /**
7918 * Set the field alignment mode.
7919 *
7920 * @private
7921 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7922 * @chainable
7923 */
7924 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7925 if ( value !== this.align ) {
7926 // Default to 'left'
7927 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7928 value = 'left';
7929 }
7930 // Reorder elements
7931 if ( value === 'inline' ) {
7932 this.$body.append( this.$field, this.$label );
7933 } else {
7934 this.$body.append( this.$label, this.$field );
7935 }
7936 // Set classes. The following classes can be used here:
7937 // * oo-ui-fieldLayout-align-left
7938 // * oo-ui-fieldLayout-align-right
7939 // * oo-ui-fieldLayout-align-top
7940 // * oo-ui-fieldLayout-align-inline
7941 if ( this.align ) {
7942 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7943 }
7944 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7945 this.align = value;
7946 }
7947
7948 return this;
7949 };
7950
7951 /**
7952 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
7953 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
7954 * is required and is specified before any optional configuration settings.
7955 *
7956 * Labels can be aligned in one of four ways:
7957 *
7958 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7959 * A left-alignment is used for forms with many fields.
7960 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7961 * A right-alignment is used for long but familiar forms which users tab through,
7962 * verifying the current field with a quick glance at the label.
7963 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7964 * that users fill out from top to bottom.
7965 * - **inline**: The label is placed after the field-widget and aligned to the left.
7966 * An inline-alignment is best used with checkboxes or radio buttons.
7967 *
7968 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
7969 * text is specified.
7970 *
7971 * @example
7972 * // Example of an ActionFieldLayout
7973 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
7974 * new OO.ui.TextInputWidget( {
7975 * placeholder: 'Field widget'
7976 * } ),
7977 * new OO.ui.ButtonWidget( {
7978 * label: 'Button'
7979 * } ),
7980 * {
7981 * label: 'An ActionFieldLayout. This label is aligned top',
7982 * align: 'top',
7983 * help: 'This is help text'
7984 * }
7985 * );
7986 *
7987 * $( 'body' ).append( actionFieldLayout.$element );
7988 *
7989 *
7990 * @class
7991 * @extends OO.ui.FieldLayout
7992 *
7993 * @constructor
7994 * @param {OO.ui.Widget} fieldWidget Field widget
7995 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7996 * @param {Object} [config] Configuration options
7997 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7998 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear in the
7999 * upper-right corner of the rendered field.
8000 */
8001 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
8002 // Allow passing positional parameters inside the config object
8003 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
8004 config = fieldWidget;
8005 fieldWidget = config.fieldWidget;
8006 buttonWidget = config.buttonWidget;
8007 }
8008
8009 // Configuration initialization
8010 config = $.extend( { align: 'left' }, config );
8011
8012 // Parent constructor
8013 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
8014
8015 // Properties
8016 this.fieldWidget = fieldWidget;
8017 this.buttonWidget = buttonWidget;
8018 this.$button = $( '<div>' )
8019 .addClass( 'oo-ui-actionFieldLayout-button' )
8020 .append( this.buttonWidget.$element );
8021 this.$input = $( '<div>' )
8022 .addClass( 'oo-ui-actionFieldLayout-input' )
8023 .append( this.fieldWidget.$element );
8024 this.$field
8025 .addClass( 'oo-ui-actionFieldLayout' )
8026 .append( this.$input, this.$button );
8027 };
8028
8029 /* Setup */
8030
8031 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
8032
8033 /**
8034 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
8035 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
8036 * configured with a label as well. For more information and examples,
8037 * please see the [OOjs UI documentation on MediaWiki][1].
8038 *
8039 * @example
8040 * // Example of a fieldset layout
8041 * var input1 = new OO.ui.TextInputWidget( {
8042 * placeholder: 'A text input field'
8043 * } );
8044 *
8045 * var input2 = new OO.ui.TextInputWidget( {
8046 * placeholder: 'A text input field'
8047 * } );
8048 *
8049 * var fieldset = new OO.ui.FieldsetLayout( {
8050 * label: 'Example of a fieldset layout'
8051 * } );
8052 *
8053 * fieldset.addItems( [
8054 * new OO.ui.FieldLayout( input1, {
8055 * label: 'Field One'
8056 * } ),
8057 * new OO.ui.FieldLayout( input2, {
8058 * label: 'Field Two'
8059 * } )
8060 * ] );
8061 * $( 'body' ).append( fieldset.$element );
8062 *
8063 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8064 *
8065 * @class
8066 * @extends OO.ui.Layout
8067 * @mixins OO.ui.IconElement
8068 * @mixins OO.ui.LabelElement
8069 * @mixins OO.ui.GroupElement
8070 *
8071 * @constructor
8072 * @param {Object} [config] Configuration options
8073 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8074 */
8075 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8076 // Configuration initialization
8077 config = config || {};
8078
8079 // Parent constructor
8080 OO.ui.FieldsetLayout.super.call( this, config );
8081
8082 // Mixin constructors
8083 OO.ui.IconElement.call( this, config );
8084 OO.ui.LabelElement.call( this, config );
8085 OO.ui.GroupElement.call( this, config );
8086
8087 if ( config.help ) {
8088 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8089 classes: [ 'oo-ui-fieldsetLayout-help' ],
8090 framed: false,
8091 icon: 'info'
8092 } );
8093
8094 this.popupButtonWidget.getPopup().$body.append(
8095 $( '<div>' )
8096 .text( config.help )
8097 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8098 );
8099 this.$help = this.popupButtonWidget.$element;
8100 } else {
8101 this.$help = $( [] );
8102 }
8103
8104 // Initialization
8105 this.$element
8106 .addClass( 'oo-ui-fieldsetLayout' )
8107 .prepend( this.$help, this.$icon, this.$label, this.$group );
8108 if ( Array.isArray( config.items ) ) {
8109 this.addItems( config.items );
8110 }
8111 };
8112
8113 /* Setup */
8114
8115 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8116 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8117 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8118 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8119
8120 /**
8121 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8122 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8123 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8124 *
8125 * @example
8126 * // Example of a form layout that wraps a fieldset layout
8127 * var input1 = new OO.ui.TextInputWidget( {
8128 * placeholder: 'Username'
8129 * } );
8130 * var input2 = new OO.ui.TextInputWidget( {
8131 * placeholder: 'Password',
8132 * type: 'password'
8133 * } );
8134 * var submit = new OO.ui.ButtonInputWidget( {
8135 * label: 'Submit'
8136 * } );
8137 *
8138 * var fieldset = new OO.ui.FieldsetLayout( {
8139 * label: 'A form layout'
8140 * } );
8141 * fieldset.addItems( [
8142 * new OO.ui.FieldLayout( input1, {
8143 * label: 'Username',
8144 * align: 'top'
8145 * } ),
8146 * new OO.ui.FieldLayout( input2, {
8147 * label: 'Password',
8148 * align: 'top'
8149 * } ),
8150 * new OO.ui.FieldLayout( submit )
8151 * ] );
8152 * var form = new OO.ui.FormLayout( {
8153 * items: [ fieldset ],
8154 * action: '/api/formhandler',
8155 * method: 'get'
8156 * } )
8157 * $( 'body' ).append( form.$element );
8158 *
8159 * @class
8160 * @extends OO.ui.Layout
8161 * @mixins OO.ui.GroupElement
8162 *
8163 * @constructor
8164 * @param {Object} [config] Configuration options
8165 * @cfg {string} [method] HTML form `method` attribute
8166 * @cfg {string} [action] HTML form `action` attribute
8167 * @cfg {string} [enctype] HTML form `enctype` attribute
8168 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8169 */
8170 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8171 // Configuration initialization
8172 config = config || {};
8173
8174 // Parent constructor
8175 OO.ui.FormLayout.super.call( this, config );
8176
8177 // Mixin constructors
8178 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8179
8180 // Events
8181 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8182
8183 // Initialization
8184 this.$element
8185 .addClass( 'oo-ui-formLayout' )
8186 .attr( {
8187 method: config.method,
8188 action: config.action,
8189 enctype: config.enctype
8190 } );
8191 if ( Array.isArray( config.items ) ) {
8192 this.addItems( config.items );
8193 }
8194 };
8195
8196 /* Setup */
8197
8198 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8199 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8200
8201 /* Events */
8202
8203 /**
8204 * A 'submit' event is emitted when the form is submitted.
8205 *
8206 * @event submit
8207 */
8208
8209 /* Static Properties */
8210
8211 OO.ui.FormLayout.static.tagName = 'form';
8212
8213 /* Methods */
8214
8215 /**
8216 * Handle form submit events.
8217 *
8218 * @private
8219 * @param {jQuery.Event} e Submit event
8220 * @fires submit
8221 */
8222 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8223 this.emit( 'submit' );
8224 return false;
8225 };
8226
8227 /**
8228 * Layout with a content and menu area.
8229 *
8230 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8231 * all remaining space.
8232 *
8233 * @class
8234 * @extends OO.ui.Layout
8235 *
8236 * @constructor
8237 * @param {Object} [config] Configuration options
8238 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8239 * @cfg {boolean} [showMenu=true] Show menu
8240 * @cfg {string} [menuPosition='before'] Position of menu: `top`, `after`, `bottom` or `before`
8241 */
8242 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8243 var positions = this.constructor.static.menuPositions;
8244
8245 // Configuration initialization
8246 config = config || {};
8247
8248 // Parent constructor
8249 OO.ui.MenuLayout.super.call( this, config );
8250
8251 // Properties
8252 this.showMenu = config.showMenu !== false;
8253 this.menuSize = config.menuSize || '18em';
8254 this.menuPosition = positions[ config.menuPosition ] || positions.before;
8255
8256 /**
8257 * Menu DOM node
8258 *
8259 * @property {jQuery}
8260 */
8261 this.$menu = $( '<div>' );
8262 /**
8263 * Content DOM node
8264 *
8265 * @property {jQuery}
8266 */
8267 this.$content = $( '<div>' );
8268
8269 // Initialization
8270 this.toggleMenu( this.showMenu );
8271 this.updateSizes();
8272 this.$menu
8273 .addClass( 'oo-ui-menuLayout-menu' )
8274 .css( this.menuPosition.sizeProperty, this.menuSize );
8275 this.$content.addClass( 'oo-ui-menuLayout-content' );
8276 this.$element
8277 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
8278 .append( this.$content, this.$menu );
8279 };
8280
8281 /* Setup */
8282
8283 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8284
8285 /* Static Properties */
8286
8287 OO.ui.MenuLayout.static.menuPositions = {
8288 top: {
8289 sizeProperty: 'height',
8290 className: 'oo-ui-menuLayout-top'
8291 },
8292 after: {
8293 sizeProperty: 'width',
8294 className: 'oo-ui-menuLayout-after'
8295 },
8296 bottom: {
8297 sizeProperty: 'height',
8298 className: 'oo-ui-menuLayout-bottom'
8299 },
8300 before: {
8301 sizeProperty: 'width',
8302 className: 'oo-ui-menuLayout-before'
8303 }
8304 };
8305
8306 /* Methods */
8307
8308 /**
8309 * Toggle menu.
8310 *
8311 * @param {boolean} showMenu Show menu, omit to toggle
8312 * @chainable
8313 */
8314 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8315 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8316
8317 if ( this.showMenu !== showMenu ) {
8318 this.showMenu = showMenu;
8319 this.updateSizes();
8320 }
8321
8322 return this;
8323 };
8324
8325 /**
8326 * Check if menu is visible
8327 *
8328 * @return {boolean} Menu is visible
8329 */
8330 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8331 return this.showMenu;
8332 };
8333
8334 /**
8335 * Set menu size.
8336 *
8337 * @param {number|string} size Size of menu in pixels or any CSS unit
8338 * @chainable
8339 */
8340 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
8341 this.menuSize = size;
8342 this.updateSizes();
8343
8344 return this;
8345 };
8346
8347 /**
8348 * Update menu and content CSS based on current menu size and visibility
8349 *
8350 * This method is called internally when size or position is changed.
8351 */
8352 OO.ui.MenuLayout.prototype.updateSizes = function () {
8353 if ( this.showMenu ) {
8354 this.$menu
8355 .css( this.menuPosition.sizeProperty, this.menuSize )
8356 .css( 'overflow', '' );
8357 // Set offsets on all sides. CSS resets all but one with
8358 // 'important' rules so directionality flips are supported
8359 this.$content.css( {
8360 top: this.menuSize,
8361 right: this.menuSize,
8362 bottom: this.menuSize,
8363 left: this.menuSize
8364 } );
8365 } else {
8366 this.$menu
8367 .css( this.menuPosition.sizeProperty, 0 )
8368 .css( 'overflow', 'hidden' );
8369 this.$content.css( {
8370 top: 0,
8371 right: 0,
8372 bottom: 0,
8373 left: 0
8374 } );
8375 }
8376 };
8377
8378 /**
8379 * Get menu size.
8380 *
8381 * @return {number|string} Menu size
8382 */
8383 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8384 return this.menuSize;
8385 };
8386
8387 /**
8388 * Set menu position.
8389 *
8390 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8391 * @throws {Error} If position value is not supported
8392 * @chainable
8393 */
8394 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8395 var positions = this.constructor.static.menuPositions;
8396
8397 if ( !positions[ position ] ) {
8398 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8399 }
8400
8401 this.$menu.css( this.menuPosition.sizeProperty, '' );
8402 this.$element.removeClass( this.menuPosition.className );
8403
8404 this.menuPosition = positions[ position ];
8405
8406 this.updateSizes();
8407 this.$element.addClass( this.menuPosition.className );
8408
8409 return this;
8410 };
8411
8412 /**
8413 * Get menu position.
8414 *
8415 * @return {string} Menu position
8416 */
8417 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8418 return this.menuPosition;
8419 };
8420
8421 /**
8422 * BookletLayouts contain {@link OO.ui.PageLayout page layouts} as well as
8423 * an {@link OO.ui.OutlineSelectWidget outline} that allows users to easily navigate
8424 * through the pages and select which one to display. By default, only one page is
8425 * displayed at a time and the outline is hidden. When a user navigates to a new page,
8426 * the booklet layout automatically focuses on the first focusable element, unless the
8427 * default setting is changed. Optionally, booklets can be configured to show
8428 * {@link OO.ui.OutlineControlsWidget controls} for adding, moving, and removing items.
8429 *
8430 * @example
8431 * // Example of a BookletLayout that contains two PageLayouts.
8432 *
8433 * function PageOneLayout( name, config ) {
8434 * PageOneLayout.super.call( this, name, config );
8435 * this.$element.append( '<p>First page</p><p>(This booklet has an outline, displayed on the left)</p>' );
8436 * }
8437 * OO.inheritClass( PageOneLayout, OO.ui.PageLayout );
8438 * PageOneLayout.prototype.setupOutlineItem = function () {
8439 * this.outlineItem.setLabel( 'Page One' );
8440 * };
8441 *
8442 * function PageTwoLayout( name, config ) {
8443 * PageTwoLayout.super.call( this, name, config );
8444 * this.$element.append( '<p>Second page</p>' );
8445 * }
8446 * OO.inheritClass( PageTwoLayout, OO.ui.PageLayout );
8447 * PageTwoLayout.prototype.setupOutlineItem = function () {
8448 * this.outlineItem.setLabel( 'Page Two' );
8449 * };
8450 *
8451 * var page1 = new PageOneLayout( 'one' ),
8452 * page2 = new PageTwoLayout( 'two' );
8453 *
8454 * var booklet = new OO.ui.BookletLayout( {
8455 * outlined: true
8456 * } );
8457 *
8458 * booklet.addPages ( [ page1, page2 ] );
8459 * $( 'body' ).append( booklet.$element );
8460 *
8461 * @class
8462 * @extends OO.ui.MenuLayout
8463 *
8464 * @constructor
8465 * @param {Object} [config] Configuration options
8466 * @cfg {boolean} [continuous=false] Show all pages, one after another
8467 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when a new page is displayed.
8468 * @cfg {boolean} [outlined=false] Show the outline. The outline is used to navigate through the pages of the booklet.
8469 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8470 */
8471 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8472 // Configuration initialization
8473 config = config || {};
8474
8475 // Parent constructor
8476 OO.ui.BookletLayout.super.call( this, config );
8477
8478 // Properties
8479 this.currentPageName = null;
8480 this.pages = {};
8481 this.ignoreFocus = false;
8482 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8483 this.$content.append( this.stackLayout.$element );
8484 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8485 this.outlineVisible = false;
8486 this.outlined = !!config.outlined;
8487 if ( this.outlined ) {
8488 this.editable = !!config.editable;
8489 this.outlineControlsWidget = null;
8490 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8491 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8492 this.$menu.append( this.outlinePanel.$element );
8493 this.outlineVisible = true;
8494 if ( this.editable ) {
8495 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8496 this.outlineSelectWidget
8497 );
8498 }
8499 }
8500 this.toggleMenu( this.outlined );
8501
8502 // Events
8503 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8504 if ( this.outlined ) {
8505 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8506 }
8507 if ( this.autoFocus ) {
8508 // Event 'focus' does not bubble, but 'focusin' does
8509 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8510 }
8511
8512 // Initialization
8513 this.$element.addClass( 'oo-ui-bookletLayout' );
8514 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8515 if ( this.outlined ) {
8516 this.outlinePanel.$element
8517 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8518 .append( this.outlineSelectWidget.$element );
8519 if ( this.editable ) {
8520 this.outlinePanel.$element
8521 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8522 .append( this.outlineControlsWidget.$element );
8523 }
8524 }
8525 };
8526
8527 /* Setup */
8528
8529 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8530
8531 /* Events */
8532
8533 /**
8534 * A 'set' event is emitted when a page is {@link #setPage set} to be displayed by the booklet layout.
8535 * @event set
8536 * @param {OO.ui.PageLayout} page Current page
8537 */
8538
8539 /**
8540 * An 'add' event is emitted when pages are {@link #addPages added} to the booklet layout.
8541 *
8542 * @event add
8543 * @param {OO.ui.PageLayout[]} page Added pages
8544 * @param {number} index Index pages were added at
8545 */
8546
8547 /**
8548 * A 'remove' event is emitted when pages are {@link #clearPages cleared} or
8549 * {@link #removePages removed} from the booklet.
8550 *
8551 * @event remove
8552 * @param {OO.ui.PageLayout[]} pages Removed pages
8553 */
8554
8555 /* Methods */
8556
8557 /**
8558 * Handle stack layout focus.
8559 *
8560 * @private
8561 * @param {jQuery.Event} e Focusin event
8562 */
8563 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8564 var name, $target;
8565
8566 // Find the page that an element was focused within
8567 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8568 for ( name in this.pages ) {
8569 // Check for page match, exclude current page to find only page changes
8570 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8571 this.setPage( name );
8572 break;
8573 }
8574 }
8575 };
8576
8577 /**
8578 * Handle stack layout set events.
8579 *
8580 * @private
8581 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8582 */
8583 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8584 var layout = this;
8585 if ( page ) {
8586 page.scrollElementIntoView( { complete: function () {
8587 if ( layout.autoFocus ) {
8588 layout.focus();
8589 }
8590 } } );
8591 }
8592 };
8593
8594 /**
8595 * Focus the first input in the current page.
8596 *
8597 * If no page is selected, the first selectable page will be selected.
8598 * If the focus is already in an element on the current page, nothing will happen.
8599 */
8600 OO.ui.BookletLayout.prototype.focus = function () {
8601 var $input, page = this.stackLayout.getCurrentItem();
8602 if ( !page && this.outlined ) {
8603 this.selectFirstSelectablePage();
8604 page = this.stackLayout.getCurrentItem();
8605 }
8606 if ( !page ) {
8607 return;
8608 }
8609 // Only change the focus if is not already in the current page
8610 if ( !page.$element.find( ':focus' ).length ) {
8611 $input = page.$element.find( ':input:first' );
8612 if ( $input.length ) {
8613 $input[ 0 ].focus();
8614 }
8615 }
8616 };
8617
8618 /**
8619 * Handle outline widget select events.
8620 *
8621 * @private
8622 * @param {OO.ui.OptionWidget|null} item Selected item
8623 */
8624 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8625 if ( item ) {
8626 this.setPage( item.getData() );
8627 }
8628 };
8629
8630 /**
8631 * Check if booklet has an outline.
8632 *
8633 * @return {boolean} Booklet has an outline
8634 */
8635 OO.ui.BookletLayout.prototype.isOutlined = function () {
8636 return this.outlined;
8637 };
8638
8639 /**
8640 * Check if booklet has editing controls.
8641 *
8642 * @return {boolean} Booklet is editable
8643 */
8644 OO.ui.BookletLayout.prototype.isEditable = function () {
8645 return this.editable;
8646 };
8647
8648 /**
8649 * Check if booklet has a visible outline.
8650 *
8651 * @return {boolean} Outline is visible
8652 */
8653 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8654 return this.outlined && this.outlineVisible;
8655 };
8656
8657 /**
8658 * Hide or show the outline.
8659 *
8660 * @param {boolean} [show] Show outline, omit to invert current state
8661 * @chainable
8662 */
8663 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8664 if ( this.outlined ) {
8665 show = show === undefined ? !this.outlineVisible : !!show;
8666 this.outlineVisible = show;
8667 this.toggleMenu( show );
8668 }
8669
8670 return this;
8671 };
8672
8673 /**
8674 * Get the page closest to the specified page.
8675 *
8676 * @param {OO.ui.PageLayout} page Page to use as a reference point
8677 * @return {OO.ui.PageLayout|null} Page closest to the specified page
8678 */
8679 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8680 var next, prev, level,
8681 pages = this.stackLayout.getItems(),
8682 index = $.inArray( page, pages );
8683
8684 if ( index !== -1 ) {
8685 next = pages[ index + 1 ];
8686 prev = pages[ index - 1 ];
8687 // Prefer adjacent pages at the same level
8688 if ( this.outlined ) {
8689 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8690 if (
8691 prev &&
8692 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8693 ) {
8694 return prev;
8695 }
8696 if (
8697 next &&
8698 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8699 ) {
8700 return next;
8701 }
8702 }
8703 }
8704 return prev || next || null;
8705 };
8706
8707 /**
8708 * Get the outline widget.
8709 *
8710 * If the booklet is not outlined, the method will return `null`.
8711 *
8712 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if the booklet is not outlined
8713 */
8714 OO.ui.BookletLayout.prototype.getOutline = function () {
8715 return this.outlineSelectWidget;
8716 };
8717
8718 /**
8719 * Get the outline controls widget.
8720 *
8721 * If the outline is not editable, the method will return `null`.
8722 *
8723 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8724 */
8725 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8726 return this.outlineControlsWidget;
8727 };
8728
8729 /**
8730 * Get a page by its symbolic name.
8731 *
8732 * @param {string} name Symbolic name of page
8733 * @return {OO.ui.PageLayout|undefined} Page, if found
8734 */
8735 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8736 return this.pages[ name ];
8737 };
8738
8739 /**
8740 * Get the current page.
8741 *
8742 * @return {OO.ui.PageLayout|undefined} Current page, if found
8743 */
8744 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8745 var name = this.getCurrentPageName();
8746 return name ? this.getPage( name ) : undefined;
8747 };
8748
8749 /**
8750 * Get the symbolic name of the current page.
8751 *
8752 * @return {string|null} Symbolic name of the current page
8753 */
8754 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8755 return this.currentPageName;
8756 };
8757
8758 /**
8759 * Add pages to the booklet layout
8760 *
8761 * When pages are added with the same names as existing pages, the existing pages will be
8762 * automatically removed before the new pages are added.
8763 *
8764 * @param {OO.ui.PageLayout[]} pages Pages to add
8765 * @param {number} index Index of the insertion point
8766 * @fires add
8767 * @chainable
8768 */
8769 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8770 var i, len, name, page, item, currentIndex,
8771 stackLayoutPages = this.stackLayout.getItems(),
8772 remove = [],
8773 items = [];
8774
8775 // Remove pages with same names
8776 for ( i = 0, len = pages.length; i < len; i++ ) {
8777 page = pages[ i ];
8778 name = page.getName();
8779
8780 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8781 // Correct the insertion index
8782 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8783 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8784 index--;
8785 }
8786 remove.push( this.pages[ name ] );
8787 }
8788 }
8789 if ( remove.length ) {
8790 this.removePages( remove );
8791 }
8792
8793 // Add new pages
8794 for ( i = 0, len = pages.length; i < len; i++ ) {
8795 page = pages[ i ];
8796 name = page.getName();
8797 this.pages[ page.getName() ] = page;
8798 if ( this.outlined ) {
8799 item = new OO.ui.OutlineOptionWidget( { data: name } );
8800 page.setOutlineItem( item );
8801 items.push( item );
8802 }
8803 }
8804
8805 if ( this.outlined && items.length ) {
8806 this.outlineSelectWidget.addItems( items, index );
8807 this.selectFirstSelectablePage();
8808 }
8809 this.stackLayout.addItems( pages, index );
8810 this.emit( 'add', pages, index );
8811
8812 return this;
8813 };
8814
8815 /**
8816 * Remove the specified pages from the booklet layout.
8817 *
8818 * To remove all pages from the booklet, you may wish to use the #clearPages method instead.
8819 *
8820 * @param {OO.ui.PageLayout[]} pages An array of pages to remove
8821 * @fires remove
8822 * @chainable
8823 */
8824 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8825 var i, len, name, page,
8826 items = [];
8827
8828 for ( i = 0, len = pages.length; i < len; i++ ) {
8829 page = pages[ i ];
8830 name = page.getName();
8831 delete this.pages[ name ];
8832 if ( this.outlined ) {
8833 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8834 page.setOutlineItem( null );
8835 }
8836 }
8837 if ( this.outlined && items.length ) {
8838 this.outlineSelectWidget.removeItems( items );
8839 this.selectFirstSelectablePage();
8840 }
8841 this.stackLayout.removeItems( pages );
8842 this.emit( 'remove', pages );
8843
8844 return this;
8845 };
8846
8847 /**
8848 * Clear all pages from the booklet layout.
8849 *
8850 * To remove only a subset of pages from the booklet, use the #removePages method.
8851 *
8852 * @fires remove
8853 * @chainable
8854 */
8855 OO.ui.BookletLayout.prototype.clearPages = function () {
8856 var i, len,
8857 pages = this.stackLayout.getItems();
8858
8859 this.pages = {};
8860 this.currentPageName = null;
8861 if ( this.outlined ) {
8862 this.outlineSelectWidget.clearItems();
8863 for ( i = 0, len = pages.length; i < len; i++ ) {
8864 pages[ i ].setOutlineItem( null );
8865 }
8866 }
8867 this.stackLayout.clearItems();
8868
8869 this.emit( 'remove', pages );
8870
8871 return this;
8872 };
8873
8874 /**
8875 * Set the current page by symbolic name.
8876 *
8877 * @fires set
8878 * @param {string} name Symbolic name of page
8879 */
8880 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8881 var selectedItem,
8882 $focused,
8883 page = this.pages[ name ];
8884
8885 if ( name !== this.currentPageName ) {
8886 if ( this.outlined ) {
8887 selectedItem = this.outlineSelectWidget.getSelectedItem();
8888 if ( selectedItem && selectedItem.getData() !== name ) {
8889 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8890 }
8891 }
8892 if ( page ) {
8893 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8894 this.pages[ this.currentPageName ].setActive( false );
8895 // Blur anything focused if the next page doesn't have anything focusable - this
8896 // is not needed if the next page has something focusable because once it is focused
8897 // this blur happens automatically
8898 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8899 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8900 if ( $focused.length ) {
8901 $focused[ 0 ].blur();
8902 }
8903 }
8904 }
8905 this.currentPageName = name;
8906 this.stackLayout.setItem( page );
8907 page.setActive( true );
8908 this.emit( 'set', page );
8909 }
8910 }
8911 };
8912
8913 /**
8914 * Select the first selectable page.
8915 *
8916 * @chainable
8917 */
8918 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8919 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8920 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8921 }
8922
8923 return this;
8924 };
8925
8926 /**
8927 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8928 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8929 *
8930 * @example
8931 * // Example of a panel layout
8932 * var panel = new OO.ui.PanelLayout( {
8933 * expanded: false,
8934 * framed: true,
8935 * padded: true,
8936 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8937 * } );
8938 * $( 'body' ).append( panel.$element );
8939 *
8940 * @class
8941 * @extends OO.ui.Layout
8942 *
8943 * @constructor
8944 * @param {Object} [config] Configuration options
8945 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8946 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8947 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8948 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8949 */
8950 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8951 // Configuration initialization
8952 config = $.extend( {
8953 scrollable: false,
8954 padded: false,
8955 expanded: true,
8956 framed: false
8957 }, config );
8958
8959 // Parent constructor
8960 OO.ui.PanelLayout.super.call( this, config );
8961
8962 // Initialization
8963 this.$element.addClass( 'oo-ui-panelLayout' );
8964 if ( config.scrollable ) {
8965 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8966 }
8967 if ( config.padded ) {
8968 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8969 }
8970 if ( config.expanded ) {
8971 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8972 }
8973 if ( config.framed ) {
8974 this.$element.addClass( 'oo-ui-panelLayout-framed' );
8975 }
8976 };
8977
8978 /* Setup */
8979
8980 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8981
8982 /**
8983 * PageLayouts are used within {@link OO.ui.BookletLayout booklet layouts} to create pages that users can select and display
8984 * from the booklet's optional {@link OO.ui.OutlineSelectWidget outline} navigation. Pages are usually not instantiated directly,
8985 * rather extended to include the required content and functionality.
8986 *
8987 * Each page must have a unique symbolic name, which is passed to the constructor. In addition, the page's outline
8988 * item is customized (with a label, outline level, etc.) using the #setupOutlineItem method. See
8989 * {@link OO.ui.BookletLayout BookletLayout} for an example.
8990 *
8991 * @class
8992 * @extends OO.ui.PanelLayout
8993 *
8994 * @constructor
8995 * @param {string} name Unique symbolic name of page
8996 * @param {Object} [config] Configuration options
8997 */
8998 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8999 // Allow passing positional parameters inside the config object
9000 if ( OO.isPlainObject( name ) && config === undefined ) {
9001 config = name;
9002 name = config.name;
9003 }
9004
9005 // Configuration initialization
9006 config = $.extend( { scrollable: true }, config );
9007
9008 // Parent constructor
9009 OO.ui.PageLayout.super.call( this, config );
9010
9011 // Properties
9012 this.name = name;
9013 this.outlineItem = null;
9014 this.active = false;
9015
9016 // Initialization
9017 this.$element.addClass( 'oo-ui-pageLayout' );
9018 };
9019
9020 /* Setup */
9021
9022 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
9023
9024 /* Events */
9025
9026 /**
9027 * An 'active' event is emitted when the page becomes active. Pages become active when they are
9028 * shown in a booklet layout that is configured to display only one page at a time.
9029 *
9030 * @event active
9031 * @param {boolean} active Page is active
9032 */
9033
9034 /* Methods */
9035
9036 /**
9037 * Get the symbolic name of the page.
9038 *
9039 * @return {string} Symbolic name of page
9040 */
9041 OO.ui.PageLayout.prototype.getName = function () {
9042 return this.name;
9043 };
9044
9045 /**
9046 * Check if page is active.
9047 *
9048 * Pages become active when they are shown in a {@link OO.ui.BookletLayout booklet layout} that is configured to display
9049 * only one page at a time. Additional CSS is applied to the page's outline item to reflect the active state.
9050 *
9051 * @return {boolean} Page is active
9052 */
9053 OO.ui.PageLayout.prototype.isActive = function () {
9054 return this.active;
9055 };
9056
9057 /**
9058 * Get outline item.
9059 *
9060 * The outline item allows users to access the page from the booklet's outline
9061 * navigation. The outline item itself can be customized (with a label, level, etc.) using the #setupOutlineItem method.
9062 *
9063 * @return {OO.ui.OutlineOptionWidget|null} Outline option widget
9064 */
9065 OO.ui.PageLayout.prototype.getOutlineItem = function () {
9066 return this.outlineItem;
9067 };
9068
9069 /**
9070 * Set or unset the outline item.
9071 *
9072 * Specify an {@link OO.ui.OutlineOptionWidget outline option} to set it,
9073 * or `null` to clear the outline item. To customize the outline item itself (e.g., to set a label or outline
9074 * level), use #setupOutlineItem instead of this method.
9075 *
9076 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline option widget, null to clear
9077 * @chainable
9078 */
9079 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
9080 this.outlineItem = outlineItem || null;
9081 if ( outlineItem ) {
9082 this.setupOutlineItem();
9083 }
9084 return this;
9085 };
9086
9087 /**
9088 * Set up the outline item.
9089 *
9090 * Use this method to customize the outline item (e.g., to add a label or outline level). To set or unset
9091 * the outline item itself (with an {@link OO.ui.OutlineOptionWidget outline option} or `null`), use
9092 * the #setOutlineItem method instead.
9093 *
9094 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline option widget to set up
9095 * @chainable
9096 */
9097 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
9098 return this;
9099 };
9100
9101 /**
9102 * Set the page to its 'active' state.
9103 *
9104 * Pages become active when they are shown in a booklet layout that is configured to display only one page at a time. Additional
9105 * CSS is applied to the outline item to reflect the page's active state. Outside of the booklet
9106 * context, setting the active state on a page does nothing.
9107 *
9108 * @param {boolean} value Page is active
9109 * @fires active
9110 */
9111 OO.ui.PageLayout.prototype.setActive = function ( active ) {
9112 active = !!active;
9113
9114 if ( active !== this.active ) {
9115 this.active = active;
9116 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
9117 this.emit( 'active', this.active );
9118 }
9119 };
9120
9121 /**
9122 * StackLayouts contain a series of {@link OO.ui.PanelLayout panel layouts}. By default, only one panel is displayed
9123 * at a time, though the stack layout can also be configured to show all contained panels, one after another,
9124 * by setting the #continuous option to 'true'.
9125 *
9126 * @example
9127 * // A stack layout with two panels, configured to be displayed continously
9128 * var myStack = new OO.ui.StackLayout( {
9129 * items: [
9130 * new OO.ui.PanelLayout( {
9131 * $content: $( '<p>Panel One</p>' ),
9132 * padded: true,
9133 * framed: true
9134 * } ),
9135 * new OO.ui.PanelLayout( {
9136 * $content: $( '<p>Panel Two</p>' ),
9137 * padded: true,
9138 * framed: true
9139 * } )
9140 * ],
9141 * continuous: true
9142 * } );
9143 * $( 'body' ).append( myStack.$element );
9144 *
9145 * @class
9146 * @extends OO.ui.PanelLayout
9147 * @mixins OO.ui.GroupElement
9148 *
9149 * @constructor
9150 * @param {Object} [config] Configuration options
9151 * @cfg {boolean} [continuous=false] Show all panels, one after another. By default, only one panel is displayed at a time.
9152 * @cfg {OO.ui.Layout[]} [items] Panel layouts to add to the stack layout.
9153 */
9154 OO.ui.StackLayout = function OoUiStackLayout( config ) {
9155 // Configuration initialization
9156 config = $.extend( { scrollable: true }, config );
9157
9158 // Parent constructor
9159 OO.ui.StackLayout.super.call( this, config );
9160
9161 // Mixin constructors
9162 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9163
9164 // Properties
9165 this.currentItem = null;
9166 this.continuous = !!config.continuous;
9167
9168 // Initialization
9169 this.$element.addClass( 'oo-ui-stackLayout' );
9170 if ( this.continuous ) {
9171 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
9172 }
9173 if ( Array.isArray( config.items ) ) {
9174 this.addItems( config.items );
9175 }
9176 };
9177
9178 /* Setup */
9179
9180 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
9181 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
9182
9183 /* Events */
9184
9185 /**
9186 * A 'set' event is emitted when panels are {@link #addItems added}, {@link #removeItems removed},
9187 * {@link #clearItems cleared} or {@link #setItem displayed}.
9188 *
9189 * @event set
9190 * @param {OO.ui.Layout|null} item Current panel or `null` if no panel is shown
9191 */
9192
9193 /* Methods */
9194
9195 /**
9196 * Get the current panel.
9197 *
9198 * @return {OO.ui.Layout|null}
9199 */
9200 OO.ui.StackLayout.prototype.getCurrentItem = function () {
9201 return this.currentItem;
9202 };
9203
9204 /**
9205 * Unset the current item.
9206 *
9207 * @private
9208 * @param {OO.ui.StackLayout} layout
9209 * @fires set
9210 */
9211 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
9212 var prevItem = this.currentItem;
9213 if ( prevItem === null ) {
9214 return;
9215 }
9216
9217 this.currentItem = null;
9218 this.emit( 'set', null );
9219 };
9220
9221 /**
9222 * Add panel layouts to the stack layout.
9223 *
9224 * Panels will be added to the end of the stack layout array unless the optional index parameter specifies a different
9225 * insertion point. Adding a panel that is already in the stack will move it to the end of the array or the point specified
9226 * by the index.
9227 *
9228 * @param {OO.ui.Layout[]} items Panels to add
9229 * @param {number} [index] Index of the insertion point
9230 * @chainable
9231 */
9232 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
9233 // Update the visibility
9234 this.updateHiddenState( items, this.currentItem );
9235
9236 // Mixin method
9237 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
9238
9239 if ( !this.currentItem && items.length ) {
9240 this.setItem( items[ 0 ] );
9241 }
9242
9243 return this;
9244 };
9245
9246 /**
9247 * Remove the specified panels from the stack layout.
9248 *
9249 * Removed panels are detached from the DOM, not removed, so that they may be reused. To remove all panels,
9250 * you may wish to use the #clearItems method instead.
9251 *
9252 * @param {OO.ui.Layout[]} items Panels to remove
9253 * @chainable
9254 * @fires set
9255 */
9256 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
9257 // Mixin method
9258 OO.ui.GroupElement.prototype.removeItems.call( this, items );
9259
9260 if ( $.inArray( this.currentItem, items ) !== -1 ) {
9261 if ( this.items.length ) {
9262 this.setItem( this.items[ 0 ] );
9263 } else {
9264 this.unsetCurrentItem();
9265 }
9266 }
9267
9268 return this;
9269 };
9270
9271 /**
9272 * Clear all panels from the stack layout.
9273 *
9274 * Cleared panels are detached from the DOM, not removed, so that they may be reused. To remove only
9275 * a subset of panels, use the #removeItems method.
9276 *
9277 * @chainable
9278 * @fires set
9279 */
9280 OO.ui.StackLayout.prototype.clearItems = function () {
9281 this.unsetCurrentItem();
9282 OO.ui.GroupElement.prototype.clearItems.call( this );
9283
9284 return this;
9285 };
9286
9287 /**
9288 * Show the specified panel.
9289 *
9290 * If another panel is currently displayed, it will be hidden.
9291 *
9292 * @param {OO.ui.Layout} item Panel to show
9293 * @chainable
9294 * @fires set
9295 */
9296 OO.ui.StackLayout.prototype.setItem = function ( item ) {
9297 if ( item !== this.currentItem ) {
9298 this.updateHiddenState( this.items, item );
9299
9300 if ( $.inArray( item, this.items ) !== -1 ) {
9301 this.currentItem = item;
9302 this.emit( 'set', item );
9303 } else {
9304 this.unsetCurrentItem();
9305 }
9306 }
9307
9308 return this;
9309 };
9310
9311 /**
9312 * Update the visibility of all items in case of non-continuous view.
9313 *
9314 * Ensure all items are hidden except for the selected one.
9315 * This method does nothing when the stack is continuous.
9316 *
9317 * @private
9318 * @param {OO.ui.Layout[]} items Item list iterate over
9319 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9320 */
9321 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
9322 var i, len;
9323
9324 if ( !this.continuous ) {
9325 for ( i = 0, len = items.length; i < len; i++ ) {
9326 if ( !selectedItem || selectedItem !== items[ i ] ) {
9327 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
9328 }
9329 }
9330 if ( selectedItem ) {
9331 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
9332 }
9333 }
9334 };
9335
9336 /**
9337 * Horizontal bar layout of tools as icon buttons.
9338 *
9339 * @class
9340 * @extends OO.ui.ToolGroup
9341 *
9342 * @constructor
9343 * @param {OO.ui.Toolbar} toolbar
9344 * @param {Object} [config] Configuration options
9345 */
9346 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
9347 // Allow passing positional parameters inside the config object
9348 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9349 config = toolbar;
9350 toolbar = config.toolbar;
9351 }
9352
9353 // Parent constructor
9354 OO.ui.BarToolGroup.super.call( this, toolbar, config );
9355
9356 // Initialization
9357 this.$element.addClass( 'oo-ui-barToolGroup' );
9358 };
9359
9360 /* Setup */
9361
9362 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
9363
9364 /* Static Properties */
9365
9366 OO.ui.BarToolGroup.static.titleTooltips = true;
9367
9368 OO.ui.BarToolGroup.static.accelTooltips = true;
9369
9370 OO.ui.BarToolGroup.static.name = 'bar';
9371
9372 /**
9373 * Popup list of tools with an icon and optional label.
9374 *
9375 * @abstract
9376 * @class
9377 * @extends OO.ui.ToolGroup
9378 * @mixins OO.ui.IconElement
9379 * @mixins OO.ui.IndicatorElement
9380 * @mixins OO.ui.LabelElement
9381 * @mixins OO.ui.TitledElement
9382 * @mixins OO.ui.ClippableElement
9383 *
9384 * @constructor
9385 * @param {OO.ui.Toolbar} toolbar
9386 * @param {Object} [config] Configuration options
9387 * @cfg {string} [header] Text to display at the top of the pop-up
9388 */
9389 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
9390 // Allow passing positional parameters inside the config object
9391 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9392 config = toolbar;
9393 toolbar = config.toolbar;
9394 }
9395
9396 // Configuration initialization
9397 config = config || {};
9398
9399 // Parent constructor
9400 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
9401
9402 // Mixin constructors
9403 OO.ui.IconElement.call( this, config );
9404 OO.ui.IndicatorElement.call( this, config );
9405 OO.ui.LabelElement.call( this, config );
9406 OO.ui.TitledElement.call( this, config );
9407 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
9408
9409 // Properties
9410 this.active = false;
9411 this.dragging = false;
9412 this.onBlurHandler = this.onBlur.bind( this );
9413 this.$handle = $( '<span>' );
9414
9415 // Events
9416 this.$handle.on( {
9417 mousedown: this.onHandlePointerDown.bind( this ),
9418 mouseup: this.onHandlePointerUp.bind( this )
9419 } );
9420
9421 // Initialization
9422 this.$handle
9423 .addClass( 'oo-ui-popupToolGroup-handle' )
9424 .append( this.$icon, this.$label, this.$indicator );
9425 // If the pop-up should have a header, add it to the top of the toolGroup.
9426 // Note: If this feature is useful for other widgets, we could abstract it into an
9427 // OO.ui.HeaderedElement mixin constructor.
9428 if ( config.header !== undefined ) {
9429 this.$group
9430 .prepend( $( '<span>' )
9431 .addClass( 'oo-ui-popupToolGroup-header' )
9432 .text( config.header )
9433 );
9434 }
9435 this.$element
9436 .addClass( 'oo-ui-popupToolGroup' )
9437 .prepend( this.$handle );
9438 };
9439
9440 /* Setup */
9441
9442 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
9443 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
9444 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
9445 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
9446 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
9447 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
9448
9449 /* Static Properties */
9450
9451 /* Methods */
9452
9453 /**
9454 * @inheritdoc
9455 */
9456 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
9457 // Parent method
9458 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
9459
9460 if ( this.isDisabled() && this.isElementAttached() ) {
9461 this.setActive( false );
9462 }
9463 };
9464
9465 /**
9466 * Handle focus being lost.
9467 *
9468 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9469 *
9470 * @param {jQuery.Event} e Mouse up event
9471 */
9472 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
9473 // Only deactivate when clicking outside the dropdown element
9474 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
9475 this.setActive( false );
9476 }
9477 };
9478
9479 /**
9480 * @inheritdoc
9481 */
9482 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
9483 // Only close toolgroup when a tool was actually selected
9484 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9485 this.setActive( false );
9486 }
9487 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9488 };
9489
9490 /**
9491 * Handle mouse up events.
9492 *
9493 * @param {jQuery.Event} e Mouse up event
9494 */
9495 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9496 return false;
9497 };
9498
9499 /**
9500 * Handle mouse down events.
9501 *
9502 * @param {jQuery.Event} e Mouse down event
9503 */
9504 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9505 if ( !this.isDisabled() && e.which === 1 ) {
9506 this.setActive( !this.active );
9507 }
9508 return false;
9509 };
9510
9511 /**
9512 * Switch into active mode.
9513 *
9514 * When active, mouseup events anywhere in the document will trigger deactivation.
9515 */
9516 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9517 value = !!value;
9518 if ( this.active !== value ) {
9519 this.active = value;
9520 if ( value ) {
9521 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9522
9523 // Try anchoring the popup to the left first
9524 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9525 this.toggleClipping( true );
9526 if ( this.isClippedHorizontally() ) {
9527 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9528 this.toggleClipping( false );
9529 this.$element
9530 .removeClass( 'oo-ui-popupToolGroup-left' )
9531 .addClass( 'oo-ui-popupToolGroup-right' );
9532 this.toggleClipping( true );
9533 }
9534 } else {
9535 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9536 this.$element.removeClass(
9537 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9538 );
9539 this.toggleClipping( false );
9540 }
9541 }
9542 };
9543
9544 /**
9545 * Drop down list layout of tools as labeled icon buttons.
9546 *
9547 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9548 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9549 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9550 *
9551 * @class
9552 * @extends OO.ui.PopupToolGroup
9553 *
9554 * @constructor
9555 * @param {OO.ui.Toolbar} toolbar
9556 * @param {Object} [config] Configuration options
9557 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9558 * shown.
9559 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9560 * allowed to be collapsed.
9561 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9562 */
9563 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9564 // Allow passing positional parameters inside the config object
9565 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9566 config = toolbar;
9567 toolbar = config.toolbar;
9568 }
9569
9570 // Configuration initialization
9571 config = config || {};
9572
9573 // Properties (must be set before parent constructor, which calls #populate)
9574 this.allowCollapse = config.allowCollapse;
9575 this.forceExpand = config.forceExpand;
9576 this.expanded = config.expanded !== undefined ? config.expanded : false;
9577 this.collapsibleTools = [];
9578
9579 // Parent constructor
9580 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9581
9582 // Initialization
9583 this.$element.addClass( 'oo-ui-listToolGroup' );
9584 };
9585
9586 /* Setup */
9587
9588 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9589
9590 /* Static Properties */
9591
9592 OO.ui.ListToolGroup.static.accelTooltips = true;
9593
9594 OO.ui.ListToolGroup.static.name = 'list';
9595
9596 /* Methods */
9597
9598 /**
9599 * @inheritdoc
9600 */
9601 OO.ui.ListToolGroup.prototype.populate = function () {
9602 var i, len, allowCollapse = [];
9603
9604 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9605
9606 // Update the list of collapsible tools
9607 if ( this.allowCollapse !== undefined ) {
9608 allowCollapse = this.allowCollapse;
9609 } else if ( this.forceExpand !== undefined ) {
9610 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9611 }
9612
9613 this.collapsibleTools = [];
9614 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9615 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9616 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9617 }
9618 }
9619
9620 // Keep at the end, even when tools are added
9621 this.$group.append( this.getExpandCollapseTool().$element );
9622
9623 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9624 this.updateCollapsibleState();
9625 };
9626
9627 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9628 if ( this.expandCollapseTool === undefined ) {
9629 var ExpandCollapseTool = function () {
9630 ExpandCollapseTool.super.apply( this, arguments );
9631 };
9632
9633 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9634
9635 ExpandCollapseTool.prototype.onSelect = function () {
9636 this.toolGroup.expanded = !this.toolGroup.expanded;
9637 this.toolGroup.updateCollapsibleState();
9638 this.setActive( false );
9639 };
9640 ExpandCollapseTool.prototype.onUpdateState = function () {
9641 // Do nothing. Tool interface requires an implementation of this function.
9642 };
9643
9644 ExpandCollapseTool.static.name = 'more-fewer';
9645
9646 this.expandCollapseTool = new ExpandCollapseTool( this );
9647 }
9648 return this.expandCollapseTool;
9649 };
9650
9651 /**
9652 * @inheritdoc
9653 */
9654 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9655 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9656
9657 // Do not close the popup when the user wants to show more/fewer tools
9658 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9659 // Prevent the popup list from being hidden
9660 this.setActive( true );
9661 }
9662
9663 return ret;
9664 };
9665
9666 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9667 var i, len;
9668
9669 this.getExpandCollapseTool()
9670 .setIcon( this.expanded ? 'collapse' : 'expand' )
9671 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9672
9673 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9674 this.collapsibleTools[ i ].toggle( this.expanded );
9675 }
9676 };
9677
9678 /**
9679 * Drop down menu layout of tools as selectable menu items.
9680 *
9681 * @class
9682 * @extends OO.ui.PopupToolGroup
9683 *
9684 * @constructor
9685 * @param {OO.ui.Toolbar} toolbar
9686 * @param {Object} [config] Configuration options
9687 */
9688 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9689 // Allow passing positional parameters inside the config object
9690 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9691 config = toolbar;
9692 toolbar = config.toolbar;
9693 }
9694
9695 // Configuration initialization
9696 config = config || {};
9697
9698 // Parent constructor
9699 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9700
9701 // Events
9702 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9703
9704 // Initialization
9705 this.$element.addClass( 'oo-ui-menuToolGroup' );
9706 };
9707
9708 /* Setup */
9709
9710 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9711
9712 /* Static Properties */
9713
9714 OO.ui.MenuToolGroup.static.accelTooltips = true;
9715
9716 OO.ui.MenuToolGroup.static.name = 'menu';
9717
9718 /* Methods */
9719
9720 /**
9721 * Handle the toolbar state being updated.
9722 *
9723 * When the state changes, the title of each active item in the menu will be joined together and
9724 * used as a label for the group. The label will be empty if none of the items are active.
9725 */
9726 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9727 var name,
9728 labelTexts = [];
9729
9730 for ( name in this.tools ) {
9731 if ( this.tools[ name ].isActive() ) {
9732 labelTexts.push( this.tools[ name ].getTitle() );
9733 }
9734 }
9735
9736 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9737 };
9738
9739 /**
9740 * Tool that shows a popup when selected.
9741 *
9742 * @abstract
9743 * @class
9744 * @extends OO.ui.Tool
9745 * @mixins OO.ui.PopupElement
9746 *
9747 * @constructor
9748 * @param {OO.ui.ToolGroup} toolGroup
9749 * @param {Object} [config] Configuration options
9750 */
9751 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
9752 // Allow passing positional parameters inside the config object
9753 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9754 config = toolGroup;
9755 toolGroup = config.toolGroup;
9756 }
9757
9758 // Parent constructor
9759 OO.ui.PopupTool.super.call( this, toolGroup, config );
9760
9761 // Mixin constructors
9762 OO.ui.PopupElement.call( this, config );
9763
9764 // Initialization
9765 this.$element
9766 .addClass( 'oo-ui-popupTool' )
9767 .append( this.popup.$element );
9768 };
9769
9770 /* Setup */
9771
9772 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9773 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9774
9775 /* Methods */
9776
9777 /**
9778 * Handle the tool being selected.
9779 *
9780 * @inheritdoc
9781 */
9782 OO.ui.PopupTool.prototype.onSelect = function () {
9783 if ( !this.isDisabled() ) {
9784 this.popup.toggle();
9785 }
9786 this.setActive( false );
9787 return false;
9788 };
9789
9790 /**
9791 * Handle the toolbar state being updated.
9792 *
9793 * @inheritdoc
9794 */
9795 OO.ui.PopupTool.prototype.onUpdateState = function () {
9796 this.setActive( false );
9797 };
9798
9799 /**
9800 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9801 * menus in toolbars (T74159).
9802 *
9803 * @abstract
9804 * @class
9805 * @extends OO.ui.Tool
9806 *
9807 * @constructor
9808 * @param {OO.ui.ToolGroup} toolGroup
9809 * @param {Object} [config] Configuration options
9810 */
9811 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
9812 // Allow passing positional parameters inside the config object
9813 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9814 config = toolGroup;
9815 toolGroup = config.toolGroup;
9816 }
9817
9818 // Parent constructor
9819 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
9820
9821 // Properties
9822 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
9823
9824 // Initialization
9825 this.$link.remove();
9826 this.$element
9827 .addClass( 'oo-ui-toolGroupTool' )
9828 .append( this.innerToolGroup.$element );
9829 };
9830
9831 /* Setup */
9832
9833 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
9834
9835 /* Static Properties */
9836
9837 /**
9838 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9839 *
9840 * @property {Object.<string,Array>}
9841 */
9842 OO.ui.ToolGroupTool.static.groupConfig = {};
9843
9844 /* Methods */
9845
9846 /**
9847 * Handle the tool being selected.
9848 *
9849 * @inheritdoc
9850 */
9851 OO.ui.ToolGroupTool.prototype.onSelect = function () {
9852 this.innerToolGroup.setActive( !this.innerToolGroup.active );
9853 return false;
9854 };
9855
9856 /**
9857 * Handle the toolbar state being updated.
9858 *
9859 * @inheritdoc
9860 */
9861 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
9862 this.setActive( false );
9863 };
9864
9865 /**
9866 * Build a OO.ui.ToolGroup from the configuration.
9867 *
9868 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9869 * accepted values.
9870 * @return {OO.ui.ListToolGroup}
9871 */
9872 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
9873 if ( group.include === '*' ) {
9874 // Apply defaults to catch-all groups
9875 if ( group.label === undefined ) {
9876 group.label = OO.ui.msg( 'ooui-toolbar-more' );
9877 }
9878 }
9879
9880 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
9881 };
9882
9883 /**
9884 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9885 *
9886 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9887 *
9888 * @private
9889 * @abstract
9890 * @class
9891 * @extends OO.ui.GroupElement
9892 *
9893 * @constructor
9894 * @param {Object} [config] Configuration options
9895 */
9896 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9897 // Parent constructor
9898 OO.ui.GroupWidget.super.call( this, config );
9899 };
9900
9901 /* Setup */
9902
9903 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9904
9905 /* Methods */
9906
9907 /**
9908 * Set the disabled state of the widget.
9909 *
9910 * This will also update the disabled state of child widgets.
9911 *
9912 * @param {boolean} disabled Disable widget
9913 * @chainable
9914 */
9915 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9916 var i, len;
9917
9918 // Parent method
9919 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9920 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9921
9922 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9923 if ( this.items ) {
9924 for ( i = 0, len = this.items.length; i < len; i++ ) {
9925 this.items[ i ].updateDisabled();
9926 }
9927 }
9928
9929 return this;
9930 };
9931
9932 /**
9933 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9934 *
9935 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9936 * allows bidirectional communication.
9937 *
9938 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9939 *
9940 * @private
9941 * @abstract
9942 * @class
9943 *
9944 * @constructor
9945 */
9946 OO.ui.ItemWidget = function OoUiItemWidget() {
9947 //
9948 };
9949
9950 /* Methods */
9951
9952 /**
9953 * Check if widget is disabled.
9954 *
9955 * Checks parent if present, making disabled state inheritable.
9956 *
9957 * @return {boolean} Widget is disabled
9958 */
9959 OO.ui.ItemWidget.prototype.isDisabled = function () {
9960 return this.disabled ||
9961 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9962 };
9963
9964 /**
9965 * Set group element is in.
9966 *
9967 * @param {OO.ui.GroupElement|null} group Group element, null if none
9968 * @chainable
9969 */
9970 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9971 // Parent method
9972 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9973 OO.ui.Element.prototype.setElementGroup.call( this, group );
9974
9975 // Initialize item disabled states
9976 this.updateDisabled();
9977
9978 return this;
9979 };
9980
9981 /**
9982 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9983 * Controls include moving items up and down, removing items, and adding different kinds of items.
9984 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9985 *
9986 * @class
9987 * @extends OO.ui.Widget
9988 * @mixins OO.ui.GroupElement
9989 * @mixins OO.ui.IconElement
9990 *
9991 * @constructor
9992 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9993 * @param {Object} [config] Configuration options
9994 * @cfg {Object} [abilities] List of abilties
9995 * @cfg {boolean} [abilities.move=true] Allow moving movable items
9996 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
9997 */
9998 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9999 // Allow passing positional parameters inside the config object
10000 if ( OO.isPlainObject( outline ) && config === undefined ) {
10001 config = outline;
10002 outline = config.outline;
10003 }
10004
10005 // Configuration initialization
10006 config = $.extend( { icon: 'add' }, config );
10007
10008 // Parent constructor
10009 OO.ui.OutlineControlsWidget.super.call( this, config );
10010
10011 // Mixin constructors
10012 OO.ui.GroupElement.call( this, config );
10013 OO.ui.IconElement.call( this, config );
10014
10015 // Properties
10016 this.outline = outline;
10017 this.$movers = $( '<div>' );
10018 this.upButton = new OO.ui.ButtonWidget( {
10019 framed: false,
10020 icon: 'collapse',
10021 title: OO.ui.msg( 'ooui-outline-control-move-up' )
10022 } );
10023 this.downButton = new OO.ui.ButtonWidget( {
10024 framed: false,
10025 icon: 'expand',
10026 title: OO.ui.msg( 'ooui-outline-control-move-down' )
10027 } );
10028 this.removeButton = new OO.ui.ButtonWidget( {
10029 framed: false,
10030 icon: 'remove',
10031 title: OO.ui.msg( 'ooui-outline-control-remove' )
10032 } );
10033 this.abilities = { move: true, remove: true };
10034
10035 // Events
10036 outline.connect( this, {
10037 select: 'onOutlineChange',
10038 add: 'onOutlineChange',
10039 remove: 'onOutlineChange'
10040 } );
10041 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
10042 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
10043 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
10044
10045 // Initialization
10046 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
10047 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
10048 this.$movers
10049 .addClass( 'oo-ui-outlineControlsWidget-movers' )
10050 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
10051 this.$element.append( this.$icon, this.$group, this.$movers );
10052 this.setAbilities( config.abilities || {} );
10053 };
10054
10055 /* Setup */
10056
10057 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
10058 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
10059 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
10060
10061 /* Events */
10062
10063 /**
10064 * @event move
10065 * @param {number} places Number of places to move
10066 */
10067
10068 /**
10069 * @event remove
10070 */
10071
10072 /* Methods */
10073
10074 /**
10075 * Set abilities.
10076 *
10077 * @param {Object} abilities List of abilties
10078 * @param {boolean} [abilities.move] Allow moving movable items
10079 * @param {boolean} [abilities.remove] Allow removing removable items
10080 */
10081 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
10082 var ability;
10083
10084 for ( ability in this.abilities ) {
10085 if ( abilities[ability] !== undefined ) {
10086 this.abilities[ability] = !!abilities[ability];
10087 }
10088 }
10089
10090 this.onOutlineChange();
10091 };
10092
10093 /**
10094 *
10095 * @private
10096 * Handle outline change events.
10097 */
10098 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
10099 var i, len, firstMovable, lastMovable,
10100 items = this.outline.getItems(),
10101 selectedItem = this.outline.getSelectedItem(),
10102 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
10103 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
10104
10105 if ( movable ) {
10106 i = -1;
10107 len = items.length;
10108 while ( ++i < len ) {
10109 if ( items[ i ].isMovable() ) {
10110 firstMovable = items[ i ];
10111 break;
10112 }
10113 }
10114 i = len;
10115 while ( i-- ) {
10116 if ( items[ i ].isMovable() ) {
10117 lastMovable = items[ i ];
10118 break;
10119 }
10120 }
10121 }
10122 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
10123 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
10124 this.removeButton.setDisabled( !removable );
10125 };
10126
10127 /**
10128 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
10129 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
10130 *
10131 * @abstract
10132 * @class
10133 *
10134 * @constructor
10135 * @param {Object} [config] Configuration options
10136 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
10137 * By default, the toggle is in the 'off' state.
10138 */
10139 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
10140 // Configuration initialization
10141 config = config || {};
10142
10143 // Properties
10144 this.value = null;
10145
10146 // Initialization
10147 this.$element.addClass( 'oo-ui-toggleWidget' );
10148 this.setValue( !!config.value );
10149 };
10150
10151 /* Events */
10152
10153 /**
10154 * @event change
10155 *
10156 * A change event is emitted when the on/off state of the toggle changes.
10157 *
10158 * @param {boolean} value Value representing the new state of the toggle
10159 */
10160
10161 /* Methods */
10162
10163 /**
10164 * Get the value representing the toggle’s state.
10165 *
10166 * @return {boolean} The on/off state of the toggle
10167 */
10168 OO.ui.ToggleWidget.prototype.getValue = function () {
10169 return this.value;
10170 };
10171
10172 /**
10173 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10174 *
10175 * @param {boolean} value The state of the toggle
10176 * @fires change
10177 * @chainable
10178 */
10179 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
10180 value = !!value;
10181 if ( this.value !== value ) {
10182 this.value = value;
10183 this.emit( 'change', value );
10184 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
10185 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
10186 this.$element.attr( 'aria-checked', value.toString() );
10187 }
10188 return this;
10189 };
10190
10191 /**
10192 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10193 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10194 * removed, and cleared from the group.
10195 *
10196 * @example
10197 * // Example: A ButtonGroupWidget with two buttons
10198 * var button1 = new OO.ui.PopupButtonWidget( {
10199 * label: 'Select a category',
10200 * icon: 'menu',
10201 * popup: {
10202 * $content: $( '<p>List of categories...</p>' ),
10203 * padded: true,
10204 * align: 'left'
10205 * }
10206 * } );
10207 * var button2 = new OO.ui.ButtonWidget( {
10208 * label: 'Add item'
10209 * });
10210 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10211 * items: [button1, button2]
10212 * } );
10213 * $( 'body' ).append( buttonGroup.$element );
10214 *
10215 * @class
10216 * @extends OO.ui.Widget
10217 * @mixins OO.ui.GroupElement
10218 *
10219 * @constructor
10220 * @param {Object} [config] Configuration options
10221 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10222 */
10223 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
10224 // Configuration initialization
10225 config = config || {};
10226
10227 // Parent constructor
10228 OO.ui.ButtonGroupWidget.super.call( this, config );
10229
10230 // Mixin constructors
10231 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10232
10233 // Initialization
10234 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
10235 if ( Array.isArray( config.items ) ) {
10236 this.addItems( config.items );
10237 }
10238 };
10239
10240 /* Setup */
10241
10242 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
10243 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
10244
10245 /**
10246 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10247 * feels, and functionality can be customized via the class’s configuration options
10248 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10249 * and examples.
10250 *
10251 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10252 *
10253 * @example
10254 * // A button widget
10255 * var button = new OO.ui.ButtonWidget( {
10256 * label: 'Button with Icon',
10257 * icon: 'remove',
10258 * iconTitle: 'Remove'
10259 * } );
10260 * $( 'body' ).append( button.$element );
10261 *
10262 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10263 *
10264 * @class
10265 * @extends OO.ui.Widget
10266 * @mixins OO.ui.ButtonElement
10267 * @mixins OO.ui.IconElement
10268 * @mixins OO.ui.IndicatorElement
10269 * @mixins OO.ui.LabelElement
10270 * @mixins OO.ui.TitledElement
10271 * @mixins OO.ui.FlaggedElement
10272 * @mixins OO.ui.TabIndexedElement
10273 *
10274 * @constructor
10275 * @param {Object} [config] Configuration options
10276 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10277 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10278 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10279 */
10280 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
10281 // Configuration initialization
10282 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10283 config = $.extend( { noFollow: config && config.nofollow }, config );
10284
10285 // Parent constructor
10286 OO.ui.ButtonWidget.super.call( this, config );
10287
10288 // Mixin constructors
10289 OO.ui.ButtonElement.call( this, config );
10290 OO.ui.IconElement.call( this, config );
10291 OO.ui.IndicatorElement.call( this, config );
10292 OO.ui.LabelElement.call( this, config );
10293 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10294 OO.ui.FlaggedElement.call( this, config );
10295 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10296
10297 // Properties
10298 this.href = null;
10299 this.target = null;
10300 this.noFollow = false;
10301 this.isHyperlink = false;
10302
10303 // Initialization
10304 this.$button.append( this.$icon, this.$label, this.$indicator );
10305 this.$element
10306 .addClass( 'oo-ui-buttonWidget' )
10307 .append( this.$button );
10308 this.setHref( config.href );
10309 this.setTarget( config.target );
10310 this.setNoFollow( config.noFollow );
10311 };
10312
10313 /* Setup */
10314
10315 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10316 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10317 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10318 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10319 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10320 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10321 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10322 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10323
10324 /* Methods */
10325
10326 /**
10327 * @inheritdoc
10328 */
10329 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10330 if ( !this.isDisabled() ) {
10331 // Remove the tab-index while the button is down to prevent the button from stealing focus
10332 this.$button.removeAttr( 'tabindex' );
10333 }
10334
10335 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10336 };
10337
10338 /**
10339 * @inheritdoc
10340 */
10341 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10342 if ( !this.isDisabled() ) {
10343 // Restore the tab-index after the button is up to restore the button's accessibility
10344 this.$button.attr( 'tabindex', this.tabIndex );
10345 }
10346
10347 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10348 };
10349
10350 /**
10351 * @inheritdoc
10352 */
10353 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10354 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10355 if ( this.isHyperlink ) {
10356 return true;
10357 }
10358 return ret;
10359 };
10360
10361 /**
10362 * @inheritdoc
10363 */
10364 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10365 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10366 if ( this.isHyperlink ) {
10367 return true;
10368 }
10369 return ret;
10370 };
10371
10372 /**
10373 * Get hyperlink location.
10374 *
10375 * @return {string} Hyperlink location
10376 */
10377 OO.ui.ButtonWidget.prototype.getHref = function () {
10378 return this.href;
10379 };
10380
10381 /**
10382 * Get hyperlink target.
10383 *
10384 * @return {string} Hyperlink target
10385 */
10386 OO.ui.ButtonWidget.prototype.getTarget = function () {
10387 return this.target;
10388 };
10389
10390 /**
10391 * Get search engine traversal hint.
10392 *
10393 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10394 */
10395 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10396 return this.noFollow;
10397 };
10398
10399 /**
10400 * Set hyperlink location.
10401 *
10402 * @param {string|null} href Hyperlink location, null to remove
10403 */
10404 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10405 href = typeof href === 'string' ? href : null;
10406
10407 if ( href !== this.href ) {
10408 this.href = href;
10409 if ( href !== null ) {
10410 this.$button.attr( 'href', href );
10411 this.isHyperlink = true;
10412 } else {
10413 this.$button.removeAttr( 'href' );
10414 this.isHyperlink = false;
10415 }
10416 }
10417
10418 return this;
10419 };
10420
10421 /**
10422 * Set hyperlink target.
10423 *
10424 * @param {string|null} target Hyperlink target, null to remove
10425 */
10426 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10427 target = typeof target === 'string' ? target : null;
10428
10429 if ( target !== this.target ) {
10430 this.target = target;
10431 if ( target !== null ) {
10432 this.$button.attr( 'target', target );
10433 } else {
10434 this.$button.removeAttr( 'target' );
10435 }
10436 }
10437
10438 return this;
10439 };
10440
10441 /**
10442 * Set search engine traversal hint.
10443 *
10444 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10445 */
10446 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10447 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10448
10449 if ( noFollow !== this.noFollow ) {
10450 this.noFollow = noFollow;
10451 if ( noFollow ) {
10452 this.$button.attr( 'rel', 'nofollow' );
10453 } else {
10454 this.$button.removeAttr( 'rel' );
10455 }
10456 }
10457
10458 return this;
10459 };
10460
10461 /**
10462 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10463 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10464 * of the actions.
10465 *
10466 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10467 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10468 * and examples.
10469 *
10470 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10471 *
10472 * @class
10473 * @extends OO.ui.ButtonWidget
10474 * @mixins OO.ui.PendingElement
10475 *
10476 * @constructor
10477 * @param {Object} [config] Configuration options
10478 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10479 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10480 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10481 * for more information about setting modes.
10482 * @cfg {boolean} [framed=false] Render the action button with a frame
10483 */
10484 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10485 // Configuration initialization
10486 config = $.extend( { framed: false }, config );
10487
10488 // Parent constructor
10489 OO.ui.ActionWidget.super.call( this, config );
10490
10491 // Mixin constructors
10492 OO.ui.PendingElement.call( this, config );
10493
10494 // Properties
10495 this.action = config.action || '';
10496 this.modes = config.modes || [];
10497 this.width = 0;
10498 this.height = 0;
10499
10500 // Initialization
10501 this.$element.addClass( 'oo-ui-actionWidget' );
10502 };
10503
10504 /* Setup */
10505
10506 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10507 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10508
10509 /* Events */
10510
10511 /**
10512 * A resize event is emitted when the size of the widget changes.
10513 *
10514 * @event resize
10515 */
10516
10517 /* Methods */
10518
10519 /**
10520 * Check if the action is configured to be available in the specified `mode`.
10521 *
10522 * @param {string} mode Name of mode
10523 * @return {boolean} The action is configured with the mode
10524 */
10525 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10526 return this.modes.indexOf( mode ) !== -1;
10527 };
10528
10529 /**
10530 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10531 *
10532 * @return {string}
10533 */
10534 OO.ui.ActionWidget.prototype.getAction = function () {
10535 return this.action;
10536 };
10537
10538 /**
10539 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10540 *
10541 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10542 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10543 * are hidden.
10544 *
10545 * @return {string[]}
10546 */
10547 OO.ui.ActionWidget.prototype.getModes = function () {
10548 return this.modes.slice();
10549 };
10550
10551 /**
10552 * Emit a resize event if the size has changed.
10553 *
10554 * @private
10555 * @chainable
10556 */
10557 OO.ui.ActionWidget.prototype.propagateResize = function () {
10558 var width, height;
10559
10560 if ( this.isElementAttached() ) {
10561 width = this.$element.width();
10562 height = this.$element.height();
10563
10564 if ( width !== this.width || height !== this.height ) {
10565 this.width = width;
10566 this.height = height;
10567 this.emit( 'resize' );
10568 }
10569 }
10570
10571 return this;
10572 };
10573
10574 /**
10575 * @inheritdoc
10576 */
10577 OO.ui.ActionWidget.prototype.setIcon = function () {
10578 // Mixin method
10579 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10580 this.propagateResize();
10581
10582 return this;
10583 };
10584
10585 /**
10586 * @inheritdoc
10587 */
10588 OO.ui.ActionWidget.prototype.setLabel = function () {
10589 // Mixin method
10590 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10591 this.propagateResize();
10592
10593 return this;
10594 };
10595
10596 /**
10597 * @inheritdoc
10598 */
10599 OO.ui.ActionWidget.prototype.setFlags = function () {
10600 // Mixin method
10601 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10602 this.propagateResize();
10603
10604 return this;
10605 };
10606
10607 /**
10608 * @inheritdoc
10609 */
10610 OO.ui.ActionWidget.prototype.clearFlags = function () {
10611 // Mixin method
10612 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10613 this.propagateResize();
10614
10615 return this;
10616 };
10617
10618 /**
10619 * Toggle the visibility of the action button.
10620 *
10621 * @param {boolean} [show] Show button, omit to toggle visibility
10622 * @chainable
10623 */
10624 OO.ui.ActionWidget.prototype.toggle = function () {
10625 // Parent method
10626 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10627 this.propagateResize();
10628
10629 return this;
10630 };
10631
10632 /**
10633 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10634 * which is used to display additional information or options.
10635 *
10636 * @example
10637 * // Example of a popup button.
10638 * var popupButton = new OO.ui.PopupButtonWidget( {
10639 * label: 'Popup button with options',
10640 * icon: 'menu',
10641 * popup: {
10642 * $content: $( '<p>Additional options here.</p>' ),
10643 * padded: true,
10644 * align: 'left'
10645 * }
10646 * } );
10647 * // Append the button to the DOM.
10648 * $( 'body' ).append( popupButton.$element );
10649 *
10650 * @class
10651 * @extends OO.ui.ButtonWidget
10652 * @mixins OO.ui.PopupElement
10653 *
10654 * @constructor
10655 * @param {Object} [config] Configuration options
10656 */
10657 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10658 // Parent constructor
10659 OO.ui.PopupButtonWidget.super.call( this, config );
10660
10661 // Mixin constructors
10662 OO.ui.PopupElement.call( this, config );
10663
10664 // Events
10665 this.connect( this, { click: 'onAction' } );
10666
10667 // Initialization
10668 this.$element
10669 .addClass( 'oo-ui-popupButtonWidget' )
10670 .attr( 'aria-haspopup', 'true' )
10671 .append( this.popup.$element );
10672 };
10673
10674 /* Setup */
10675
10676 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10677 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10678
10679 /* Methods */
10680
10681 /**
10682 * Handle the button action being triggered.
10683 *
10684 * @private
10685 */
10686 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10687 this.popup.toggle();
10688 };
10689
10690 /**
10691 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10692 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10693 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10694 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10695 * and {@link OO.ui.LabelElement labels}. Please see
10696 * the [OOjs UI documentation][1] on MediaWiki for more information.
10697 *
10698 * @example
10699 * // Toggle buttons in the 'off' and 'on' state.
10700 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10701 * label: 'Toggle Button off'
10702 * } );
10703 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10704 * label: 'Toggle Button on',
10705 * value: true
10706 * } );
10707 * // Append the buttons to the DOM.
10708 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10709 *
10710 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10711 *
10712 * @class
10713 * @extends OO.ui.ButtonWidget
10714 * @mixins OO.ui.ToggleWidget
10715 *
10716 * @constructor
10717 * @param {Object} [config] Configuration options
10718 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10719 * state. By default, the button is in the 'off' state.
10720 */
10721 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10722 // Configuration initialization
10723 config = config || {};
10724
10725 // Parent constructor
10726 OO.ui.ToggleButtonWidget.super.call( this, config );
10727
10728 // Mixin constructors
10729 OO.ui.ToggleWidget.call( this, config );
10730
10731 // Events
10732 this.connect( this, { click: 'onAction' } );
10733
10734 // Initialization
10735 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10736 };
10737
10738 /* Setup */
10739
10740 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10741 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10742
10743 /* Methods */
10744
10745 /**
10746 *
10747 * @private
10748 * Handle the button action being triggered.
10749 */
10750 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10751 this.setValue( !this.value );
10752 };
10753
10754 /**
10755 * @inheritdoc
10756 */
10757 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10758 value = !!value;
10759 if ( value !== this.value ) {
10760 this.$button.attr( 'aria-pressed', value.toString() );
10761 this.setActive( value );
10762 }
10763
10764 // Parent method (from mixin)
10765 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10766
10767 return this;
10768 };
10769
10770 /**
10771 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10772 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10773 * users can interact with it.
10774 *
10775 * @example
10776 * // Example: A DropdownWidget with a menu that contains three options
10777 * var dropDown = new OO.ui.DropdownWidget( {
10778 * label: 'Dropdown menu: Select a menu option',
10779 * menu: {
10780 * items: [
10781 * new OO.ui.MenuOptionWidget( {
10782 * data: 'a',
10783 * label: 'First'
10784 * } ),
10785 * new OO.ui.MenuOptionWidget( {
10786 * data: 'b',
10787 * label: 'Second'
10788 * } ),
10789 * new OO.ui.MenuOptionWidget( {
10790 * data: 'c',
10791 * label: 'Third'
10792 * } )
10793 * ]
10794 * }
10795 * } );
10796 *
10797 * $( 'body' ).append( dropDown.$element );
10798 *
10799 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10800 *
10801 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10802 *
10803 * @class
10804 * @extends OO.ui.Widget
10805 * @mixins OO.ui.IconElement
10806 * @mixins OO.ui.IndicatorElement
10807 * @mixins OO.ui.LabelElement
10808 * @mixins OO.ui.TitledElement
10809 * @mixins OO.ui.TabIndexedElement
10810 *
10811 * @constructor
10812 * @param {Object} [config] Configuration options
10813 * @cfg {Object} [menu] Configuration options to pass to menu widget
10814 */
10815 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10816 // Configuration initialization
10817 config = $.extend( { indicator: 'down' }, config );
10818
10819 // Parent constructor
10820 OO.ui.DropdownWidget.super.call( this, config );
10821
10822 // Properties (must be set before TabIndexedElement constructor call)
10823 this.$handle = this.$( '<span>' );
10824
10825 // Mixin constructors
10826 OO.ui.IconElement.call( this, config );
10827 OO.ui.IndicatorElement.call( this, config );
10828 OO.ui.LabelElement.call( this, config );
10829 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10830 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10831
10832 // Properties
10833 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
10834
10835 // Events
10836 this.$handle.on( {
10837 click: this.onClick.bind( this ),
10838 keypress: this.onKeyPress.bind( this )
10839 } );
10840 this.menu.connect( this, { select: 'onMenuSelect' } );
10841
10842 // Initialization
10843 this.$handle
10844 .addClass( 'oo-ui-dropdownWidget-handle' )
10845 .append( this.$icon, this.$label, this.$indicator );
10846 this.$element
10847 .addClass( 'oo-ui-dropdownWidget' )
10848 .append( this.$handle, this.menu.$element );
10849 };
10850
10851 /* Setup */
10852
10853 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10854 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10855 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10856 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10857 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10858 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
10859
10860 /* Methods */
10861
10862 /**
10863 * Get the menu.
10864 *
10865 * @return {OO.ui.MenuSelectWidget} Menu of widget
10866 */
10867 OO.ui.DropdownWidget.prototype.getMenu = function () {
10868 return this.menu;
10869 };
10870
10871 /**
10872 * Handles menu select events.
10873 *
10874 * @private
10875 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10876 */
10877 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10878 var selectedLabel;
10879
10880 if ( !item ) {
10881 return;
10882 }
10883
10884 selectedLabel = item.getLabel();
10885
10886 // If the label is a DOM element, clone it, because setLabel will append() it
10887 if ( selectedLabel instanceof jQuery ) {
10888 selectedLabel = selectedLabel.clone();
10889 }
10890
10891 this.setLabel( selectedLabel );
10892 };
10893
10894 /**
10895 * Handle mouse click events.
10896 *
10897 * @private
10898 * @param {jQuery.Event} e Mouse click event
10899 */
10900 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10901 if ( !this.isDisabled() && e.which === 1 ) {
10902 this.menu.toggle();
10903 }
10904 return false;
10905 };
10906
10907 /**
10908 * Handle key press events.
10909 *
10910 * @private
10911 * @param {jQuery.Event} e Key press event
10912 */
10913 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
10914 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10915 this.menu.toggle();
10916 return false;
10917 }
10918 };
10919
10920 /**
10921 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10922 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10923 * for a list of icons included in the library.
10924 *
10925 * @example
10926 * // An icon widget with a label
10927 * var myIcon = new OO.ui.IconWidget( {
10928 * icon: 'help',
10929 * iconTitle: 'Help'
10930 * } );
10931 * // Create a label.
10932 * var iconLabel = new OO.ui.LabelWidget( {
10933 * label: 'Help'
10934 * } );
10935 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10936 *
10937 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10938 *
10939 * @class
10940 * @extends OO.ui.Widget
10941 * @mixins OO.ui.IconElement
10942 * @mixins OO.ui.TitledElement
10943 * @mixins OO.ui.FlaggedElement
10944 *
10945 * @constructor
10946 * @param {Object} [config] Configuration options
10947 */
10948 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10949 // Configuration initialization
10950 config = config || {};
10951
10952 // Parent constructor
10953 OO.ui.IconWidget.super.call( this, config );
10954
10955 // Mixin constructors
10956 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10957 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10958 OO.ui.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) );
10959
10960 // Initialization
10961 this.$element.addClass( 'oo-ui-iconWidget' );
10962 };
10963
10964 /* Setup */
10965
10966 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10967 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10968 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10969 OO.mixinClass( OO.ui.IconWidget, OO.ui.FlaggedElement );
10970
10971 /* Static Properties */
10972
10973 OO.ui.IconWidget.static.tagName = 'span';
10974
10975 /**
10976 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10977 * attention to the status of an item or to clarify the function of a control. For a list of
10978 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10979 *
10980 * @example
10981 * // Example of an indicator widget
10982 * var indicator1 = new OO.ui.IndicatorWidget( {
10983 * indicator: 'alert'
10984 * } );
10985 *
10986 * // Create a fieldset layout to add a label
10987 * var fieldset = new OO.ui.FieldsetLayout();
10988 * fieldset.addItems( [
10989 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10990 * ] );
10991 * $( 'body' ).append( fieldset.$element );
10992 *
10993 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10994 *
10995 * @class
10996 * @extends OO.ui.Widget
10997 * @mixins OO.ui.IndicatorElement
10998 * @mixins OO.ui.TitledElement
10999 *
11000 * @constructor
11001 * @param {Object} [config] Configuration options
11002 */
11003 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
11004 // Configuration initialization
11005 config = config || {};
11006
11007 // Parent constructor
11008 OO.ui.IndicatorWidget.super.call( this, config );
11009
11010 // Mixin constructors
11011 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
11012 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
11013
11014 // Initialization
11015 this.$element.addClass( 'oo-ui-indicatorWidget' );
11016 };
11017
11018 /* Setup */
11019
11020 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
11021 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
11022 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
11023
11024 /* Static Properties */
11025
11026 OO.ui.IndicatorWidget.static.tagName = 'span';
11027
11028 /**
11029 * InputWidget is the base class for all input widgets, which
11030 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
11031 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
11032 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11033 *
11034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11035 *
11036 * @abstract
11037 * @class
11038 * @extends OO.ui.Widget
11039 * @mixins OO.ui.FlaggedElement
11040 * @mixins OO.ui.TabIndexedElement
11041 *
11042 * @constructor
11043 * @param {Object} [config] Configuration options
11044 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
11045 * @cfg {string} [value=''] The value of the input.
11046 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
11047 * before it is accepted.
11048 */
11049 OO.ui.InputWidget = function OoUiInputWidget( config ) {
11050 // Configuration initialization
11051 config = config || {};
11052
11053 // Parent constructor
11054 OO.ui.InputWidget.super.call( this, config );
11055
11056 // Properties
11057 this.$input = this.getInputElement( config );
11058 this.value = '';
11059 this.inputFilter = config.inputFilter;
11060
11061 // Mixin constructors
11062 OO.ui.FlaggedElement.call( this, config );
11063 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
11064
11065 // Events
11066 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
11067
11068 // Initialization
11069 this.$input
11070 .attr( 'name', config.name )
11071 .prop( 'disabled', this.isDisabled() );
11072 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
11073 this.setValue( config.value );
11074 };
11075
11076 /* Setup */
11077
11078 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
11079 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
11080 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
11081
11082 /* Events */
11083
11084 /**
11085 * @event change
11086 *
11087 * A change event is emitted when the value of the input changes.
11088 *
11089 * @param {string} value
11090 */
11091
11092 /* Methods */
11093
11094 /**
11095 * Get input element.
11096 *
11097 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
11098 * different circumstances. The element must have a `value` property (like form elements).
11099 *
11100 * @private
11101 * @param {Object} config Configuration options
11102 * @return {jQuery} Input element
11103 */
11104 OO.ui.InputWidget.prototype.getInputElement = function () {
11105 return $( '<input>' );
11106 };
11107
11108 /**
11109 * Handle potentially value-changing events.
11110 *
11111 * @private
11112 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
11113 */
11114 OO.ui.InputWidget.prototype.onEdit = function () {
11115 var widget = this;
11116 if ( !this.isDisabled() ) {
11117 // Allow the stack to clear so the value will be updated
11118 setTimeout( function () {
11119 widget.setValue( widget.$input.val() );
11120 } );
11121 }
11122 };
11123
11124 /**
11125 * Get the value of the input.
11126 *
11127 * @return {string} Input value
11128 */
11129 OO.ui.InputWidget.prototype.getValue = function () {
11130 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11131 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11132 var value = this.$input.val();
11133 if ( this.value !== value ) {
11134 this.setValue( value );
11135 }
11136 return this.value;
11137 };
11138
11139 /**
11140 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
11141 *
11142 * @param {boolean} isRTL
11143 * Direction is right-to-left
11144 */
11145 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
11146 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
11147 };
11148
11149 /**
11150 * Set the value of the input.
11151 *
11152 * @param {string} value New value
11153 * @fires change
11154 * @chainable
11155 */
11156 OO.ui.InputWidget.prototype.setValue = function ( value ) {
11157 value = this.cleanUpValue( value );
11158 // Update the DOM if it has changed. Note that with cleanUpValue, it
11159 // is possible for the DOM value to change without this.value changing.
11160 if ( this.$input.val() !== value ) {
11161 this.$input.val( value );
11162 }
11163 if ( this.value !== value ) {
11164 this.value = value;
11165 this.emit( 'change', this.value );
11166 }
11167 return this;
11168 };
11169
11170 /**
11171 * Clean up incoming value.
11172 *
11173 * Ensures value is a string, and converts undefined and null to empty string.
11174 *
11175 * @private
11176 * @param {string} value Original value
11177 * @return {string} Cleaned up value
11178 */
11179 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
11180 if ( value === undefined || value === null ) {
11181 return '';
11182 } else if ( this.inputFilter ) {
11183 return this.inputFilter( String( value ) );
11184 } else {
11185 return String( value );
11186 }
11187 };
11188
11189 /**
11190 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11191 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11192 * called directly.
11193 */
11194 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
11195 if ( !this.isDisabled() ) {
11196 if ( this.$input.is( ':checkbox, :radio' ) ) {
11197 this.$input.click();
11198 }
11199 if ( this.$input.is( ':input' ) ) {
11200 this.$input[ 0 ].focus();
11201 }
11202 }
11203 };
11204
11205 /**
11206 * @inheritdoc
11207 */
11208 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
11209 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
11210 if ( this.$input ) {
11211 this.$input.prop( 'disabled', this.isDisabled() );
11212 }
11213 return this;
11214 };
11215
11216 /**
11217 * Focus the input.
11218 *
11219 * @chainable
11220 */
11221 OO.ui.InputWidget.prototype.focus = function () {
11222 this.$input[ 0 ].focus();
11223 return this;
11224 };
11225
11226 /**
11227 * Blur the input.
11228 *
11229 * @chainable
11230 */
11231 OO.ui.InputWidget.prototype.blur = function () {
11232 this.$input[ 0 ].blur();
11233 return this;
11234 };
11235
11236 /**
11237 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11238 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11239 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11240 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11241 * [OOjs UI documentation on MediaWiki] [1] for more information.
11242 *
11243 * @example
11244 * // A ButtonInputWidget rendered as an HTML button, the default.
11245 * var button = new OO.ui.ButtonInputWidget( {
11246 * label: 'Input button',
11247 * icon: 'check',
11248 * value: 'check'
11249 * } );
11250 * $( 'body' ).append( button.$element );
11251 *
11252 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11253 *
11254 * @class
11255 * @extends OO.ui.InputWidget
11256 * @mixins OO.ui.ButtonElement
11257 * @mixins OO.ui.IconElement
11258 * @mixins OO.ui.IndicatorElement
11259 * @mixins OO.ui.LabelElement
11260 * @mixins OO.ui.TitledElement
11261 * @mixins OO.ui.FlaggedElement
11262 *
11263 * @constructor
11264 * @param {Object} [config] Configuration options
11265 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11266 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11267 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11268 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11269 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11270 */
11271 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
11272 // Configuration initialization
11273 config = $.extend( { type: 'button', useInputTag: false }, config );
11274
11275 // Properties (must be set before parent constructor, which calls #setValue)
11276 this.useInputTag = config.useInputTag;
11277
11278 // Parent constructor
11279 OO.ui.ButtonInputWidget.super.call( this, config );
11280
11281 // Mixin constructors
11282 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
11283 OO.ui.IconElement.call( this, config );
11284 OO.ui.IndicatorElement.call( this, config );
11285 OO.ui.LabelElement.call( this, config );
11286 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
11287 OO.ui.FlaggedElement.call( this, config );
11288
11289 // Initialization
11290 if ( !config.useInputTag ) {
11291 this.$input.append( this.$icon, this.$label, this.$indicator );
11292 }
11293 this.$element.addClass( 'oo-ui-buttonInputWidget' );
11294 };
11295
11296 /* Setup */
11297
11298 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
11299 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
11300 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
11301 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
11302 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
11303 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
11304 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
11305
11306 /* Methods */
11307
11308 /**
11309 * @inheritdoc
11310 * @private
11311 */
11312 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
11313 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
11314 return $( html );
11315 };
11316
11317 /**
11318 * Set label value.
11319 *
11320 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11321 *
11322 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11323 * text, or `null` for no label
11324 * @chainable
11325 */
11326 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
11327 OO.ui.LabelElement.prototype.setLabel.call( this, label );
11328
11329 if ( this.useInputTag ) {
11330 if ( typeof label === 'function' ) {
11331 label = OO.ui.resolveMsg( label );
11332 }
11333 if ( label instanceof jQuery ) {
11334 label = label.text();
11335 }
11336 if ( !label ) {
11337 label = '';
11338 }
11339 this.$input.val( label );
11340 }
11341
11342 return this;
11343 };
11344
11345 /**
11346 * Set the value of the input.
11347 *
11348 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11349 * they do not support {@link #value values}.
11350 *
11351 * @param {string} value New value
11352 * @chainable
11353 */
11354 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11355 if ( !this.useInputTag ) {
11356 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11357 }
11358 return this;
11359 };
11360
11361 /**
11362 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11363 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11364 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11365 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11366 *
11367 * @example
11368 * // An example of selected, unselected, and disabled checkbox inputs
11369 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11370 * value: 'a',
11371 * selected: true
11372 * } );
11373 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11374 * value: 'b'
11375 * } );
11376 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11377 * value:'c',
11378 * disabled: true
11379 * } );
11380 * // Create a fieldset layout with fields for each checkbox.
11381 * var fieldset = new OO.ui.FieldsetLayout( {
11382 * label: 'Checkboxes'
11383 * } );
11384 * fieldset.addItems( [
11385 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11386 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11387 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11388 * ] );
11389 * $( 'body' ).append( fieldset.$element );
11390 *
11391 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11392 *
11393 * @class
11394 * @extends OO.ui.InputWidget
11395 *
11396 * @constructor
11397 * @param {Object} [config] Configuration options
11398 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11399 */
11400 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11401 // Configuration initialization
11402 config = config || {};
11403
11404 // Parent constructor
11405 OO.ui.CheckboxInputWidget.super.call( this, config );
11406
11407 // Initialization
11408 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11409 this.setSelected( config.selected !== undefined ? config.selected : false );
11410 };
11411
11412 /* Setup */
11413
11414 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11415
11416 /* Methods */
11417
11418 /**
11419 * @inheritdoc
11420 * @private
11421 */
11422 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11423 return $( '<input type="checkbox" />' );
11424 };
11425
11426 /**
11427 * @inheritdoc
11428 */
11429 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11430 var widget = this;
11431 if ( !this.isDisabled() ) {
11432 // Allow the stack to clear so the value will be updated
11433 setTimeout( function () {
11434 widget.setSelected( widget.$input.prop( 'checked' ) );
11435 } );
11436 }
11437 };
11438
11439 /**
11440 * Set selection state of this checkbox.
11441 *
11442 * @param {boolean} state `true` for selected
11443 * @chainable
11444 */
11445 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11446 state = !!state;
11447 if ( this.selected !== state ) {
11448 this.selected = state;
11449 this.$input.prop( 'checked', this.selected );
11450 this.emit( 'change', this.selected );
11451 }
11452 return this;
11453 };
11454
11455 /**
11456 * Check if this checkbox is selected.
11457 *
11458 * @return {boolean} Checkbox is selected
11459 */
11460 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11461 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11462 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11463 var selected = this.$input.prop( 'checked' );
11464 if ( this.selected !== selected ) {
11465 this.setSelected( selected );
11466 }
11467 return this.selected;
11468 };
11469
11470 /**
11471 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11472 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11473 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11474 * more information about input widgets.
11475 *
11476 * @example
11477 * // Example: A DropdownInputWidget with three options
11478 * var dropDown = new OO.ui.DropdownInputWidget( {
11479 * label: 'Dropdown menu: Select a menu option',
11480 * options: [
11481 * { data: 'a', label: 'First' } ,
11482 * { data: 'b', label: 'Second'} ,
11483 * { data: 'c', label: 'Third' }
11484 * ]
11485 * } );
11486 * $( 'body' ).append( dropDown.$element );
11487 *
11488 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11489 *
11490 * @class
11491 * @extends OO.ui.InputWidget
11492 *
11493 * @constructor
11494 * @param {Object} [config] Configuration options
11495 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11496 */
11497 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11498 // Configuration initialization
11499 config = config || {};
11500
11501 // Properties (must be done before parent constructor which calls #setDisabled)
11502 this.dropdownWidget = new OO.ui.DropdownWidget();
11503
11504 // Parent constructor
11505 OO.ui.DropdownInputWidget.super.call( this, config );
11506
11507 // Events
11508 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11509
11510 // Initialization
11511 this.setOptions( config.options || [] );
11512 this.$element
11513 .addClass( 'oo-ui-dropdownInputWidget' )
11514 .append( this.dropdownWidget.$element );
11515 };
11516
11517 /* Setup */
11518
11519 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11520
11521 /* Methods */
11522
11523 /**
11524 * @inheritdoc
11525 * @private
11526 */
11527 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11528 return $( '<input type="hidden">' );
11529 };
11530
11531 /**
11532 * Handles menu select events.
11533 *
11534 * @private
11535 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11536 */
11537 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11538 this.setValue( item.getData() );
11539 };
11540
11541 /**
11542 * @inheritdoc
11543 */
11544 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11545 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11546 if ( item ) {
11547 this.dropdownWidget.getMenu().selectItem( item );
11548 }
11549 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11550 return this;
11551 };
11552
11553 /**
11554 * @inheritdoc
11555 */
11556 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11557 this.dropdownWidget.setDisabled( state );
11558 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11559 return this;
11560 };
11561
11562 /**
11563 * Set the options available for this input.
11564 *
11565 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11566 * @chainable
11567 */
11568 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11569 var value = this.getValue();
11570
11571 // Rebuild the dropdown menu
11572 this.dropdownWidget.getMenu()
11573 .clearItems()
11574 .addItems( options.map( function ( opt ) {
11575 return new OO.ui.MenuOptionWidget( {
11576 data: opt.data,
11577 label: opt.label !== undefined ? opt.label : opt.data
11578 } );
11579 } ) );
11580
11581 // Restore the previous value, or reset to something sensible
11582 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11583 // Previous value is still available, ensure consistency with the dropdown
11584 this.setValue( value );
11585 } else {
11586 // No longer valid, reset
11587 if ( options.length ) {
11588 this.setValue( options[ 0 ].data );
11589 }
11590 }
11591
11592 return this;
11593 };
11594
11595 /**
11596 * @inheritdoc
11597 */
11598 OO.ui.DropdownInputWidget.prototype.focus = function () {
11599 this.dropdownWidget.getMenu().toggle( true );
11600 return this;
11601 };
11602
11603 /**
11604 * @inheritdoc
11605 */
11606 OO.ui.DropdownInputWidget.prototype.blur = function () {
11607 this.dropdownWidget.getMenu().toggle( false );
11608 return this;
11609 };
11610
11611 /**
11612 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11613 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11614 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11615 * please see the [OOjs UI documentation on MediaWiki][1].
11616 *
11617 * @example
11618 * // An example of selected, unselected, and disabled radio inputs
11619 * var radio1 = new OO.ui.RadioInputWidget( {
11620 * value: 'a',
11621 * selected: true
11622 * } );
11623 * var radio2 = new OO.ui.RadioInputWidget( {
11624 * value: 'b'
11625 * } );
11626 * var radio3 = new OO.ui.RadioInputWidget( {
11627 * value: 'c',
11628 * disabled: true
11629 * } );
11630 * // Create a fieldset layout with fields for each radio button.
11631 * var fieldset = new OO.ui.FieldsetLayout( {
11632 * label: 'Radio inputs'
11633 * } );
11634 * fieldset.addItems( [
11635 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11636 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11637 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11638 * ] );
11639 * $( 'body' ).append( fieldset.$element );
11640 *
11641 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11642 *
11643 * @class
11644 * @extends OO.ui.InputWidget
11645 *
11646 * @constructor
11647 * @param {Object} [config] Configuration options
11648 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11649 */
11650 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11651 // Configuration initialization
11652 config = config || {};
11653
11654 // Parent constructor
11655 OO.ui.RadioInputWidget.super.call( this, config );
11656
11657 // Initialization
11658 this.$element.addClass( 'oo-ui-radioInputWidget' );
11659 this.setSelected( config.selected !== undefined ? config.selected : false );
11660 };
11661
11662 /* Setup */
11663
11664 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11665
11666 /* Methods */
11667
11668 /**
11669 * @inheritdoc
11670 * @private
11671 */
11672 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11673 return $( '<input type="radio" />' );
11674 };
11675
11676 /**
11677 * @inheritdoc
11678 */
11679 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11680 // RadioInputWidget doesn't track its state.
11681 };
11682
11683 /**
11684 * Set selection state of this radio button.
11685 *
11686 * @param {boolean} state `true` for selected
11687 * @chainable
11688 */
11689 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11690 // RadioInputWidget doesn't track its state.
11691 this.$input.prop( 'checked', state );
11692 return this;
11693 };
11694
11695 /**
11696 * Check if this radio button is selected.
11697 *
11698 * @return {boolean} Radio is selected
11699 */
11700 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11701 return this.$input.prop( 'checked' );
11702 };
11703
11704 /**
11705 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11706 * size of the field as well as its presentation. In addition, these widgets can be configured
11707 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11708 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11709 * which modifies incoming values rather than validating them.
11710 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11711 *
11712 * @example
11713 * // Example of a text input widget
11714 * var textInput = new OO.ui.TextInputWidget( {
11715 * value: 'Text input'
11716 * } )
11717 * $( 'body' ).append( textInput.$element );
11718 *
11719 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11720 *
11721 * @class
11722 * @extends OO.ui.InputWidget
11723 * @mixins OO.ui.IconElement
11724 * @mixins OO.ui.IndicatorElement
11725 * @mixins OO.ui.PendingElement
11726 * @mixins OO.ui.LabelElement
11727 *
11728 * @constructor
11729 * @param {Object} [config] Configuration options
11730 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11731 * @cfg {string} [placeholder] Placeholder text
11732 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11733 * instruct the browser to focus this widget.
11734 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11735 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11736 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11737 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11738 * Use the #maxRows config to specify a maximum number of displayed rows.
11739 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11740 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11741 * the value or placeholder text: `'before'` or `'after'`
11742 * @cfg {boolean} [required=false] Mark the field as required
11743 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11744 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11745 * or 'integer' (the value must contain only numbers).
11746 */
11747 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
11748 // Configuration initialization
11749 config = $.extend( {
11750 type: 'text',
11751 labelPosition: 'after',
11752 maxRows: 10
11753 }, config );
11754
11755 // Parent constructor
11756 OO.ui.TextInputWidget.super.call( this, config );
11757
11758 // Mixin constructors
11759 OO.ui.IconElement.call( this, config );
11760 OO.ui.IndicatorElement.call( this, config );
11761 OO.ui.PendingElement.call( this, config );
11762 OO.ui.LabelElement.call( this, config );
11763
11764 // Properties
11765 this.readOnly = false;
11766 this.multiline = !!config.multiline;
11767 this.autosize = !!config.autosize;
11768 this.maxRows = config.maxRows;
11769 this.validate = null;
11770
11771 // Clone for resizing
11772 if ( this.autosize ) {
11773 this.$clone = this.$input
11774 .clone()
11775 .insertAfter( this.$input )
11776 .attr( 'aria-hidden', 'true' )
11777 .addClass( 'oo-ui-element-hidden' );
11778 }
11779
11780 this.setValidation( config.validate );
11781 this.setLabelPosition( config.labelPosition );
11782
11783 // Events
11784 this.$input.on( {
11785 keypress: this.onKeyPress.bind( this ),
11786 blur: this.setValidityFlag.bind( this )
11787 } );
11788 this.$input.one( {
11789 focus: this.onElementAttach.bind( this )
11790 } );
11791 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11792 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11793 this.on( 'labelChange', this.updatePosition.bind( this ) );
11794
11795 // Initialization
11796 this.$element
11797 .addClass( 'oo-ui-textInputWidget' )
11798 .append( this.$icon, this.$indicator );
11799 this.setReadOnly( !!config.readOnly );
11800 if ( config.placeholder ) {
11801 this.$input.attr( 'placeholder', config.placeholder );
11802 }
11803 if ( config.maxLength !== undefined ) {
11804 this.$input.attr( 'maxlength', config.maxLength );
11805 }
11806 if ( config.autofocus ) {
11807 this.$input.attr( 'autofocus', 'autofocus' );
11808 }
11809 if ( config.required ) {
11810 this.$input.attr( 'required', 'true' );
11811 }
11812 if ( this.label || config.autosize ) {
11813 this.installParentChangeDetector();
11814 }
11815 };
11816
11817 /* Setup */
11818
11819 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11820 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11821 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11822 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11823 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11824
11825 /* Static properties */
11826
11827 OO.ui.TextInputWidget.static.validationPatterns = {
11828 'non-empty': /.+/,
11829 integer: /^\d+$/
11830 };
11831
11832 /* Events */
11833
11834 /**
11835 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11836 *
11837 * Not emitted if the input is multiline.
11838 *
11839 * @event enter
11840 */
11841
11842 /* Methods */
11843
11844 /**
11845 * Handle icon mouse down events.
11846 *
11847 * @private
11848 * @param {jQuery.Event} e Mouse down event
11849 * @fires icon
11850 */
11851 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11852 if ( e.which === 1 ) {
11853 this.$input[ 0 ].focus();
11854 return false;
11855 }
11856 };
11857
11858 /**
11859 * Handle indicator mouse down events.
11860 *
11861 * @private
11862 * @param {jQuery.Event} e Mouse down event
11863 * @fires indicator
11864 */
11865 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11866 if ( e.which === 1 ) {
11867 this.$input[ 0 ].focus();
11868 return false;
11869 }
11870 };
11871
11872 /**
11873 * Handle key press events.
11874 *
11875 * @private
11876 * @param {jQuery.Event} e Key press event
11877 * @fires enter If enter key is pressed and input is not multiline
11878 */
11879 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11880 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11881 this.emit( 'enter', e );
11882 }
11883 };
11884
11885 /**
11886 * Handle element attach events.
11887 *
11888 * @private
11889 * @param {jQuery.Event} e Element attach event
11890 */
11891 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11892 // Any previously calculated size is now probably invalid if we reattached elsewhere
11893 this.valCache = null;
11894 this.adjustSize();
11895 this.positionLabel();
11896 };
11897
11898 /**
11899 * @inheritdoc
11900 */
11901 OO.ui.TextInputWidget.prototype.onEdit = function () {
11902 this.adjustSize();
11903
11904 // Parent method
11905 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11906 };
11907
11908 /**
11909 * @inheritdoc
11910 */
11911 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11912 // Parent method
11913 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11914
11915 this.setValidityFlag();
11916 this.adjustSize();
11917 return this;
11918 };
11919
11920 /**
11921 * Check if the input is {@link #readOnly read-only}.
11922 *
11923 * @return {boolean}
11924 */
11925 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11926 return this.readOnly;
11927 };
11928
11929 /**
11930 * Set the {@link #readOnly read-only} state of the input.
11931 *
11932 * @param {boolean} state Make input read-only
11933 * @chainable
11934 */
11935 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11936 this.readOnly = !!state;
11937 this.$input.prop( 'readOnly', this.readOnly );
11938 return this;
11939 };
11940
11941 /**
11942 * Support function for making #onElementAttach work across browsers.
11943 *
11944 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11945 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11946 *
11947 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11948 * first time that the element gets attached to the documented.
11949 */
11950 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
11951 var mutationObserver, onRemove, topmostNode, fakeParentNode,
11952 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
11953 widget = this;
11954
11955 if ( MutationObserver ) {
11956 // The new way. If only it wasn't so ugly.
11957
11958 if ( this.$element.closest( 'html' ).length ) {
11959 // Widget is attached already, do nothing. This breaks the functionality of this function when
11960 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11961 // would require observation of the whole document, which would hurt performance of other,
11962 // more important code.
11963 return;
11964 }
11965
11966 // Find topmost node in the tree
11967 topmostNode = this.$element[0];
11968 while ( topmostNode.parentNode ) {
11969 topmostNode = topmostNode.parentNode;
11970 }
11971
11972 // We have no way to detect the $element being attached somewhere without observing the entire
11973 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11974 // parent node of $element, and instead detect when $element is removed from it (and thus
11975 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11976 // doesn't get attached, we end up back here and create the parent.
11977
11978 mutationObserver = new MutationObserver( function ( mutations ) {
11979 var i, j, removedNodes;
11980 for ( i = 0; i < mutations.length; i++ ) {
11981 removedNodes = mutations[ i ].removedNodes;
11982 for ( j = 0; j < removedNodes.length; j++ ) {
11983 if ( removedNodes[ j ] === topmostNode ) {
11984 setTimeout( onRemove, 0 );
11985 return;
11986 }
11987 }
11988 }
11989 } );
11990
11991 onRemove = function () {
11992 // If the node was attached somewhere else, report it
11993 if ( widget.$element.closest( 'html' ).length ) {
11994 widget.onElementAttach();
11995 }
11996 mutationObserver.disconnect();
11997 widget.installParentChangeDetector();
11998 };
11999
12000 // Create a fake parent and observe it
12001 fakeParentNode = $( '<div>' ).append( this.$element )[0];
12002 mutationObserver.observe( fakeParentNode, { childList: true } );
12003 } else {
12004 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
12005 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
12006 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
12007 }
12008 };
12009
12010 /**
12011 * Automatically adjust the size of the text input.
12012 *
12013 * This only affects #multiline inputs that are {@link #autosize autosized}.
12014 *
12015 * @chainable
12016 */
12017 OO.ui.TextInputWidget.prototype.adjustSize = function () {
12018 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
12019
12020 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
12021 this.$clone
12022 .val( this.$input.val() )
12023 .attr( 'rows', '' )
12024 // Set inline height property to 0 to measure scroll height
12025 .css( 'height', 0 );
12026
12027 this.$clone.removeClass( 'oo-ui-element-hidden' );
12028
12029 this.valCache = this.$input.val();
12030
12031 scrollHeight = this.$clone[ 0 ].scrollHeight;
12032
12033 // Remove inline height property to measure natural heights
12034 this.$clone.css( 'height', '' );
12035 innerHeight = this.$clone.innerHeight();
12036 outerHeight = this.$clone.outerHeight();
12037
12038 // Measure max rows height
12039 this.$clone
12040 .attr( 'rows', this.maxRows )
12041 .css( 'height', 'auto' )
12042 .val( '' );
12043 maxInnerHeight = this.$clone.innerHeight();
12044
12045 // Difference between reported innerHeight and scrollHeight with no scrollbars present
12046 // Equals 1 on Blink-based browsers and 0 everywhere else
12047 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
12048 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
12049
12050 this.$clone.addClass( 'oo-ui-element-hidden' );
12051
12052 // Only apply inline height when expansion beyond natural height is needed
12053 if ( idealHeight > innerHeight ) {
12054 // Use the difference between the inner and outer height as a buffer
12055 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
12056 } else {
12057 this.$input.css( 'height', '' );
12058 }
12059 }
12060 return this;
12061 };
12062
12063 /**
12064 * @inheritdoc
12065 * @private
12066 */
12067 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
12068 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
12069 };
12070
12071 /**
12072 * Check if the input supports multiple lines.
12073 *
12074 * @return {boolean}
12075 */
12076 OO.ui.TextInputWidget.prototype.isMultiline = function () {
12077 return !!this.multiline;
12078 };
12079
12080 /**
12081 * Check if the input automatically adjusts its size.
12082 *
12083 * @return {boolean}
12084 */
12085 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
12086 return !!this.autosize;
12087 };
12088
12089 /**
12090 * Select the entire text of the input.
12091 *
12092 * @chainable
12093 */
12094 OO.ui.TextInputWidget.prototype.select = function () {
12095 this.$input.select();
12096 return this;
12097 };
12098
12099 /**
12100 * Set the validation pattern.
12101 *
12102 * The validation pattern is either a regular expression or the symbolic name of a pattern
12103 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
12104 * value must contain only numbers).
12105 *
12106 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
12107 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
12108 */
12109 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
12110 if ( validate instanceof RegExp ) {
12111 this.validate = validate;
12112 } else {
12113 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
12114 }
12115 };
12116
12117 /**
12118 * Sets the 'invalid' flag appropriately.
12119 */
12120 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
12121 var widget = this;
12122 this.isValid().done( function ( valid ) {
12123 widget.setFlags( { invalid: !valid } );
12124 } );
12125 };
12126
12127 /**
12128 * Check if a value is valid.
12129 *
12130 * This method returns a promise that resolves with a boolean `true` if the current value is
12131 * considered valid according to the supplied {@link #validate validation pattern}.
12132 *
12133 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
12134 */
12135 OO.ui.TextInputWidget.prototype.isValid = function () {
12136 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
12137 };
12138
12139 /**
12140 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
12141 *
12142 * @param {string} labelPosition Label position, 'before' or 'after'
12143 * @chainable
12144 */
12145 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
12146 this.labelPosition = labelPosition;
12147 this.updatePosition();
12148 return this;
12149 };
12150
12151 /**
12152 * Deprecated alias of #setLabelPosition
12153 *
12154 * @deprecated Use setLabelPosition instead.
12155 */
12156 OO.ui.TextInputWidget.prototype.setPosition =
12157 OO.ui.TextInputWidget.prototype.setLabelPosition;
12158
12159 /**
12160 * Update the position of the inline label.
12161 *
12162 * This method is called by #setLabelPosition, and can also be called on its own if
12163 * something causes the label to be mispositioned.
12164 *
12165 *
12166 * @chainable
12167 */
12168 OO.ui.TextInputWidget.prototype.updatePosition = function () {
12169 var after = this.labelPosition === 'after';
12170
12171 this.$element
12172 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
12173 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
12174
12175 if ( this.label ) {
12176 this.positionLabel();
12177 }
12178
12179 return this;
12180 };
12181
12182 /**
12183 * Position the label by setting the correct padding on the input.
12184 *
12185 * @private
12186 * @chainable
12187 */
12188 OO.ui.TextInputWidget.prototype.positionLabel = function () {
12189 // Clear old values
12190 this.$input
12191 // Clear old values if present
12192 .css( {
12193 'padding-right': '',
12194 'padding-left': ''
12195 } );
12196
12197 if ( this.label ) {
12198 this.$element.append( this.$label );
12199 } else {
12200 this.$label.detach();
12201 return;
12202 }
12203
12204 var after = this.labelPosition === 'after',
12205 rtl = this.$element.css( 'direction' ) === 'rtl',
12206 property = after === rtl ? 'padding-left' : 'padding-right';
12207
12208 this.$input.css( property, this.$label.outerWidth( true ) );
12209
12210 return this;
12211 };
12212
12213 /**
12214 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12215 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12216 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12217 *
12218 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12219 * option, that option will appear to be selected.
12220 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12221 * input field.
12222 *
12223 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12224 *
12225 * @example
12226 * // Example: A ComboBoxWidget.
12227 * var comboBox = new OO.ui.ComboBoxWidget( {
12228 * label: 'ComboBoxWidget',
12229 * input: { value: 'Option One' },
12230 * menu: {
12231 * items: [
12232 * new OO.ui.MenuOptionWidget( {
12233 * data: 'Option 1',
12234 * label: 'Option One'
12235 * } ),
12236 * new OO.ui.MenuOptionWidget( {
12237 * data: 'Option 2',
12238 * label: 'Option Two'
12239 * } ),
12240 * new OO.ui.MenuOptionWidget( {
12241 * data: 'Option 3',
12242 * label: 'Option Three'
12243 * } ),
12244 * new OO.ui.MenuOptionWidget( {
12245 * data: 'Option 4',
12246 * label: 'Option Four'
12247 * } ),
12248 * new OO.ui.MenuOptionWidget( {
12249 * data: 'Option 5',
12250 * label: 'Option Five'
12251 * } )
12252 * ]
12253 * }
12254 * } );
12255 * $( 'body' ).append( comboBox.$element );
12256 *
12257 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12258 *
12259 * @class
12260 * @extends OO.ui.Widget
12261 * @mixins OO.ui.TabIndexedElement
12262 *
12263 * @constructor
12264 * @param {Object} [config] Configuration options
12265 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12266 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12267 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12268 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12269 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12270 */
12271 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
12272 // Configuration initialization
12273 config = config || {};
12274
12275 // Parent constructor
12276 OO.ui.ComboBoxWidget.super.call( this, config );
12277
12278 // Properties (must be set before TabIndexedElement constructor call)
12279 this.$indicator = this.$( '<span>' );
12280
12281 // Mixin constructors
12282 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
12283
12284 // Properties
12285 this.$overlay = config.$overlay || this.$element;
12286 this.input = new OO.ui.TextInputWidget( $.extend(
12287 {
12288 indicator: 'down',
12289 $indicator: this.$indicator,
12290 disabled: this.isDisabled()
12291 },
12292 config.input
12293 ) );
12294 this.input.$input.eq( 0 ).attr( {
12295 role: 'combobox',
12296 'aria-autocomplete': 'list'
12297 } );
12298 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
12299 {
12300 widget: this,
12301 input: this.input,
12302 disabled: this.isDisabled()
12303 },
12304 config.menu
12305 ) );
12306
12307 // Events
12308 this.$indicator.on( {
12309 click: this.onClick.bind( this ),
12310 keypress: this.onKeyPress.bind( this )
12311 } );
12312 this.input.connect( this, {
12313 change: 'onInputChange',
12314 enter: 'onInputEnter'
12315 } );
12316 this.menu.connect( this, {
12317 choose: 'onMenuChoose',
12318 add: 'onMenuItemsChange',
12319 remove: 'onMenuItemsChange'
12320 } );
12321
12322 // Initialization
12323 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
12324 this.$overlay.append( this.menu.$element );
12325 this.onMenuItemsChange();
12326 };
12327
12328 /* Setup */
12329
12330 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
12331 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
12332
12333 /* Methods */
12334
12335 /**
12336 * Get the combobox's menu.
12337 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12338 */
12339 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
12340 return this.menu;
12341 };
12342
12343 /**
12344 * Handle input change events.
12345 *
12346 * @private
12347 * @param {string} value New value
12348 */
12349 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
12350 var match = this.menu.getItemFromData( value );
12351
12352 this.menu.selectItem( match );
12353 if ( this.menu.getHighlightedItem() ) {
12354 this.menu.highlightItem( match );
12355 }
12356
12357 if ( !this.isDisabled() ) {
12358 this.menu.toggle( true );
12359 }
12360 };
12361
12362 /**
12363 * Handle mouse click events.
12364 *
12365 *
12366 * @private
12367 * @param {jQuery.Event} e Mouse click event
12368 */
12369 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
12370 if ( !this.isDisabled() && e.which === 1 ) {
12371 this.menu.toggle();
12372 this.input.$input[ 0 ].focus();
12373 }
12374 return false;
12375 };
12376
12377 /**
12378 * Handle key press events.
12379 *
12380 *
12381 * @private
12382 * @param {jQuery.Event} e Key press event
12383 */
12384 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
12385 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
12386 this.menu.toggle();
12387 this.input.$input[ 0 ].focus();
12388 return false;
12389 }
12390 };
12391
12392 /**
12393 * Handle input enter events.
12394 *
12395 * @private
12396 */
12397 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
12398 if ( !this.isDisabled() ) {
12399 this.menu.toggle( false );
12400 }
12401 };
12402
12403 /**
12404 * Handle menu choose events.
12405 *
12406 * @private
12407 * @param {OO.ui.OptionWidget} item Chosen item
12408 */
12409 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
12410 this.input.setValue( item.getData() );
12411 };
12412
12413 /**
12414 * Handle menu item change events.
12415 *
12416 * @private
12417 */
12418 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
12419 var match = this.menu.getItemFromData( this.input.getValue() );
12420 this.menu.selectItem( match );
12421 if ( this.menu.getHighlightedItem() ) {
12422 this.menu.highlightItem( match );
12423 }
12424 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
12425 };
12426
12427 /**
12428 * @inheritdoc
12429 */
12430 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
12431 // Parent method
12432 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
12433
12434 if ( this.input ) {
12435 this.input.setDisabled( this.isDisabled() );
12436 }
12437 if ( this.menu ) {
12438 this.menu.setDisabled( this.isDisabled() );
12439 }
12440
12441 return this;
12442 };
12443
12444 /**
12445 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12446 * be configured with a `label` option that is set to a string, a label node, or a function:
12447 *
12448 * - String: a plaintext string
12449 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12450 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12451 * - Function: a function that will produce a string in the future. Functions are used
12452 * in cases where the value of the label is not currently defined.
12453 *
12454 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12455 * will come into focus when the label is clicked.
12456 *
12457 * @example
12458 * // Examples of LabelWidgets
12459 * var label1 = new OO.ui.LabelWidget( {
12460 * label: 'plaintext label'
12461 * } );
12462 * var label2 = new OO.ui.LabelWidget( {
12463 * label: $( '<a href="default.html">jQuery label</a>' )
12464 * } );
12465 * // Create a fieldset layout with fields for each example
12466 * var fieldset = new OO.ui.FieldsetLayout();
12467 * fieldset.addItems( [
12468 * new OO.ui.FieldLayout( label1 ),
12469 * new OO.ui.FieldLayout( label2 )
12470 * ] );
12471 * $( 'body' ).append( fieldset.$element );
12472 *
12473 *
12474 * @class
12475 * @extends OO.ui.Widget
12476 * @mixins OO.ui.LabelElement
12477 *
12478 * @constructor
12479 * @param {Object} [config] Configuration options
12480 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12481 * Clicking the label will focus the specified input field.
12482 */
12483 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
12484 // Configuration initialization
12485 config = config || {};
12486
12487 // Parent constructor
12488 OO.ui.LabelWidget.super.call( this, config );
12489
12490 // Mixin constructors
12491 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
12492 OO.ui.TitledElement.call( this, config );
12493
12494 // Properties
12495 this.input = config.input;
12496
12497 // Events
12498 if ( this.input instanceof OO.ui.InputWidget ) {
12499 this.$element.on( 'click', this.onClick.bind( this ) );
12500 }
12501
12502 // Initialization
12503 this.$element.addClass( 'oo-ui-labelWidget' );
12504 };
12505
12506 /* Setup */
12507
12508 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
12509 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
12510 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
12511
12512 /* Static Properties */
12513
12514 OO.ui.LabelWidget.static.tagName = 'span';
12515
12516 /* Methods */
12517
12518 /**
12519 * Handles label mouse click events.
12520 *
12521 * @private
12522 * @param {jQuery.Event} e Mouse click event
12523 */
12524 OO.ui.LabelWidget.prototype.onClick = function () {
12525 this.input.simulateLabelClick();
12526 return false;
12527 };
12528
12529 /**
12530 * OptionWidgets are special elements that can be selected and configured with data. The
12531 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12532 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12533 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12534 *
12535 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12536 *
12537 * @class
12538 * @extends OO.ui.Widget
12539 * @mixins OO.ui.LabelElement
12540 * @mixins OO.ui.FlaggedElement
12541 *
12542 * @constructor
12543 * @param {Object} [config] Configuration options
12544 */
12545 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
12546 // Configuration initialization
12547 config = config || {};
12548
12549 // Parent constructor
12550 OO.ui.OptionWidget.super.call( this, config );
12551
12552 // Mixin constructors
12553 OO.ui.ItemWidget.call( this );
12554 OO.ui.LabelElement.call( this, config );
12555 OO.ui.FlaggedElement.call( this, config );
12556
12557 // Properties
12558 this.selected = false;
12559 this.highlighted = false;
12560 this.pressed = false;
12561
12562 // Initialization
12563 this.$element
12564 .data( 'oo-ui-optionWidget', this )
12565 .attr( 'role', 'option' )
12566 .addClass( 'oo-ui-optionWidget' )
12567 .append( this.$label );
12568 };
12569
12570 /* Setup */
12571
12572 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12573 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12574 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12575 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12576
12577 /* Static Properties */
12578
12579 OO.ui.OptionWidget.static.selectable = true;
12580
12581 OO.ui.OptionWidget.static.highlightable = true;
12582
12583 OO.ui.OptionWidget.static.pressable = true;
12584
12585 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12586
12587 /* Methods */
12588
12589 /**
12590 * Check if the option can be selected.
12591 *
12592 * @return {boolean} Item is selectable
12593 */
12594 OO.ui.OptionWidget.prototype.isSelectable = function () {
12595 return this.constructor.static.selectable && !this.isDisabled();
12596 };
12597
12598 /**
12599 * Check if the option can be highlighted. A highlight indicates that the option
12600 * may be selected when a user presses enter or clicks. Disabled items cannot
12601 * be highlighted.
12602 *
12603 * @return {boolean} Item is highlightable
12604 */
12605 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12606 return this.constructor.static.highlightable && !this.isDisabled();
12607 };
12608
12609 /**
12610 * Check if the option can be pressed. The pressed state occurs when a user mouses
12611 * down on an item, but has not yet let go of the mouse.
12612 *
12613 * @return {boolean} Item is pressable
12614 */
12615 OO.ui.OptionWidget.prototype.isPressable = function () {
12616 return this.constructor.static.pressable && !this.isDisabled();
12617 };
12618
12619 /**
12620 * Check if the option is selected.
12621 *
12622 * @return {boolean} Item is selected
12623 */
12624 OO.ui.OptionWidget.prototype.isSelected = function () {
12625 return this.selected;
12626 };
12627
12628 /**
12629 * Check if the option is highlighted. A highlight indicates that the
12630 * item may be selected when a user presses enter or clicks.
12631 *
12632 * @return {boolean} Item is highlighted
12633 */
12634 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12635 return this.highlighted;
12636 };
12637
12638 /**
12639 * Check if the option is pressed. The pressed state occurs when a user mouses
12640 * down on an item, but has not yet let go of the mouse. The item may appear
12641 * selected, but it will not be selected until the user releases the mouse.
12642 *
12643 * @return {boolean} Item is pressed
12644 */
12645 OO.ui.OptionWidget.prototype.isPressed = function () {
12646 return this.pressed;
12647 };
12648
12649 /**
12650 * Set the option’s selected state. In general, all modifications to the selection
12651 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12652 * method instead of this method.
12653 *
12654 * @param {boolean} [state=false] Select option
12655 * @chainable
12656 */
12657 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12658 if ( this.constructor.static.selectable ) {
12659 this.selected = !!state;
12660 this.$element
12661 .toggleClass( 'oo-ui-optionWidget-selected', state )
12662 .attr( 'aria-selected', state.toString() );
12663 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12664 this.scrollElementIntoView();
12665 }
12666 this.updateThemeClasses();
12667 }
12668 return this;
12669 };
12670
12671 /**
12672 * Set the option’s highlighted state. In general, all programmatic
12673 * modifications to the highlight should be handled by the
12674 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12675 * method instead of this method.
12676 *
12677 * @param {boolean} [state=false] Highlight option
12678 * @chainable
12679 */
12680 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12681 if ( this.constructor.static.highlightable ) {
12682 this.highlighted = !!state;
12683 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12684 this.updateThemeClasses();
12685 }
12686 return this;
12687 };
12688
12689 /**
12690 * Set the option’s pressed state. In general, all
12691 * programmatic modifications to the pressed state should be handled by the
12692 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12693 * method instead of this method.
12694 *
12695 * @param {boolean} [state=false] Press option
12696 * @chainable
12697 */
12698 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12699 if ( this.constructor.static.pressable ) {
12700 this.pressed = !!state;
12701 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12702 this.updateThemeClasses();
12703 }
12704 return this;
12705 };
12706
12707 /**
12708 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12709 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12710 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12711 * options. For more information about options and selects, please see the
12712 * [OOjs UI documentation on MediaWiki][1].
12713 *
12714 * @example
12715 * // Decorated options in a select widget
12716 * var select = new OO.ui.SelectWidget( {
12717 * items: [
12718 * new OO.ui.DecoratedOptionWidget( {
12719 * data: 'a',
12720 * label: 'Option with icon',
12721 * icon: 'help'
12722 * } ),
12723 * new OO.ui.DecoratedOptionWidget( {
12724 * data: 'b',
12725 * label: 'Option with indicator',
12726 * indicator: 'next'
12727 * } )
12728 * ]
12729 * } );
12730 * $( 'body' ).append( select.$element );
12731 *
12732 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12733 *
12734 * @class
12735 * @extends OO.ui.OptionWidget
12736 * @mixins OO.ui.IconElement
12737 * @mixins OO.ui.IndicatorElement
12738 *
12739 * @constructor
12740 * @param {Object} [config] Configuration options
12741 */
12742 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
12743 // Parent constructor
12744 OO.ui.DecoratedOptionWidget.super.call( this, config );
12745
12746 // Mixin constructors
12747 OO.ui.IconElement.call( this, config );
12748 OO.ui.IndicatorElement.call( this, config );
12749
12750 // Initialization
12751 this.$element
12752 .addClass( 'oo-ui-decoratedOptionWidget' )
12753 .prepend( this.$icon )
12754 .append( this.$indicator );
12755 };
12756
12757 /* Setup */
12758
12759 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
12760 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
12761 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
12762
12763 /**
12764 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12765 * can be selected and configured with data. The class is
12766 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12767 * [OOjs UI documentation on MediaWiki] [1] for more information.
12768 *
12769 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12770 *
12771 * @class
12772 * @extends OO.ui.DecoratedOptionWidget
12773 * @mixins OO.ui.ButtonElement
12774 * @mixins OO.ui.TabIndexedElement
12775 *
12776 * @constructor
12777 * @param {Object} [config] Configuration options
12778 */
12779 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
12780 // Configuration initialization
12781 config = $.extend( { tabIndex: -1 }, config );
12782
12783 // Parent constructor
12784 OO.ui.ButtonOptionWidget.super.call( this, config );
12785
12786 // Mixin constructors
12787 OO.ui.ButtonElement.call( this, config );
12788 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12789
12790 // Initialization
12791 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
12792 this.$button.append( this.$element.contents() );
12793 this.$element.append( this.$button );
12794 };
12795
12796 /* Setup */
12797
12798 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
12799 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
12800 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
12801
12802 /* Static Properties */
12803
12804 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12805 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
12806
12807 OO.ui.ButtonOptionWidget.static.highlightable = false;
12808
12809 /* Methods */
12810
12811 /**
12812 * @inheritdoc
12813 */
12814 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
12815 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
12816
12817 if ( this.constructor.static.selectable ) {
12818 this.setActive( state );
12819 }
12820
12821 return this;
12822 };
12823
12824 /**
12825 * RadioOptionWidget is an option widget that looks like a radio button.
12826 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12827 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12828 *
12829 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12830 *
12831 * @class
12832 * @extends OO.ui.OptionWidget
12833 *
12834 * @constructor
12835 * @param {Object} [config] Configuration options
12836 */
12837 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
12838 // Configuration initialization
12839 config = config || {};
12840
12841 // Properties (must be done before parent constructor which calls #setDisabled)
12842 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
12843
12844 // Parent constructor
12845 OO.ui.RadioOptionWidget.super.call( this, config );
12846
12847 // Initialization
12848 this.$element
12849 .addClass( 'oo-ui-radioOptionWidget' )
12850 .prepend( this.radio.$element );
12851 };
12852
12853 /* Setup */
12854
12855 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
12856
12857 /* Static Properties */
12858
12859 OO.ui.RadioOptionWidget.static.highlightable = false;
12860
12861 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
12862
12863 OO.ui.RadioOptionWidget.static.pressable = false;
12864
12865 OO.ui.RadioOptionWidget.static.tagName = 'label';
12866
12867 /* Methods */
12868
12869 /**
12870 * @inheritdoc
12871 */
12872 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
12873 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
12874
12875 this.radio.setSelected( state );
12876
12877 return this;
12878 };
12879
12880 /**
12881 * @inheritdoc
12882 */
12883 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
12884 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
12885
12886 this.radio.setDisabled( this.isDisabled() );
12887
12888 return this;
12889 };
12890
12891 /**
12892 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12893 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12894 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12895 *
12896 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12897 *
12898 * @class
12899 * @extends OO.ui.DecoratedOptionWidget
12900 *
12901 * @constructor
12902 * @param {Object} [config] Configuration options
12903 */
12904 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
12905 // Configuration initialization
12906 config = $.extend( { icon: 'check' }, config );
12907
12908 // Parent constructor
12909 OO.ui.MenuOptionWidget.super.call( this, config );
12910
12911 // Initialization
12912 this.$element
12913 .attr( 'role', 'menuitem' )
12914 .addClass( 'oo-ui-menuOptionWidget' );
12915 };
12916
12917 /* Setup */
12918
12919 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
12920
12921 /* Static Properties */
12922
12923 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
12924
12925 /**
12926 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12927 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12928 *
12929 * @example
12930 * var myDropdown = new OO.ui.DropdownWidget( {
12931 * menu: {
12932 * items: [
12933 * new OO.ui.MenuSectionOptionWidget( {
12934 * label: 'Dogs'
12935 * } ),
12936 * new OO.ui.MenuOptionWidget( {
12937 * data: 'corgi',
12938 * label: 'Welsh Corgi'
12939 * } ),
12940 * new OO.ui.MenuOptionWidget( {
12941 * data: 'poodle',
12942 * label: 'Standard Poodle'
12943 * } ),
12944 * new OO.ui.MenuSectionOptionWidget( {
12945 * label: 'Cats'
12946 * } ),
12947 * new OO.ui.MenuOptionWidget( {
12948 * data: 'lion',
12949 * label: 'Lion'
12950 * } )
12951 * ]
12952 * }
12953 * } );
12954 * $( 'body' ).append( myDropdown.$element );
12955 *
12956 *
12957 * @class
12958 * @extends OO.ui.DecoratedOptionWidget
12959 *
12960 * @constructor
12961 * @param {Object} [config] Configuration options
12962 */
12963 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
12964 // Parent constructor
12965 OO.ui.MenuSectionOptionWidget.super.call( this, config );
12966
12967 // Initialization
12968 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
12969 };
12970
12971 /* Setup */
12972
12973 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
12974
12975 /* Static Properties */
12976
12977 OO.ui.MenuSectionOptionWidget.static.selectable = false;
12978
12979 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
12980
12981 /**
12982 * OutlineOptionWidget is an item in an {@link OO.ui.OutlineSelectWidget OutlineSelectWidget}.
12983 *
12984 * Currently, this class is only used by {@link OO.ui.BookletLayout booklet layouts}, which contain
12985 * {@link OO.ui.PageLayout page layouts}. See {@link OO.ui.BookletLayout BookletLayout}
12986 * for an example.
12987 *
12988 * @class
12989 * @extends OO.ui.DecoratedOptionWidget
12990 *
12991 * @constructor
12992 * @param {Object} [config] Configuration options
12993 * @cfg {number} [level] Indentation level
12994 * @cfg {boolean} [movable] Allow modification from {@link OO.ui.OutlineControlsWidget outline controls}.
12995 */
12996 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
12997 // Configuration initialization
12998 config = config || {};
12999
13000 // Parent constructor
13001 OO.ui.OutlineOptionWidget.super.call( this, config );
13002
13003 // Properties
13004 this.level = 0;
13005 this.movable = !!config.movable;
13006 this.removable = !!config.removable;
13007
13008 // Initialization
13009 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
13010 this.setLevel( config.level );
13011 };
13012
13013 /* Setup */
13014
13015 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
13016
13017 /* Static Properties */
13018
13019 OO.ui.OutlineOptionWidget.static.highlightable = false;
13020
13021 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
13022
13023 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
13024
13025 OO.ui.OutlineOptionWidget.static.levels = 3;
13026
13027 /* Methods */
13028
13029 /**
13030 * Check if item is movable.
13031 *
13032 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13033 *
13034 * @return {boolean} Item is movable
13035 */
13036 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
13037 return this.movable;
13038 };
13039
13040 /**
13041 * Check if item is removable.
13042 *
13043 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13044 *
13045 * @return {boolean} Item is removable
13046 */
13047 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
13048 return this.removable;
13049 };
13050
13051 /**
13052 * Get indentation level.
13053 *
13054 * @return {number} Indentation level
13055 */
13056 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
13057 return this.level;
13058 };
13059
13060 /**
13061 * Set movability.
13062 *
13063 * Movability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13064 *
13065 * @param {boolean} movable Item is movable
13066 * @chainable
13067 */
13068 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
13069 this.movable = !!movable;
13070 this.updateThemeClasses();
13071 return this;
13072 };
13073
13074 /**
13075 * Set removability.
13076 *
13077 * Removability is used by {@link OO.ui.OutlineControlsWidget outline controls}.
13078 *
13079 * @param {boolean} movable Item is removable
13080 * @chainable
13081 */
13082 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
13083 this.removable = !!removable;
13084 this.updateThemeClasses();
13085 return this;
13086 };
13087
13088 /**
13089 * Set indentation level.
13090 *
13091 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
13092 * @chainable
13093 */
13094 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
13095 var levels = this.constructor.static.levels,
13096 levelClass = this.constructor.static.levelClass,
13097 i = levels;
13098
13099 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
13100 while ( i-- ) {
13101 if ( this.level === i ) {
13102 this.$element.addClass( levelClass + i );
13103 } else {
13104 this.$element.removeClass( levelClass + i );
13105 }
13106 }
13107 this.updateThemeClasses();
13108
13109 return this;
13110 };
13111
13112 /**
13113 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
13114 * By default, each popup has an anchor that points toward its origin.
13115 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
13116 *
13117 * @example
13118 * // A popup widget.
13119 * var popup = new OO.ui.PopupWidget( {
13120 * $content: $( '<p>Hi there!</p>' ),
13121 * padded: true,
13122 * width: 300
13123 * } );
13124 *
13125 * $( 'body' ).append( popup.$element );
13126 * // To display the popup, toggle the visibility to 'true'.
13127 * popup.toggle( true );
13128 *
13129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
13130 *
13131 * @class
13132 * @extends OO.ui.Widget
13133 * @mixins OO.ui.LabelElement
13134 *
13135 * @constructor
13136 * @param {Object} [config] Configuration options
13137 * @cfg {number} [width=320] Width of popup in pixels
13138 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
13139 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
13140 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
13141 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
13142 * For left-aligned popups, the left edge is aligned to the anchor.
13143 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
13144 * See the [OOjs UI docs on MediaWiki][3] for an example.
13145 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
13146 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
13147 * @cfg {jQuery} [$content] Content to append to the popup's body
13148 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
13149 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
13150 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
13151 * for an example.
13152 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13153 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13154 * button.
13155 * @cfg {boolean} [padded] Add padding to the popup's body
13156 */
13157 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
13158 // Configuration initialization
13159 config = config || {};
13160
13161 // Parent constructor
13162 OO.ui.PopupWidget.super.call( this, config );
13163
13164 // Properties (must be set before ClippableElement constructor call)
13165 this.$body = $( '<div>' );
13166
13167 // Mixin constructors
13168 OO.ui.LabelElement.call( this, config );
13169 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
13170
13171 // Properties
13172 this.$popup = $( '<div>' );
13173 this.$head = $( '<div>' );
13174 this.$anchor = $( '<div>' );
13175 // If undefined, will be computed lazily in updateDimensions()
13176 this.$container = config.$container;
13177 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
13178 this.autoClose = !!config.autoClose;
13179 this.$autoCloseIgnore = config.$autoCloseIgnore;
13180 this.transitionTimeout = null;
13181 this.anchor = null;
13182 this.width = config.width !== undefined ? config.width : 320;
13183 this.height = config.height !== undefined ? config.height : null;
13184 this.align = config.align || 'center';
13185 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
13186 this.onMouseDownHandler = this.onMouseDown.bind( this );
13187 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
13188
13189 // Events
13190 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
13191
13192 // Initialization
13193 this.toggleAnchor( config.anchor === undefined || config.anchor );
13194 this.$body.addClass( 'oo-ui-popupWidget-body' );
13195 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
13196 this.$head
13197 .addClass( 'oo-ui-popupWidget-head' )
13198 .append( this.$label, this.closeButton.$element );
13199 if ( !config.head ) {
13200 this.$head.addClass( 'oo-ui-element-hidden' );
13201 }
13202 this.$popup
13203 .addClass( 'oo-ui-popupWidget-popup' )
13204 .append( this.$head, this.$body );
13205 this.$element
13206 .addClass( 'oo-ui-popupWidget' )
13207 .append( this.$popup, this.$anchor );
13208 // Move content, which was added to #$element by OO.ui.Widget, to the body
13209 if ( config.$content instanceof jQuery ) {
13210 this.$body.append( config.$content );
13211 }
13212 if ( config.padded ) {
13213 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
13214 }
13215
13216 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13217 // that reference properties not initialized at that time of parent class construction
13218 // TODO: Find a better way to handle post-constructor setup
13219 this.visible = false;
13220 this.$element.addClass( 'oo-ui-element-hidden' );
13221 };
13222
13223 /* Setup */
13224
13225 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
13226 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
13227 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
13228
13229 /* Methods */
13230
13231 /**
13232 * Handles mouse down events.
13233 *
13234 * @private
13235 * @param {MouseEvent} e Mouse down event
13236 */
13237 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
13238 if (
13239 this.isVisible() &&
13240 !$.contains( this.$element[ 0 ], e.target ) &&
13241 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
13242 ) {
13243 this.toggle( false );
13244 }
13245 };
13246
13247 /**
13248 * Bind mouse down listener.
13249 *
13250 * @private
13251 */
13252 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
13253 // Capture clicks outside popup
13254 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
13255 };
13256
13257 /**
13258 * Handles close button click events.
13259 *
13260 * @private
13261 */
13262 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
13263 if ( this.isVisible() ) {
13264 this.toggle( false );
13265 }
13266 };
13267
13268 /**
13269 * Unbind mouse down listener.
13270 *
13271 * @private
13272 */
13273 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
13274 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
13275 };
13276
13277 /**
13278 * Handles key down events.
13279 *
13280 * @private
13281 * @param {KeyboardEvent} e Key down event
13282 */
13283 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
13284 if (
13285 e.which === OO.ui.Keys.ESCAPE &&
13286 this.isVisible()
13287 ) {
13288 this.toggle( false );
13289 e.preventDefault();
13290 e.stopPropagation();
13291 }
13292 };
13293
13294 /**
13295 * Bind key down listener.
13296 *
13297 * @private
13298 */
13299 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
13300 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13301 };
13302
13303 /**
13304 * Unbind key down listener.
13305 *
13306 * @private
13307 */
13308 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
13309 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13310 };
13311
13312 /**
13313 * Show, hide, or toggle the visibility of the anchor.
13314 *
13315 * @param {boolean} [show] Show anchor, omit to toggle
13316 */
13317 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
13318 show = show === undefined ? !this.anchored : !!show;
13319
13320 if ( this.anchored !== show ) {
13321 if ( show ) {
13322 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
13323 } else {
13324 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
13325 }
13326 this.anchored = show;
13327 }
13328 };
13329
13330 /**
13331 * Check if the anchor is visible.
13332 *
13333 * @return {boolean} Anchor is visible
13334 */
13335 OO.ui.PopupWidget.prototype.hasAnchor = function () {
13336 return this.anchor;
13337 };
13338
13339 /**
13340 * @inheritdoc
13341 */
13342 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
13343 show = show === undefined ? !this.isVisible() : !!show;
13344
13345 var change = show !== this.isVisible();
13346
13347 // Parent method
13348 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
13349
13350 if ( change ) {
13351 if ( show ) {
13352 if ( this.autoClose ) {
13353 this.bindMouseDownListener();
13354 this.bindKeyDownListener();
13355 }
13356 this.updateDimensions();
13357 this.toggleClipping( true );
13358 } else {
13359 this.toggleClipping( false );
13360 if ( this.autoClose ) {
13361 this.unbindMouseDownListener();
13362 this.unbindKeyDownListener();
13363 }
13364 }
13365 }
13366
13367 return this;
13368 };
13369
13370 /**
13371 * Set the size of the popup.
13372 *
13373 * Changing the size may also change the popup's position depending on the alignment.
13374 *
13375 * @param {number} width Width in pixels
13376 * @param {number} height Height in pixels
13377 * @param {boolean} [transition=false] Use a smooth transition
13378 * @chainable
13379 */
13380 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
13381 this.width = width;
13382 this.height = height !== undefined ? height : null;
13383 if ( this.isVisible() ) {
13384 this.updateDimensions( transition );
13385 }
13386 };
13387
13388 /**
13389 * Update the size and position.
13390 *
13391 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13392 * be called automatically.
13393 *
13394 * @param {boolean} [transition=false] Use a smooth transition
13395 * @chainable
13396 */
13397 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
13398 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
13399 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
13400 widget = this;
13401
13402 if ( !this.$container ) {
13403 // Lazy-initialize $container if not specified in constructor
13404 this.$container = $( this.getClosestScrollableElementContainer() );
13405 }
13406
13407 // Set height and width before measuring things, since it might cause our measurements
13408 // to change (e.g. due to scrollbars appearing or disappearing)
13409 this.$popup.css( {
13410 width: this.width,
13411 height: this.height !== null ? this.height : 'auto'
13412 } );
13413
13414 // Compute initial popupOffset based on alignment
13415 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
13416
13417 // Figure out if this will cause the popup to go beyond the edge of the container
13418 originOffset = this.$element.offset().left;
13419 containerLeft = this.$container.offset().left;
13420 containerWidth = this.$container.innerWidth();
13421 containerRight = containerLeft + containerWidth;
13422 popupLeft = popupOffset - this.containerPadding;
13423 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
13424 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
13425 overlapRight = containerRight - ( originOffset + popupRight );
13426
13427 // Adjust offset to make the popup not go beyond the edge, if needed
13428 if ( overlapRight < 0 ) {
13429 popupOffset += overlapRight;
13430 } else if ( overlapLeft < 0 ) {
13431 popupOffset -= overlapLeft;
13432 }
13433
13434 // Adjust offset to avoid anchor being rendered too close to the edge
13435 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13436 // TODO: Find a measurement that works for CSS anchors and image anchors
13437 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
13438 if ( popupOffset + this.width < anchorWidth ) {
13439 popupOffset = anchorWidth - this.width;
13440 } else if ( -popupOffset < anchorWidth ) {
13441 popupOffset = -anchorWidth;
13442 }
13443
13444 // Prevent transition from being interrupted
13445 clearTimeout( this.transitionTimeout );
13446 if ( transition ) {
13447 // Enable transition
13448 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
13449 }
13450
13451 // Position body relative to anchor
13452 this.$popup.css( 'margin-left', popupOffset );
13453
13454 if ( transition ) {
13455 // Prevent transitioning after transition is complete
13456 this.transitionTimeout = setTimeout( function () {
13457 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13458 }, 200 );
13459 } else {
13460 // Prevent transitioning immediately
13461 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13462 }
13463
13464 // Reevaluate clipping state since we've relocated and resized the popup
13465 this.clip();
13466
13467 return this;
13468 };
13469
13470 /**
13471 * Progress bars visually display the status of an operation, such as a download,
13472 * and can be either determinate or indeterminate:
13473 *
13474 * - **determinate** process bars show the percent of an operation that is complete.
13475 *
13476 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13477 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13478 * not use percentages.
13479 *
13480 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13481 *
13482 * @example
13483 * // Examples of determinate and indeterminate progress bars.
13484 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13485 * progress: 33
13486 * } );
13487 * var progressBar2 = new OO.ui.ProgressBarWidget();
13488 *
13489 * // Create a FieldsetLayout to layout progress bars
13490 * var fieldset = new OO.ui.FieldsetLayout;
13491 * fieldset.addItems( [
13492 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13493 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13494 * ] );
13495 * $( 'body' ).append( fieldset.$element );
13496 *
13497 * @class
13498 * @extends OO.ui.Widget
13499 *
13500 * @constructor
13501 * @param {Object} [config] Configuration options
13502 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13503 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13504 * By default, the progress bar is indeterminate.
13505 */
13506 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
13507 // Configuration initialization
13508 config = config || {};
13509
13510 // Parent constructor
13511 OO.ui.ProgressBarWidget.super.call( this, config );
13512
13513 // Properties
13514 this.$bar = $( '<div>' );
13515 this.progress = null;
13516
13517 // Initialization
13518 this.setProgress( config.progress !== undefined ? config.progress : false );
13519 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
13520 this.$element
13521 .attr( {
13522 role: 'progressbar',
13523 'aria-valuemin': 0,
13524 'aria-valuemax': 100
13525 } )
13526 .addClass( 'oo-ui-progressBarWidget' )
13527 .append( this.$bar );
13528 };
13529
13530 /* Setup */
13531
13532 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
13533
13534 /* Static Properties */
13535
13536 OO.ui.ProgressBarWidget.static.tagName = 'div';
13537
13538 /* Methods */
13539
13540 /**
13541 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13542 *
13543 * @return {number|boolean} Progress percent
13544 */
13545 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
13546 return this.progress;
13547 };
13548
13549 /**
13550 * Set the percent of the process completed or `false` for an indeterminate process.
13551 *
13552 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13553 */
13554 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
13555 this.progress = progress;
13556
13557 if ( progress !== false ) {
13558 this.$bar.css( 'width', this.progress + '%' );
13559 this.$element.attr( 'aria-valuenow', this.progress );
13560 } else {
13561 this.$bar.css( 'width', '' );
13562 this.$element.removeAttr( 'aria-valuenow' );
13563 }
13564 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
13565 };
13566
13567 /**
13568 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13569 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13570 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13571 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13572 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13573 *
13574 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13575 * the [OOjs UI demos][1] for an example.
13576 *
13577 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13578 *
13579 * @class
13580 * @extends OO.ui.Widget
13581 *
13582 * @constructor
13583 * @param {Object} [config] Configuration options
13584 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13585 * @cfg {string} [value] Initial query value
13586 */
13587 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
13588 // Configuration initialization
13589 config = config || {};
13590
13591 // Parent constructor
13592 OO.ui.SearchWidget.super.call( this, config );
13593
13594 // Properties
13595 this.query = new OO.ui.TextInputWidget( {
13596 icon: 'search',
13597 placeholder: config.placeholder,
13598 value: config.value
13599 } );
13600 this.results = new OO.ui.SelectWidget();
13601 this.$query = $( '<div>' );
13602 this.$results = $( '<div>' );
13603
13604 // Events
13605 this.query.connect( this, {
13606 change: 'onQueryChange',
13607 enter: 'onQueryEnter'
13608 } );
13609 this.results.connect( this, {
13610 highlight: 'onResultsHighlight',
13611 select: 'onResultsSelect'
13612 } );
13613 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
13614
13615 // Initialization
13616 this.$query
13617 .addClass( 'oo-ui-searchWidget-query' )
13618 .append( this.query.$element );
13619 this.$results
13620 .addClass( 'oo-ui-searchWidget-results' )
13621 .append( this.results.$element );
13622 this.$element
13623 .addClass( 'oo-ui-searchWidget' )
13624 .append( this.$results, this.$query );
13625 };
13626
13627 /* Setup */
13628
13629 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
13630
13631 /* Events */
13632
13633 /**
13634 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13635 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13636 * string is typed into the query field instead, the first menu item that matches the query
13637 * will be highlighted.
13638
13639 * @event highlight
13640 * @deprecated Connect straight to getResults() events instead
13641 * @param {Object|null} item Item data or null if no item is highlighted
13642 */
13643
13644 /**
13645 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13646 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13647 *
13648 * @event select
13649 * @deprecated Connect straight to getResults() events instead
13650 * @param {Object|null} item Item data or null if no item is selected
13651 */
13652
13653 /* Methods */
13654
13655 /**
13656 * Handle query key down events.
13657 *
13658 * @private
13659 * @param {jQuery.Event} e Key down event
13660 */
13661 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
13662 var highlightedItem, nextItem,
13663 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
13664
13665 if ( dir ) {
13666 highlightedItem = this.results.getHighlightedItem();
13667 if ( !highlightedItem ) {
13668 highlightedItem = this.results.getSelectedItem();
13669 }
13670 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
13671 this.results.highlightItem( nextItem );
13672 nextItem.scrollElementIntoView();
13673 }
13674 };
13675
13676 /**
13677 * Handle select widget select events.
13678 *
13679 * Clears existing results. Subclasses should repopulate items according to new query.
13680 *
13681 * @private
13682 * @param {string} value New value
13683 */
13684 OO.ui.SearchWidget.prototype.onQueryChange = function () {
13685 // Reset
13686 this.results.clearItems();
13687 };
13688
13689 /**
13690 * Handle select widget enter key events.
13691 *
13692 * Selects highlighted item.
13693 *
13694 * @private
13695 * @param {string} value New value
13696 */
13697 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
13698 // Reset
13699 this.results.selectItem( this.results.getHighlightedItem() );
13700 };
13701
13702 /**
13703 * Handle select widget highlight events.
13704 *
13705 * @private
13706 * @deprecated Connect straight to getResults() events instead
13707 * @param {OO.ui.OptionWidget} item Highlighted item
13708 * @fires highlight
13709 */
13710 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
13711 this.emit( 'highlight', item ? item.getData() : null );
13712 };
13713
13714 /**
13715 * Handle select widget select events.
13716 *
13717 * @private
13718 * @deprecated Connect straight to getResults() events instead
13719 * @param {OO.ui.OptionWidget} item Selected item
13720 * @fires select
13721 */
13722 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
13723 this.emit( 'select', item ? item.getData() : null );
13724 };
13725
13726 /**
13727 * Get the query input.
13728 *
13729 * @return {OO.ui.TextInputWidget} Query input
13730 */
13731 OO.ui.SearchWidget.prototype.getQuery = function () {
13732 return this.query;
13733 };
13734
13735 /**
13736 * Get the search results menu.
13737 *
13738 * @return {OO.ui.SelectWidget} Menu of search results
13739 */
13740 OO.ui.SearchWidget.prototype.getResults = function () {
13741 return this.results;
13742 };
13743
13744 /**
13745 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13746 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13747 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13748 * menu selects}.
13749 *
13750 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13751 * information, please see the [OOjs UI documentation on MediaWiki][1].
13752 *
13753 * @example
13754 * // Example of a select widget with three options
13755 * var select = new OO.ui.SelectWidget( {
13756 * items: [
13757 * new OO.ui.OptionWidget( {
13758 * data: 'a',
13759 * label: 'Option One',
13760 * } ),
13761 * new OO.ui.OptionWidget( {
13762 * data: 'b',
13763 * label: 'Option Two',
13764 * } ),
13765 * new OO.ui.OptionWidget( {
13766 * data: 'c',
13767 * label: 'Option Three',
13768 * } )
13769 * ]
13770 * } );
13771 * $( 'body' ).append( select.$element );
13772 *
13773 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13774 *
13775 * @class
13776 * @extends OO.ui.Widget
13777 * @mixins OO.ui.GroupElement
13778 *
13779 * @constructor
13780 * @param {Object} [config] Configuration options
13781 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13782 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13783 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13784 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13785 */
13786 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
13787 // Configuration initialization
13788 config = config || {};
13789
13790 // Parent constructor
13791 OO.ui.SelectWidget.super.call( this, config );
13792
13793 // Mixin constructors
13794 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
13795
13796 // Properties
13797 this.pressed = false;
13798 this.selecting = null;
13799 this.onMouseUpHandler = this.onMouseUp.bind( this );
13800 this.onMouseMoveHandler = this.onMouseMove.bind( this );
13801 this.onKeyDownHandler = this.onKeyDown.bind( this );
13802
13803 // Events
13804 this.$element.on( {
13805 mousedown: this.onMouseDown.bind( this ),
13806 mouseover: this.onMouseOver.bind( this ),
13807 mouseleave: this.onMouseLeave.bind( this )
13808 } );
13809
13810 // Initialization
13811 this.$element
13812 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13813 .attr( 'role', 'listbox' );
13814 if ( Array.isArray( config.items ) ) {
13815 this.addItems( config.items );
13816 }
13817 };
13818
13819 /* Setup */
13820
13821 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
13822
13823 // Need to mixin base class as well
13824 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
13825 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
13826
13827 /* Events */
13828
13829 /**
13830 * @event highlight
13831 *
13832 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13833 *
13834 * @param {OO.ui.OptionWidget|null} item Highlighted item
13835 */
13836
13837 /**
13838 * @event press
13839 *
13840 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13841 * pressed state of an option.
13842 *
13843 * @param {OO.ui.OptionWidget|null} item Pressed item
13844 */
13845
13846 /**
13847 * @event select
13848 *
13849 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13850 *
13851 * @param {OO.ui.OptionWidget|null} item Selected item
13852 */
13853
13854 /**
13855 * @event choose
13856 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13857 * @param {OO.ui.OptionWidget} item Chosen item
13858 */
13859
13860 /**
13861 * @event add
13862 *
13863 * An `add` event is emitted when options are added to the select with the #addItems method.
13864 *
13865 * @param {OO.ui.OptionWidget[]} items Added items
13866 * @param {number} index Index of insertion point
13867 */
13868
13869 /**
13870 * @event remove
13871 *
13872 * A `remove` event is emitted when options are removed from the select with the #clearItems
13873 * or #removeItems methods.
13874 *
13875 * @param {OO.ui.OptionWidget[]} items Removed items
13876 */
13877
13878 /* Methods */
13879
13880 /**
13881 * Handle mouse down events.
13882 *
13883 * @private
13884 * @param {jQuery.Event} e Mouse down event
13885 */
13886 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
13887 var item;
13888
13889 if ( !this.isDisabled() && e.which === 1 ) {
13890 this.togglePressed( true );
13891 item = this.getTargetItem( e );
13892 if ( item && item.isSelectable() ) {
13893 this.pressItem( item );
13894 this.selecting = item;
13895 this.getElementDocument().addEventListener(
13896 'mouseup',
13897 this.onMouseUpHandler,
13898 true
13899 );
13900 this.getElementDocument().addEventListener(
13901 'mousemove',
13902 this.onMouseMoveHandler,
13903 true
13904 );
13905 }
13906 }
13907 return false;
13908 };
13909
13910 /**
13911 * Handle mouse up events.
13912 *
13913 * @private
13914 * @param {jQuery.Event} e Mouse up event
13915 */
13916 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
13917 var item;
13918
13919 this.togglePressed( false );
13920 if ( !this.selecting ) {
13921 item = this.getTargetItem( e );
13922 if ( item && item.isSelectable() ) {
13923 this.selecting = item;
13924 }
13925 }
13926 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
13927 this.pressItem( null );
13928 this.chooseItem( this.selecting );
13929 this.selecting = null;
13930 }
13931
13932 this.getElementDocument().removeEventListener(
13933 'mouseup',
13934 this.onMouseUpHandler,
13935 true
13936 );
13937 this.getElementDocument().removeEventListener(
13938 'mousemove',
13939 this.onMouseMoveHandler,
13940 true
13941 );
13942
13943 return false;
13944 };
13945
13946 /**
13947 * Handle mouse move events.
13948 *
13949 * @private
13950 * @param {jQuery.Event} e Mouse move event
13951 */
13952 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
13953 var item;
13954
13955 if ( !this.isDisabled() && this.pressed ) {
13956 item = this.getTargetItem( e );
13957 if ( item && item !== this.selecting && item.isSelectable() ) {
13958 this.pressItem( item );
13959 this.selecting = item;
13960 }
13961 }
13962 return false;
13963 };
13964
13965 /**
13966 * Handle mouse over events.
13967 *
13968 * @private
13969 * @param {jQuery.Event} e Mouse over event
13970 */
13971 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
13972 var item;
13973
13974 if ( !this.isDisabled() ) {
13975 item = this.getTargetItem( e );
13976 this.highlightItem( item && item.isHighlightable() ? item : null );
13977 }
13978 return false;
13979 };
13980
13981 /**
13982 * Handle mouse leave events.
13983 *
13984 * @private
13985 * @param {jQuery.Event} e Mouse over event
13986 */
13987 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
13988 if ( !this.isDisabled() ) {
13989 this.highlightItem( null );
13990 }
13991 return false;
13992 };
13993
13994 /**
13995 * Handle key down events.
13996 *
13997 * @protected
13998 * @param {jQuery.Event} e Key down event
13999 */
14000 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
14001 var nextItem,
14002 handled = false,
14003 currentItem = this.getHighlightedItem() || this.getSelectedItem();
14004
14005 if ( !this.isDisabled() && this.isVisible() ) {
14006 switch ( e.keyCode ) {
14007 case OO.ui.Keys.ENTER:
14008 if ( currentItem && currentItem.constructor.static.highlightable ) {
14009 // Was only highlighted, now let's select it. No-op if already selected.
14010 this.chooseItem( currentItem );
14011 handled = true;
14012 }
14013 break;
14014 case OO.ui.Keys.UP:
14015 case OO.ui.Keys.LEFT:
14016 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
14017 handled = true;
14018 break;
14019 case OO.ui.Keys.DOWN:
14020 case OO.ui.Keys.RIGHT:
14021 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
14022 handled = true;
14023 break;
14024 case OO.ui.Keys.ESCAPE:
14025 case OO.ui.Keys.TAB:
14026 if ( currentItem && currentItem.constructor.static.highlightable ) {
14027 currentItem.setHighlighted( false );
14028 }
14029 this.unbindKeyDownListener();
14030 // Don't prevent tabbing away / defocusing
14031 handled = false;
14032 break;
14033 }
14034
14035 if ( nextItem ) {
14036 if ( nextItem.constructor.static.highlightable ) {
14037 this.highlightItem( nextItem );
14038 } else {
14039 this.chooseItem( nextItem );
14040 }
14041 nextItem.scrollElementIntoView();
14042 }
14043
14044 if ( handled ) {
14045 // Can't just return false, because e is not always a jQuery event
14046 e.preventDefault();
14047 e.stopPropagation();
14048 }
14049 }
14050 };
14051
14052 /**
14053 * Bind key down listener.
14054 *
14055 * @protected
14056 */
14057 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
14058 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
14059 };
14060
14061 /**
14062 * Unbind key down listener.
14063 *
14064 * @protected
14065 */
14066 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
14067 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
14068 };
14069
14070 /**
14071 * Get the closest item to a jQuery.Event.
14072 *
14073 * @private
14074 * @param {jQuery.Event} e
14075 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
14076 */
14077 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
14078 var $item = $( e.target ).closest( '.oo-ui-optionWidget' );
14079 if ( $item.length ) {
14080 return $item.data( 'oo-ui-optionWidget' );
14081 }
14082 return null;
14083 };
14084
14085 /**
14086 * Get selected item.
14087 *
14088 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
14089 */
14090 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
14091 var i, len;
14092
14093 for ( i = 0, len = this.items.length; i < len; i++ ) {
14094 if ( this.items[ i ].isSelected() ) {
14095 return this.items[ i ];
14096 }
14097 }
14098 return null;
14099 };
14100
14101 /**
14102 * Get highlighted item.
14103 *
14104 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
14105 */
14106 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
14107 var i, len;
14108
14109 for ( i = 0, len = this.items.length; i < len; i++ ) {
14110 if ( this.items[ i ].isHighlighted() ) {
14111 return this.items[ i ];
14112 }
14113 }
14114 return null;
14115 };
14116
14117 /**
14118 * Toggle pressed state.
14119 *
14120 * Press is a state that occurs when a user mouses down on an item, but
14121 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
14122 * until the user releases the mouse.
14123 *
14124 * @param {boolean} pressed An option is being pressed
14125 */
14126 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
14127 if ( pressed === undefined ) {
14128 pressed = !this.pressed;
14129 }
14130 if ( pressed !== this.pressed ) {
14131 this.$element
14132 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
14133 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
14134 this.pressed = pressed;
14135 }
14136 };
14137
14138 /**
14139 * Highlight an option. If the `item` param is omitted, no options will be highlighted
14140 * and any existing highlight will be removed. The highlight is mutually exclusive.
14141 *
14142 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
14143 * @fires highlight
14144 * @chainable
14145 */
14146 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
14147 var i, len, highlighted,
14148 changed = false;
14149
14150 for ( i = 0, len = this.items.length; i < len; i++ ) {
14151 highlighted = this.items[ i ] === item;
14152 if ( this.items[ i ].isHighlighted() !== highlighted ) {
14153 this.items[ i ].setHighlighted( highlighted );
14154 changed = true;
14155 }
14156 }
14157 if ( changed ) {
14158 this.emit( 'highlight', item );
14159 }
14160
14161 return this;
14162 };
14163
14164 /**
14165 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14166 * all options will be deselected.
14167 *
14168 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14169 * @fires select
14170 * @chainable
14171 */
14172 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
14173 var i, len, selected,
14174 changed = false;
14175
14176 for ( i = 0, len = this.items.length; i < len; i++ ) {
14177 selected = this.items[ i ] === item;
14178 if ( this.items[ i ].isSelected() !== selected ) {
14179 this.items[ i ].setSelected( selected );
14180 changed = true;
14181 }
14182 }
14183 if ( changed ) {
14184 this.emit( 'select', item );
14185 }
14186
14187 return this;
14188 };
14189
14190 /**
14191 * Press an item.
14192 *
14193 * Press is a state that occurs when a user mouses down on an item, but has not
14194 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14195 * releases the mouse.
14196 *
14197 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14198 * @fires press
14199 * @chainable
14200 */
14201 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
14202 var i, len, pressed,
14203 changed = false;
14204
14205 for ( i = 0, len = this.items.length; i < len; i++ ) {
14206 pressed = this.items[ i ] === item;
14207 if ( this.items[ i ].isPressed() !== pressed ) {
14208 this.items[ i ].setPressed( pressed );
14209 changed = true;
14210 }
14211 }
14212 if ( changed ) {
14213 this.emit( 'press', item );
14214 }
14215
14216 return this;
14217 };
14218
14219 /**
14220 * Choose an item.
14221 *
14222 * Note that ‘choose’ should never be modified programmatically. A user can choose
14223 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14224 * use the #selectItem method.
14225 *
14226 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14227 * when users choose an item with the keyboard or mouse.
14228 *
14229 * @param {OO.ui.OptionWidget} item Item to choose
14230 * @fires choose
14231 * @chainable
14232 */
14233 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
14234 this.selectItem( item );
14235 this.emit( 'choose', item );
14236
14237 return this;
14238 };
14239
14240 /**
14241 * Get an option by its position relative to the specified item (or to the start of the option array,
14242 * if item is `null`). The direction in which to search through the option array is specified with a
14243 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14244 * `null` if there are no options in the array.
14245 *
14246 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14247 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14248 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14249 */
14250 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
14251 var currentIndex, nextIndex, i,
14252 increase = direction > 0 ? 1 : -1,
14253 len = this.items.length;
14254
14255 if ( item instanceof OO.ui.OptionWidget ) {
14256 currentIndex = $.inArray( item, this.items );
14257 nextIndex = ( currentIndex + increase + len ) % len;
14258 } else {
14259 // If no item is selected and moving forward, start at the beginning.
14260 // If moving backward, start at the end.
14261 nextIndex = direction > 0 ? 0 : len - 1;
14262 }
14263
14264 for ( i = 0; i < len; i++ ) {
14265 item = this.items[ nextIndex ];
14266 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14267 return item;
14268 }
14269 nextIndex = ( nextIndex + increase + len ) % len;
14270 }
14271 return null;
14272 };
14273
14274 /**
14275 * Get the next selectable item or `null` if there are no selectable items.
14276 * Disabled options and menu-section markers and breaks are not selectable.
14277 *
14278 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14279 */
14280 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
14281 var i, len, item;
14282
14283 for ( i = 0, len = this.items.length; i < len; i++ ) {
14284 item = this.items[ i ];
14285 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14286 return item;
14287 }
14288 }
14289
14290 return null;
14291 };
14292
14293 /**
14294 * Add an array of options to the select. Optionally, an index number can be used to
14295 * specify an insertion point.
14296 *
14297 * @param {OO.ui.OptionWidget[]} items Items to add
14298 * @param {number} [index] Index to insert items after
14299 * @fires add
14300 * @chainable
14301 */
14302 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
14303 // Mixin method
14304 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
14305
14306 // Always provide an index, even if it was omitted
14307 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
14308
14309 return this;
14310 };
14311
14312 /**
14313 * Remove the specified array of options from the select. Options will be detached
14314 * from the DOM, not removed, so they can be reused later. To remove all options from
14315 * the select, you may wish to use the #clearItems method instead.
14316 *
14317 * @param {OO.ui.OptionWidget[]} items Items to remove
14318 * @fires remove
14319 * @chainable
14320 */
14321 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
14322 var i, len, item;
14323
14324 // Deselect items being removed
14325 for ( i = 0, len = items.length; i < len; i++ ) {
14326 item = items[ i ];
14327 if ( item.isSelected() ) {
14328 this.selectItem( null );
14329 }
14330 }
14331
14332 // Mixin method
14333 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
14334
14335 this.emit( 'remove', items );
14336
14337 return this;
14338 };
14339
14340 /**
14341 * Clear all options from the select. Options will be detached from the DOM, not removed,
14342 * so that they can be reused later. To remove a subset of options from the select, use
14343 * the #removeItems method.
14344 *
14345 * @fires remove
14346 * @chainable
14347 */
14348 OO.ui.SelectWidget.prototype.clearItems = function () {
14349 var items = this.items.slice();
14350
14351 // Mixin method
14352 OO.ui.GroupWidget.prototype.clearItems.call( this );
14353
14354 // Clear selection
14355 this.selectItem( null );
14356
14357 this.emit( 'remove', items );
14358
14359 return this;
14360 };
14361
14362 /**
14363 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14364 * button options and is used together with
14365 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14366 * highlighting, choosing, and selecting mutually exclusive options. Please see
14367 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14368 *
14369 * @example
14370 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14371 * var option1 = new OO.ui.ButtonOptionWidget( {
14372 * data: 1,
14373 * label: 'Option 1',
14374 * title: 'Button option 1'
14375 * } );
14376 *
14377 * var option2 = new OO.ui.ButtonOptionWidget( {
14378 * data: 2,
14379 * label: 'Option 2',
14380 * title: 'Button option 2'
14381 * } );
14382 *
14383 * var option3 = new OO.ui.ButtonOptionWidget( {
14384 * data: 3,
14385 * label: 'Option 3',
14386 * title: 'Button option 3'
14387 * } );
14388 *
14389 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14390 * items: [ option1, option2, option3 ]
14391 * } );
14392 * $( 'body' ).append( buttonSelect.$element );
14393 *
14394 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14395 *
14396 * @class
14397 * @extends OO.ui.SelectWidget
14398 * @mixins OO.ui.TabIndexedElement
14399 *
14400 * @constructor
14401 * @param {Object} [config] Configuration options
14402 */
14403 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
14404 // Parent constructor
14405 OO.ui.ButtonSelectWidget.super.call( this, config );
14406
14407 // Mixin constructors
14408 OO.ui.TabIndexedElement.call( this, config );
14409
14410 // Events
14411 this.$element.on( {
14412 focus: this.bindKeyDownListener.bind( this ),
14413 blur: this.unbindKeyDownListener.bind( this )
14414 } );
14415
14416 // Initialization
14417 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
14418 };
14419
14420 /* Setup */
14421
14422 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
14423 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
14424
14425 /**
14426 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14427 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14428 * an interface for adding, removing and selecting options.
14429 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14430 *
14431 * @example
14432 * // A RadioSelectWidget with RadioOptions.
14433 * var option1 = new OO.ui.RadioOptionWidget( {
14434 * data: 'a',
14435 * label: 'Selected radio option'
14436 * } );
14437 *
14438 * var option2 = new OO.ui.RadioOptionWidget( {
14439 * data: 'b',
14440 * label: 'Unselected radio option'
14441 * } );
14442 *
14443 * var radioSelect=new OO.ui.RadioSelectWidget( {
14444 * items: [ option1, option2 ]
14445 * } );
14446 *
14447 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14448 * radioSelect.selectItem( option1 );
14449 *
14450 * $( 'body' ).append( radioSelect.$element );
14451 *
14452 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14453
14454 *
14455 * @class
14456 * @extends OO.ui.SelectWidget
14457 * @mixins OO.ui.TabIndexedElement
14458 *
14459 * @constructor
14460 * @param {Object} [config] Configuration options
14461 */
14462 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
14463 // Parent constructor
14464 OO.ui.RadioSelectWidget.super.call( this, config );
14465
14466 // Mixin constructors
14467 OO.ui.TabIndexedElement.call( this, config );
14468
14469 // Events
14470 this.$element.on( {
14471 focus: this.bindKeyDownListener.bind( this ),
14472 blur: this.unbindKeyDownListener.bind( this )
14473 } );
14474
14475 // Initialization
14476 this.$element.addClass( 'oo-ui-radioSelectWidget' );
14477 };
14478
14479 /* Setup */
14480
14481 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
14482 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
14483
14484 /**
14485 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14486 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14487 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14488 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14489 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14490 * and customized to be opened, closed, and displayed as needed.
14491 *
14492 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14493 * mouse outside the menu.
14494 *
14495 * Menus also have support for keyboard interaction:
14496 *
14497 * - Enter/Return key: choose and select a menu option
14498 * - Up-arrow key: highlight the previous menu option
14499 * - Down-arrow key: highlight the next menu option
14500 * - Esc key: hide the menu
14501 *
14502 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14503 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14504 *
14505 * @class
14506 * @extends OO.ui.SelectWidget
14507 * @mixins OO.ui.ClippableElement
14508 *
14509 * @constructor
14510 * @param {Object} [config] Configuration options
14511 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14512 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14513 * and {@link OO.ui.LookupElement LookupElement}
14514 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14515 * anywhere on the page outside of this widget, the menu is hidden.
14516 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14517 */
14518 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
14519 // Configuration initialization
14520 config = config || {};
14521
14522 // Parent constructor
14523 OO.ui.MenuSelectWidget.super.call( this, config );
14524
14525 // Mixin constructors
14526 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
14527
14528 // Properties
14529 this.newItems = null;
14530 this.autoHide = config.autoHide === undefined || !!config.autoHide;
14531 this.$input = config.input ? config.input.$input : null;
14532 this.$widget = config.widget ? config.widget.$element : null;
14533 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
14534
14535 // Initialization
14536 this.$element
14537 .addClass( 'oo-ui-menuSelectWidget' )
14538 .attr( 'role', 'menu' );
14539
14540 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14541 // that reference properties not initialized at that time of parent class construction
14542 // TODO: Find a better way to handle post-constructor setup
14543 this.visible = false;
14544 this.$element.addClass( 'oo-ui-element-hidden' );
14545 };
14546
14547 /* Setup */
14548
14549 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
14550 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
14551
14552 /* Methods */
14553
14554 /**
14555 * Handles document mouse down events.
14556 *
14557 * @protected
14558 * @param {jQuery.Event} e Key down event
14559 */
14560 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
14561 if (
14562 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
14563 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
14564 ) {
14565 this.toggle( false );
14566 }
14567 };
14568
14569 /**
14570 * @inheritdoc
14571 */
14572 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
14573 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
14574
14575 if ( !this.isDisabled() && this.isVisible() ) {
14576 switch ( e.keyCode ) {
14577 case OO.ui.Keys.LEFT:
14578 case OO.ui.Keys.RIGHT:
14579 // Do nothing if a text field is associated, arrow keys will be handled natively
14580 if ( !this.$input ) {
14581 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14582 }
14583 break;
14584 case OO.ui.Keys.ESCAPE:
14585 case OO.ui.Keys.TAB:
14586 if ( currentItem ) {
14587 currentItem.setHighlighted( false );
14588 }
14589 this.toggle( false );
14590 // Don't prevent tabbing away, prevent defocusing
14591 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
14592 e.preventDefault();
14593 e.stopPropagation();
14594 }
14595 break;
14596 default:
14597 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14598 return;
14599 }
14600 }
14601 };
14602
14603 /**
14604 * @inheritdoc
14605 */
14606 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
14607 if ( this.$input ) {
14608 this.$input.on( 'keydown', this.onKeyDownHandler );
14609 } else {
14610 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
14611 }
14612 };
14613
14614 /**
14615 * @inheritdoc
14616 */
14617 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
14618 if ( this.$input ) {
14619 this.$input.off( 'keydown', this.onKeyDownHandler );
14620 } else {
14621 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
14622 }
14623 };
14624
14625 /**
14626 * Choose an item.
14627 *
14628 * When a user chooses an item, the menu is closed.
14629 *
14630 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14631 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14632 * @param {OO.ui.OptionWidget} item Item to choose
14633 * @chainable
14634 */
14635 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
14636 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
14637 this.toggle( false );
14638 return this;
14639 };
14640
14641 /**
14642 * @inheritdoc
14643 */
14644 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
14645 var i, len, item;
14646
14647 // Parent method
14648 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
14649
14650 // Auto-initialize
14651 if ( !this.newItems ) {
14652 this.newItems = [];
14653 }
14654
14655 for ( i = 0, len = items.length; i < len; i++ ) {
14656 item = items[ i ];
14657 if ( this.isVisible() ) {
14658 // Defer fitting label until item has been attached
14659 item.fitLabel();
14660 } else {
14661 this.newItems.push( item );
14662 }
14663 }
14664
14665 // Reevaluate clipping
14666 this.clip();
14667
14668 return this;
14669 };
14670
14671 /**
14672 * @inheritdoc
14673 */
14674 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
14675 // Parent method
14676 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
14677
14678 // Reevaluate clipping
14679 this.clip();
14680
14681 return this;
14682 };
14683
14684 /**
14685 * @inheritdoc
14686 */
14687 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
14688 // Parent method
14689 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
14690
14691 // Reevaluate clipping
14692 this.clip();
14693
14694 return this;
14695 };
14696
14697 /**
14698 * @inheritdoc
14699 */
14700 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
14701 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
14702
14703 var i, len,
14704 change = visible !== this.isVisible();
14705
14706 // Parent method
14707 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
14708
14709 if ( change ) {
14710 if ( visible ) {
14711 this.bindKeyDownListener();
14712
14713 if ( this.newItems && this.newItems.length ) {
14714 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
14715 this.newItems[ i ].fitLabel();
14716 }
14717 this.newItems = null;
14718 }
14719 this.toggleClipping( true );
14720
14721 // Auto-hide
14722 if ( this.autoHide ) {
14723 this.getElementDocument().addEventListener(
14724 'mousedown', this.onDocumentMouseDownHandler, true
14725 );
14726 }
14727 } else {
14728 this.unbindKeyDownListener();
14729 this.getElementDocument().removeEventListener(
14730 'mousedown', this.onDocumentMouseDownHandler, true
14731 );
14732 this.toggleClipping( false );
14733 }
14734 }
14735
14736 return this;
14737 };
14738
14739 /**
14740 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14741 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14742 * calculated and maintained when the menu is toggled or the window is resized.
14743 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14744 *
14745 * @class
14746 * @extends OO.ui.MenuSelectWidget
14747 *
14748 * @constructor
14749 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14750 * @param {Object} [config] Configuration options
14751 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14752 */
14753 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
14754 // Allow passing positional parameters inside the config object
14755 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
14756 config = inputWidget;
14757 inputWidget = config.inputWidget;
14758 }
14759
14760 // Configuration initialization
14761 config = config || {};
14762
14763 // Parent constructor
14764 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
14765
14766 // Properties
14767 this.inputWidget = inputWidget;
14768 this.$container = config.$container || this.inputWidget.$element;
14769 this.onWindowResizeHandler = this.onWindowResize.bind( this );
14770
14771 // Initialization
14772 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
14773 };
14774
14775 /* Setup */
14776
14777 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
14778
14779 /* Methods */
14780
14781 /**
14782 * Handle window resize event.
14783 *
14784 * @private
14785 * @param {jQuery.Event} e Window resize event
14786 */
14787 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
14788 this.position();
14789 };
14790
14791 /**
14792 * @inheritdoc
14793 */
14794 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
14795 visible = visible === undefined ? !this.isVisible() : !!visible;
14796
14797 var change = visible !== this.isVisible();
14798
14799 if ( change && visible ) {
14800 // Make sure the width is set before the parent method runs.
14801 // After this we have to call this.position(); again to actually
14802 // position ourselves correctly.
14803 this.position();
14804 }
14805
14806 // Parent method
14807 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
14808
14809 if ( change ) {
14810 if ( this.isVisible() ) {
14811 this.position();
14812 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
14813 } else {
14814 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
14815 }
14816 }
14817
14818 return this;
14819 };
14820
14821 /**
14822 * Position the menu.
14823 *
14824 * @private
14825 * @chainable
14826 */
14827 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
14828 var $container = this.$container,
14829 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
14830
14831 // Position under input
14832 pos.top += $container.height();
14833 this.$element.css( pos );
14834
14835 // Set width
14836 this.setIdealSize( $container.width() );
14837 // We updated the position, so re-evaluate the clipping state
14838 this.clip();
14839
14840 return this;
14841 };
14842
14843 /**
14844 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14845 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14846 *
14847 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14848 *
14849 * @class
14850 * @extends OO.ui.SelectWidget
14851 * @mixins OO.ui.TabIndexedElement
14852 *
14853 * @constructor
14854 * @param {Object} [config] Configuration options
14855 */
14856 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
14857 // Parent constructor
14858 OO.ui.OutlineSelectWidget.super.call( this, config );
14859
14860 // Mixin constructors
14861 OO.ui.TabIndexedElement.call( this, config );
14862
14863 // Events
14864 this.$element.on( {
14865 focus: this.bindKeyDownListener.bind( this ),
14866 blur: this.unbindKeyDownListener.bind( this )
14867 } );
14868
14869 // Initialization
14870 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
14871 };
14872
14873 /* Setup */
14874
14875 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
14876 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
14877
14878 /**
14879 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14880 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14881 * visually by a slider in the leftmost position.
14882 *
14883 * @example
14884 * // Toggle switches in the 'off' and 'on' position.
14885 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14886 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14887 * value: true
14888 * } );
14889 *
14890 * // Create a FieldsetLayout to layout and label switches
14891 * var fieldset = new OO.ui.FieldsetLayout( {
14892 * label: 'Toggle switches'
14893 * } );
14894 * fieldset.addItems( [
14895 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14896 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14897 * ] );
14898 * $( 'body' ).append( fieldset.$element );
14899 *
14900 * @class
14901 * @extends OO.ui.Widget
14902 * @mixins OO.ui.ToggleWidget
14903 * @mixins OO.ui.TabIndexedElement
14904 *
14905 * @constructor
14906 * @param {Object} [config] Configuration options
14907 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14908 * By default, the toggle switch is in the 'off' position.
14909 */
14910 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
14911 // Parent constructor
14912 OO.ui.ToggleSwitchWidget.super.call( this, config );
14913
14914 // Mixin constructors
14915 OO.ui.ToggleWidget.call( this, config );
14916 OO.ui.TabIndexedElement.call( this, config );
14917
14918 // Properties
14919 this.dragging = false;
14920 this.dragStart = null;
14921 this.sliding = false;
14922 this.$glow = $( '<span>' );
14923 this.$grip = $( '<span>' );
14924
14925 // Events
14926 this.$element.on( {
14927 click: this.onClick.bind( this ),
14928 keypress: this.onKeyPress.bind( this )
14929 } );
14930
14931 // Initialization
14932 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14933 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14934 this.$element
14935 .addClass( 'oo-ui-toggleSwitchWidget' )
14936 .attr( 'role', 'checkbox' )
14937 .append( this.$glow, this.$grip );
14938 };
14939
14940 /* Setup */
14941
14942 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
14943 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
14944 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
14945
14946 /* Methods */
14947
14948 /**
14949 * Handle mouse click events.
14950 *
14951 * @private
14952 * @param {jQuery.Event} e Mouse click event
14953 */
14954 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
14955 if ( !this.isDisabled() && e.which === 1 ) {
14956 this.setValue( !this.value );
14957 }
14958 return false;
14959 };
14960
14961 /**
14962 * Handle key press events.
14963 *
14964 * @private
14965 * @param {jQuery.Event} e Key press event
14966 */
14967 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
14968 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
14969 this.setValue( !this.value );
14970 return false;
14971 }
14972 };
14973
14974 }( OO ) );