Update OOjs UI to v0.9.3
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.9.3
3 * https://www.mediawiki.org/wiki/OOjs_UI
4 *
5 * Copyright 2011–2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-03-19T23:18:59Z
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 * Container for elements.
1578 *
1579 * @abstract
1580 * @class
1581 * @extends OO.ui.Element
1582 * @mixins OO.EventEmitter
1583 *
1584 * @constructor
1585 * @param {Object} [config] Configuration options
1586 */
1587 OO.ui.Layout = function OoUiLayout( config ) {
1588 // Configuration initialization
1589 config = config || {};
1590
1591 // Parent constructor
1592 OO.ui.Layout.super.call( this, config );
1593
1594 // Mixin constructors
1595 OO.EventEmitter.call( this );
1596
1597 // Initialization
1598 this.$element.addClass( 'oo-ui-layout' );
1599 };
1600
1601 /* Setup */
1602
1603 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1604 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1605
1606 /**
1607 * Widgets are compositions of one or more OOjs UI elements that users can both view
1608 * and interact with. All widgets can be configured and modified via a standard API,
1609 * and their state can change dynamically according to a model.
1610 *
1611 * @abstract
1612 * @class
1613 * @extends OO.ui.Element
1614 * @mixins OO.EventEmitter
1615 *
1616 * @constructor
1617 * @param {Object} [config] Configuration options
1618 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1619 * appearance reflects this state.
1620 */
1621 OO.ui.Widget = function OoUiWidget( config ) {
1622 // Initialize config
1623 config = $.extend( { disabled: false }, config );
1624
1625 // Parent constructor
1626 OO.ui.Widget.super.call( this, config );
1627
1628 // Mixin constructors
1629 OO.EventEmitter.call( this );
1630
1631 // Properties
1632 this.disabled = null;
1633 this.wasDisabled = null;
1634
1635 // Initialization
1636 this.$element.addClass( 'oo-ui-widget' );
1637 this.setDisabled( !!config.disabled );
1638 };
1639
1640 /* Setup */
1641
1642 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1643 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1644
1645 /* Events */
1646
1647 /**
1648 * @event disable
1649 *
1650 * A 'disable' event is emitted when a widget is disabled.
1651 *
1652 * @param {boolean} disabled Widget is disabled
1653 */
1654
1655 /**
1656 * @event toggle
1657 *
1658 * A 'toggle' event is emitted when the visibility of the widget changes.
1659 *
1660 * @param {boolean} visible Widget is visible
1661 */
1662
1663 /* Methods */
1664
1665 /**
1666 * Check if the widget is disabled.
1667 *
1668 * @return {boolean} Widget is disabled
1669 */
1670 OO.ui.Widget.prototype.isDisabled = function () {
1671 return this.disabled;
1672 };
1673
1674 /**
1675 * Set the 'disabled' state of the widget.
1676 *
1677 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1678 *
1679 * @param {boolean} disabled Disable widget
1680 * @chainable
1681 */
1682 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1683 var isDisabled;
1684
1685 this.disabled = !!disabled;
1686 isDisabled = this.isDisabled();
1687 if ( isDisabled !== this.wasDisabled ) {
1688 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1689 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1690 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1691 this.emit( 'disable', isDisabled );
1692 this.updateThemeClasses();
1693 }
1694 this.wasDisabled = isDisabled;
1695
1696 return this;
1697 };
1698
1699 /**
1700 * Update the disabled state, in case of changes in parent widget.
1701 *
1702 * @chainable
1703 */
1704 OO.ui.Widget.prototype.updateDisabled = function () {
1705 this.setDisabled( this.disabled );
1706 return this;
1707 };
1708
1709 /**
1710 * A window is a container for elements that are in a child frame. They are used with
1711 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1712 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1713 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1714 * the window manager will choose a sensible fallback.
1715 *
1716 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1717 * different processes are executed:
1718 *
1719 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1720 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1721 * the window.
1722 *
1723 * - {@link #getSetupProcess} method is called and its result executed
1724 * - {@link #getReadyProcess} method is called and its result executed
1725 *
1726 * **opened**: The window is now open
1727 *
1728 * **closing**: The closing stage begins when the window manager's
1729 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1730 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1731 *
1732 * - {@link #getHoldProcess} method is called and its result executed
1733 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1734 *
1735 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1736 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1737 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1738 * processing can complete. Always assume window processes are executed asynchronously.
1739 *
1740 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1741 *
1742 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1743 *
1744 * @abstract
1745 * @class
1746 * @extends OO.ui.Element
1747 * @mixins OO.EventEmitter
1748 *
1749 * @constructor
1750 * @param {Object} [config] Configuration options
1751 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1752 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1753 */
1754 OO.ui.Window = function OoUiWindow( config ) {
1755 // Configuration initialization
1756 config = config || {};
1757
1758 // Parent constructor
1759 OO.ui.Window.super.call( this, config );
1760
1761 // Mixin constructors
1762 OO.EventEmitter.call( this );
1763
1764 // Properties
1765 this.manager = null;
1766 this.size = config.size || this.constructor.static.size;
1767 this.$frame = $( '<div>' );
1768 this.$overlay = $( '<div>' );
1769 this.$content = $( '<div>' );
1770
1771 // Initialization
1772 this.$overlay.addClass( 'oo-ui-window-overlay' );
1773 this.$content
1774 .addClass( 'oo-ui-window-content' )
1775 .attr( 'tabIndex', 0 );
1776 this.$frame
1777 .addClass( 'oo-ui-window-frame' )
1778 .append( this.$content );
1779
1780 this.$element
1781 .addClass( 'oo-ui-window' )
1782 .append( this.$frame, this.$overlay );
1783
1784 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1785 // that reference properties not initialized at that time of parent class construction
1786 // TODO: Find a better way to handle post-constructor setup
1787 this.visible = false;
1788 this.$element.addClass( 'oo-ui-element-hidden' );
1789 };
1790
1791 /* Setup */
1792
1793 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1794 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1795
1796 /* Static Properties */
1797
1798 /**
1799 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1800 *
1801 * The static size is used if no #size is configured during construction.
1802 *
1803 * @static
1804 * @inheritable
1805 * @property {string}
1806 */
1807 OO.ui.Window.static.size = 'medium';
1808
1809 /* Methods */
1810
1811 /**
1812 * Handle mouse down events.
1813 *
1814 * @private
1815 * @param {jQuery.Event} e Mouse down event
1816 */
1817 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1818 // Prevent clicking on the click-block from stealing focus
1819 if ( e.target === this.$element[ 0 ] ) {
1820 return false;
1821 }
1822 };
1823
1824 /**
1825 * Check if the window has been initialized.
1826 *
1827 * Initialization occurs when a window is added to a manager.
1828 *
1829 * @return {boolean} Window has been initialized
1830 */
1831 OO.ui.Window.prototype.isInitialized = function () {
1832 return !!this.manager;
1833 };
1834
1835 /**
1836 * Check if the window is visible.
1837 *
1838 * @return {boolean} Window is visible
1839 */
1840 OO.ui.Window.prototype.isVisible = function () {
1841 return this.visible;
1842 };
1843
1844 /**
1845 * Check if the window is opening.
1846 *
1847 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1848 * method.
1849 *
1850 * @return {boolean} Window is opening
1851 */
1852 OO.ui.Window.prototype.isOpening = function () {
1853 return this.manager.isOpening( this );
1854 };
1855
1856 /**
1857 * Check if the window is closing.
1858 *
1859 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1860 *
1861 * @return {boolean} Window is closing
1862 */
1863 OO.ui.Window.prototype.isClosing = function () {
1864 return this.manager.isClosing( this );
1865 };
1866
1867 /**
1868 * Check if the window is opened.
1869 *
1870 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1871 *
1872 * @return {boolean} Window is opened
1873 */
1874 OO.ui.Window.prototype.isOpened = function () {
1875 return this.manager.isOpened( this );
1876 };
1877
1878 /**
1879 * Get the window manager.
1880 *
1881 * All windows must be attached to a window manager, which is used to open
1882 * and close the window and control its presentation.
1883 *
1884 * @return {OO.ui.WindowManager} Manager of window
1885 */
1886 OO.ui.Window.prototype.getManager = function () {
1887 return this.manager;
1888 };
1889
1890 /**
1891 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1892 *
1893 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1894 */
1895 OO.ui.Window.prototype.getSize = function () {
1896 return this.size;
1897 };
1898
1899 /**
1900 * Disable transitions on window's frame for the duration of the callback function, then enable them
1901 * back.
1902 *
1903 * @private
1904 * @param {Function} callback Function to call while transitions are disabled
1905 */
1906 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1907 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1908 // Disable transitions first, otherwise we'll get values from when the window was animating.
1909 var oldTransition,
1910 styleObj = this.$frame[ 0 ].style;
1911 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1912 styleObj.MozTransition || styleObj.WebkitTransition;
1913 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1914 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1915 callback();
1916 // Force reflow to make sure the style changes done inside callback really are not transitioned
1917 this.$frame.height();
1918 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1919 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1920 };
1921
1922 /**
1923 * Get the height of the full window contents (i.e., the window head, body and foot together).
1924 *
1925 * What consistitutes the head, body, and foot varies depending on the window type.
1926 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1927 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1928 * and special actions in the head, and dialog content in the body.
1929 *
1930 * To get just the height of the dialog body, use the #getBodyHeight method.
1931 *
1932 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1933 */
1934 OO.ui.Window.prototype.getContentHeight = function () {
1935 var bodyHeight,
1936 win = this,
1937 bodyStyleObj = this.$body[ 0 ].style,
1938 frameStyleObj = this.$frame[ 0 ].style;
1939
1940 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1941 // Disable transitions first, otherwise we'll get values from when the window was animating.
1942 this.withoutSizeTransitions( function () {
1943 var oldHeight = frameStyleObj.height,
1944 oldPosition = bodyStyleObj.position;
1945 frameStyleObj.height = '1px';
1946 // Force body to resize to new width
1947 bodyStyleObj.position = 'relative';
1948 bodyHeight = win.getBodyHeight();
1949 frameStyleObj.height = oldHeight;
1950 bodyStyleObj.position = oldPosition;
1951 } );
1952
1953 return (
1954 // Add buffer for border
1955 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1956 // Use combined heights of children
1957 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1958 );
1959 };
1960
1961 /**
1962 * Get the height of the window body.
1963 *
1964 * To get the height of the full window contents (the window body, head, and foot together),
1965 * use #getContentHeight.
1966 *
1967 * When this function is called, the window will temporarily have been resized
1968 * to height=1px, so .scrollHeight measurements can be taken accurately.
1969 *
1970 * @return {number} Height of the window body in pixels
1971 */
1972 OO.ui.Window.prototype.getBodyHeight = function () {
1973 return this.$body[ 0 ].scrollHeight;
1974 };
1975
1976 /**
1977 * Get the directionality of the frame (right-to-left or left-to-right).
1978 *
1979 * @return {string} Directionality: `'ltr'` or `'rtl'`
1980 */
1981 OO.ui.Window.prototype.getDir = function () {
1982 return this.dir;
1983 };
1984
1985 /**
1986 * Get the 'setup' process.
1987 *
1988 * The setup process is used to set up a window for use in a particular context,
1989 * based on the `data` argument. This method is called during the opening phase of the window’s
1990 * lifecycle.
1991 *
1992 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1993 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1994 * of OO.ui.Process.
1995 *
1996 * To add window content that persists between openings, you may wish to use the #initialize method
1997 * instead.
1998 *
1999 * @abstract
2000 * @param {Object} [data] Window opening data
2001 * @return {OO.ui.Process} Setup process
2002 */
2003 OO.ui.Window.prototype.getSetupProcess = function () {
2004 return new OO.ui.Process();
2005 };
2006
2007 /**
2008 * Get the ‘ready’ process.
2009 *
2010 * The ready process is used to ready a window for use in a particular
2011 * context, based on the `data` argument. This method is called during the opening phase of
2012 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2013 *
2014 * Override this method to add additional steps to the ‘ready’ process the parent method
2015 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2016 * methods of OO.ui.Process.
2017 *
2018 * @abstract
2019 * @param {Object} [data] Window opening data
2020 * @return {OO.ui.Process} Ready process
2021 */
2022 OO.ui.Window.prototype.getReadyProcess = function () {
2023 return new OO.ui.Process();
2024 };
2025
2026 /**
2027 * Get the 'hold' process.
2028 *
2029 * The hold proccess is used to keep a window from being used in a particular context,
2030 * based on the `data` argument. This method is called during the closing phase of the window’s
2031 * lifecycle.
2032 *
2033 * Override this method to add additional steps to the 'hold' process the parent method provides
2034 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2035 * of OO.ui.Process.
2036 *
2037 * @abstract
2038 * @param {Object} [data] Window closing data
2039 * @return {OO.ui.Process} Hold process
2040 */
2041 OO.ui.Window.prototype.getHoldProcess = function () {
2042 return new OO.ui.Process();
2043 };
2044
2045 /**
2046 * Get the ‘teardown’ process.
2047 *
2048 * The teardown process is used to teardown a window after use. During teardown,
2049 * user interactions within the window are conveyed and the window is closed, based on the `data`
2050 * argument. This method is called during the closing phase of the window’s lifecycle.
2051 *
2052 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2053 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2054 * of OO.ui.Process.
2055 *
2056 * @abstract
2057 * @param {Object} [data] Window closing data
2058 * @return {OO.ui.Process} Teardown process
2059 */
2060 OO.ui.Window.prototype.getTeardownProcess = function () {
2061 return new OO.ui.Process();
2062 };
2063
2064 /**
2065 * Set the window manager.
2066 *
2067 * This will cause the window to initialize. Calling it more than once will cause an error.
2068 *
2069 * @param {OO.ui.WindowManager} manager Manager for this window
2070 * @throws {Error} An error is thrown if the method is called more than once
2071 * @chainable
2072 */
2073 OO.ui.Window.prototype.setManager = function ( manager ) {
2074 if ( this.manager ) {
2075 throw new Error( 'Cannot set window manager, window already has a manager' );
2076 }
2077
2078 this.manager = manager;
2079 this.initialize();
2080
2081 return this;
2082 };
2083
2084 /**
2085 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2086 *
2087 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2088 * `full`
2089 * @chainable
2090 */
2091 OO.ui.Window.prototype.setSize = function ( size ) {
2092 this.size = size;
2093 this.updateSize();
2094 return this;
2095 };
2096
2097 /**
2098 * Update the window size.
2099 *
2100 * @throws {Error} An error is thrown if the window is not attached to a window manager
2101 * @chainable
2102 */
2103 OO.ui.Window.prototype.updateSize = function () {
2104 if ( !this.manager ) {
2105 throw new Error( 'Cannot update window size, must be attached to a manager' );
2106 }
2107
2108 this.manager.updateWindowSize( this );
2109
2110 return this;
2111 };
2112
2113 /**
2114 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2115 * when the window is opening. In general, setDimensions should not be called directly.
2116 *
2117 * To set the size of the window, use the #setSize method.
2118 *
2119 * @param {Object} dim CSS dimension properties
2120 * @param {string|number} [dim.width] Width
2121 * @param {string|number} [dim.minWidth] Minimum width
2122 * @param {string|number} [dim.maxWidth] Maximum width
2123 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2124 * @param {string|number} [dim.minWidth] Minimum height
2125 * @param {string|number} [dim.maxWidth] Maximum height
2126 * @chainable
2127 */
2128 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2129 var height,
2130 win = this,
2131 styleObj = this.$frame[ 0 ].style;
2132
2133 // Calculate the height we need to set using the correct width
2134 if ( dim.height === undefined ) {
2135 this.withoutSizeTransitions( function () {
2136 var oldWidth = styleObj.width;
2137 win.$frame.css( 'width', dim.width || '' );
2138 height = win.getContentHeight();
2139 styleObj.width = oldWidth;
2140 } );
2141 } else {
2142 height = dim.height;
2143 }
2144
2145 this.$frame.css( {
2146 width: dim.width || '',
2147 minWidth: dim.minWidth || '',
2148 maxWidth: dim.maxWidth || '',
2149 height: height || '',
2150 minHeight: dim.minHeight || '',
2151 maxHeight: dim.maxHeight || ''
2152 } );
2153
2154 return this;
2155 };
2156
2157 /**
2158 * Initialize window contents.
2159 *
2160 * Before the window is opened for the first time, #initialize is called so that content that
2161 * persists between openings can be added to the window.
2162 *
2163 * To set up a window with new content each time the window opens, use #getSetupProcess.
2164 *
2165 * @throws {Error} An error is thrown if the window is not attached to a window manager
2166 * @chainable
2167 */
2168 OO.ui.Window.prototype.initialize = function () {
2169 if ( !this.manager ) {
2170 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2171 }
2172
2173 // Properties
2174 this.$head = $( '<div>' );
2175 this.$body = $( '<div>' );
2176 this.$foot = $( '<div>' );
2177 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2178 this.$document = $( this.getElementDocument() );
2179
2180 // Events
2181 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2182
2183 // Initialization
2184 this.$head.addClass( 'oo-ui-window-head' );
2185 this.$body.addClass( 'oo-ui-window-body' );
2186 this.$foot.addClass( 'oo-ui-window-foot' );
2187 this.$content.append( this.$head, this.$body, this.$foot );
2188
2189 return this;
2190 };
2191
2192 /**
2193 * Open the window.
2194 *
2195 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2196 * method, which returns a promise resolved when the window is done opening.
2197 *
2198 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2199 *
2200 * @param {Object} [data] Window opening data
2201 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2202 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2203 * value is a new promise, which is resolved when the window begins closing.
2204 * @throws {Error} An error is thrown if the window is not attached to a window manager
2205 */
2206 OO.ui.Window.prototype.open = function ( data ) {
2207 if ( !this.manager ) {
2208 throw new Error( 'Cannot open window, must be attached to a manager' );
2209 }
2210
2211 return this.manager.openWindow( this, data );
2212 };
2213
2214 /**
2215 * Close the window.
2216 *
2217 * This method is a wrapper around a call to the window
2218 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2219 * which returns a closing promise resolved when the window is done closing.
2220 *
2221 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2222 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2223 * the window closes.
2224 *
2225 * @param {Object} [data] Window closing data
2226 * @return {jQuery.Promise} Promise resolved when window is closed
2227 * @throws {Error} An error is thrown if the window is not attached to a window manager
2228 */
2229 OO.ui.Window.prototype.close = function ( data ) {
2230 if ( !this.manager ) {
2231 throw new Error( 'Cannot close window, must be attached to a manager' );
2232 }
2233
2234 return this.manager.closeWindow( this, data );
2235 };
2236
2237 /**
2238 * Setup window.
2239 *
2240 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2241 * by other systems.
2242 *
2243 * @param {Object} [data] Window opening data
2244 * @return {jQuery.Promise} Promise resolved when window is setup
2245 */
2246 OO.ui.Window.prototype.setup = function ( data ) {
2247 var win = this,
2248 deferred = $.Deferred();
2249
2250 this.toggle( true );
2251
2252 this.getSetupProcess( data ).execute().done( function () {
2253 // Force redraw by asking the browser to measure the elements' widths
2254 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2255 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2256 deferred.resolve();
2257 } );
2258
2259 return deferred.promise();
2260 };
2261
2262 /**
2263 * Ready window.
2264 *
2265 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2266 * by other systems.
2267 *
2268 * @param {Object} [data] Window opening data
2269 * @return {jQuery.Promise} Promise resolved when window is ready
2270 */
2271 OO.ui.Window.prototype.ready = function ( data ) {
2272 var win = this,
2273 deferred = $.Deferred();
2274
2275 this.$content.focus();
2276 this.getReadyProcess( data ).execute().done( function () {
2277 // Force redraw by asking the browser to measure the elements' widths
2278 win.$element.addClass( 'oo-ui-window-ready' ).width();
2279 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2280 deferred.resolve();
2281 } );
2282
2283 return deferred.promise();
2284 };
2285
2286 /**
2287 * Hold window.
2288 *
2289 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2290 * by other systems.
2291 *
2292 * @param {Object} [data] Window closing data
2293 * @return {jQuery.Promise} Promise resolved when window is held
2294 */
2295 OO.ui.Window.prototype.hold = function ( data ) {
2296 var win = this,
2297 deferred = $.Deferred();
2298
2299 this.getHoldProcess( data ).execute().done( function () {
2300 // Get the focused element within the window's content
2301 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2302
2303 // Blur the focused element
2304 if ( $focus.length ) {
2305 $focus[ 0 ].blur();
2306 }
2307
2308 // Force redraw by asking the browser to measure the elements' widths
2309 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2310 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2311 deferred.resolve();
2312 } );
2313
2314 return deferred.promise();
2315 };
2316
2317 /**
2318 * Teardown window.
2319 *
2320 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2321 * by other systems.
2322 *
2323 * @param {Object} [data] Window closing data
2324 * @return {jQuery.Promise} Promise resolved when window is torn down
2325 */
2326 OO.ui.Window.prototype.teardown = function ( data ) {
2327 var win = this;
2328
2329 return this.getTeardownProcess( data ).execute()
2330 .done( function () {
2331 // Force redraw by asking the browser to measure the elements' widths
2332 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2333 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2334 win.toggle( false );
2335 } );
2336 };
2337
2338 /**
2339 * The Dialog class serves as the base class for the other types of dialogs.
2340 * Unless extended to include controls, the rendered dialog box is a simple window
2341 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2342 * which opens, closes, and controls the presentation of the window. See the
2343 * [OOjs UI documentation on MediaWiki] [1] for more information.
2344 *
2345 * @example
2346 * // A simple dialog window.
2347 * function MyDialog( config ) {
2348 * MyDialog.super.call( this, config );
2349 * }
2350 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2351 * MyDialog.prototype.initialize = function () {
2352 * MyDialog.super.prototype.initialize.call( this );
2353 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2354 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2355 * this.$body.append( this.content.$element );
2356 * };
2357 * MyDialog.prototype.getBodyHeight = function () {
2358 * return this.content.$element.outerHeight( true );
2359 * };
2360 * var myDialog = new MyDialog( {
2361 * size: 'medium'
2362 * } );
2363 * // Create and append a window manager, which opens and closes the window.
2364 * var windowManager = new OO.ui.WindowManager();
2365 * $( 'body' ).append( windowManager.$element );
2366 * windowManager.addWindows( [ myDialog ] );
2367 * // Open the window!
2368 * windowManager.openWindow( myDialog );
2369 *
2370 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2371 *
2372 * @abstract
2373 * @class
2374 * @extends OO.ui.Window
2375 * @mixins OO.ui.PendingElement
2376 *
2377 * @constructor
2378 * @param {Object} [config] Configuration options
2379 */
2380 OO.ui.Dialog = function OoUiDialog( config ) {
2381 // Parent constructor
2382 OO.ui.Dialog.super.call( this, config );
2383
2384 // Mixin constructors
2385 OO.ui.PendingElement.call( this );
2386
2387 // Properties
2388 this.actions = new OO.ui.ActionSet();
2389 this.attachedActions = [];
2390 this.currentAction = null;
2391 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2392
2393 // Events
2394 this.actions.connect( this, {
2395 click: 'onActionClick',
2396 resize: 'onActionResize',
2397 change: 'onActionsChange'
2398 } );
2399
2400 // Initialization
2401 this.$element
2402 .addClass( 'oo-ui-dialog' )
2403 .attr( 'role', 'dialog' );
2404 };
2405
2406 /* Setup */
2407
2408 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2409 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2410
2411 /* Static Properties */
2412
2413 /**
2414 * Symbolic name of dialog.
2415 *
2416 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2417 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2418 *
2419 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2420 *
2421 * @abstract
2422 * @static
2423 * @inheritable
2424 * @property {string}
2425 */
2426 OO.ui.Dialog.static.name = '';
2427
2428 /**
2429 * The dialog title.
2430 *
2431 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2432 * that will produce a Label node or string. The title can also be specified with data passed to the
2433 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2434 *
2435 * @abstract
2436 * @static
2437 * @inheritable
2438 * @property {jQuery|string|Function}
2439 */
2440 OO.ui.Dialog.static.title = '';
2441
2442 /**
2443 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2444 *
2445 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2446 * value will be overriden.
2447 *
2448 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2449 *
2450 * @static
2451 * @inheritable
2452 * @property {Object[]}
2453 */
2454 OO.ui.Dialog.static.actions = [];
2455
2456 /**
2457 * Close the dialog when the 'Esc' key is pressed.
2458 *
2459 * @static
2460 * @abstract
2461 * @inheritable
2462 * @property {boolean}
2463 */
2464 OO.ui.Dialog.static.escapable = true;
2465
2466 /* Methods */
2467
2468 /**
2469 * Handle frame document key down events.
2470 *
2471 * @private
2472 * @param {jQuery.Event} e Key down event
2473 */
2474 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2475 if ( e.which === OO.ui.Keys.ESCAPE ) {
2476 this.close();
2477 e.preventDefault();
2478 e.stopPropagation();
2479 }
2480 };
2481
2482 /**
2483 * Handle action resized events.
2484 *
2485 * @private
2486 * @param {OO.ui.ActionWidget} action Action that was resized
2487 */
2488 OO.ui.Dialog.prototype.onActionResize = function () {
2489 // Override in subclass
2490 };
2491
2492 /**
2493 * Handle action click events.
2494 *
2495 * @private
2496 * @param {OO.ui.ActionWidget} action Action that was clicked
2497 */
2498 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2499 if ( !this.isPending() ) {
2500 this.executeAction( action.getAction() );
2501 }
2502 };
2503
2504 /**
2505 * Handle actions change event.
2506 *
2507 * @private
2508 */
2509 OO.ui.Dialog.prototype.onActionsChange = function () {
2510 this.detachActions();
2511 if ( !this.isClosing() ) {
2512 this.attachActions();
2513 }
2514 };
2515
2516 /**
2517 * Get the set of actions used by the dialog.
2518 *
2519 * @return {OO.ui.ActionSet}
2520 */
2521 OO.ui.Dialog.prototype.getActions = function () {
2522 return this.actions;
2523 };
2524
2525 /**
2526 * Get a process for taking action.
2527 *
2528 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2529 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2530 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2531 *
2532 * @abstract
2533 * @param {string} [action] Symbolic name of action
2534 * @return {OO.ui.Process} Action process
2535 */
2536 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2537 return new OO.ui.Process()
2538 .next( function () {
2539 if ( !action ) {
2540 // An empty action always closes the dialog without data, which should always be
2541 // safe and make no changes
2542 this.close();
2543 }
2544 }, this );
2545 };
2546
2547 /**
2548 * @inheritdoc
2549 *
2550 * @param {Object} [data] Dialog opening data
2551 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2552 * the {@link #static-title static title}
2553 * @param {Object[]} [data.actions] List of configuration options for each
2554 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2555 */
2556 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2557 data = data || {};
2558
2559 // Parent method
2560 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2561 .next( function () {
2562 var config = this.constructor.static,
2563 actions = data.actions !== undefined ? data.actions : config.actions;
2564
2565 this.title.setLabel(
2566 data.title !== undefined ? data.title : this.constructor.static.title
2567 );
2568 this.actions.add( this.getActionWidgets( actions ) );
2569
2570 if ( this.constructor.static.escapable ) {
2571 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2572 }
2573 }, this );
2574 };
2575
2576 /**
2577 * @inheritdoc
2578 */
2579 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2580 // Parent method
2581 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2582 .first( function () {
2583 if ( this.constructor.static.escapable ) {
2584 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2585 }
2586
2587 this.actions.clear();
2588 this.currentAction = null;
2589 }, this );
2590 };
2591
2592 /**
2593 * @inheritdoc
2594 */
2595 OO.ui.Dialog.prototype.initialize = function () {
2596 // Parent method
2597 OO.ui.Dialog.super.prototype.initialize.call( this );
2598
2599 // Properties
2600 this.title = new OO.ui.LabelWidget();
2601
2602 // Initialization
2603 this.$content.addClass( 'oo-ui-dialog-content' );
2604 this.setPendingElement( this.$head );
2605 };
2606
2607 /**
2608 * Get action widgets from a list of configs
2609 *
2610 * @param {Object[]} actions Action widget configs
2611 * @return {OO.ui.ActionWidget[]} Action widgets
2612 */
2613 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2614 var i, len, widgets = [];
2615 for ( i = 0, len = actions.length; i < len; i++ ) {
2616 widgets.push(
2617 new OO.ui.ActionWidget( actions[ i ] )
2618 );
2619 }
2620 return widgets;
2621 };
2622
2623 /**
2624 * Attach action actions.
2625 *
2626 * @protected
2627 */
2628 OO.ui.Dialog.prototype.attachActions = function () {
2629 // Remember the list of potentially attached actions
2630 this.attachedActions = this.actions.get();
2631 };
2632
2633 /**
2634 * Detach action actions.
2635 *
2636 * @protected
2637 * @chainable
2638 */
2639 OO.ui.Dialog.prototype.detachActions = function () {
2640 var i, len;
2641
2642 // Detach all actions that may have been previously attached
2643 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2644 this.attachedActions[ i ].$element.detach();
2645 }
2646 this.attachedActions = [];
2647 };
2648
2649 /**
2650 * Execute an action.
2651 *
2652 * @param {string} action Symbolic name of action to execute
2653 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2654 */
2655 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2656 this.pushPending();
2657 this.currentAction = action;
2658 return this.getActionProcess( action ).execute()
2659 .always( this.popPending.bind( this ) );
2660 };
2661
2662 /**
2663 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2664 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2665 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2666 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2667 * pertinent data and reused.
2668 *
2669 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2670 * `opened`, and `closing`, which represent the primary stages of the cycle:
2671 *
2672 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2673 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2674 *
2675 * - an `opening` event is emitted with an `opening` promise
2676 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2677 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2678 * window and its result executed
2679 * - a `setup` progress notification is emitted from the `opening` promise
2680 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2682 * window and its result executed
2683 * - a `ready` progress notification is emitted from the `opening` promise
2684 * - the `opening` promise is resolved with an `opened` promise
2685 *
2686 * **Opened**: the window is now open.
2687 *
2688 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2689 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2690 * to close the window.
2691 *
2692 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2693 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2694 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2695 * window and its result executed
2696 * - a `hold` progress notification is emitted from the `closing` promise
2697 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2699 * window and its result executed
2700 * - a `teardown` progress notification is emitted from the `closing` promise
2701 * - the `closing` promise is resolved. The window is now closed
2702 *
2703 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2704 *
2705 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2706 *
2707 * @class
2708 * @extends OO.ui.Element
2709 * @mixins OO.EventEmitter
2710 *
2711 * @constructor
2712 * @param {Object} [config] Configuration options
2713 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2714 * Note that window classes that are instantiated with a factory must have
2715 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2716 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2717 */
2718 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2719 // Configuration initialization
2720 config = config || {};
2721
2722 // Parent constructor
2723 OO.ui.WindowManager.super.call( this, config );
2724
2725 // Mixin constructors
2726 OO.EventEmitter.call( this );
2727
2728 // Properties
2729 this.factory = config.factory;
2730 this.modal = config.modal === undefined || !!config.modal;
2731 this.windows = {};
2732 this.opening = null;
2733 this.opened = null;
2734 this.closing = null;
2735 this.preparingToOpen = null;
2736 this.preparingToClose = null;
2737 this.currentWindow = null;
2738 this.globalEvents = false;
2739 this.$ariaHidden = null;
2740 this.onWindowResizeTimeout = null;
2741 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2742 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2743
2744 // Initialization
2745 this.$element
2746 .addClass( 'oo-ui-windowManager' )
2747 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2748 };
2749
2750 /* Setup */
2751
2752 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2753 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2754
2755 /* Events */
2756
2757 /**
2758 * An 'opening' event is emitted when the window begins to be opened.
2759 *
2760 * @event opening
2761 * @param {OO.ui.Window} win Window that's being opened
2762 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2763 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2764 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2765 * @param {Object} data Window opening data
2766 */
2767
2768 /**
2769 * A 'closing' event is emitted when the window begins to be closed.
2770 *
2771 * @event closing
2772 * @param {OO.ui.Window} win Window that's being closed
2773 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2774 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2775 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2776 * is the closing data.
2777 * @param {Object} data Window closing data
2778 */
2779
2780 /**
2781 * A 'resize' event is emitted when a window is resized.
2782 *
2783 * @event resize
2784 * @param {OO.ui.Window} win Window that was resized
2785 */
2786
2787 /* Static Properties */
2788
2789 /**
2790 * Map of the symbolic name of each window size and its CSS properties.
2791 *
2792 * @static
2793 * @inheritable
2794 * @property {Object}
2795 */
2796 OO.ui.WindowManager.static.sizes = {
2797 small: {
2798 width: 300
2799 },
2800 medium: {
2801 width: 500
2802 },
2803 large: {
2804 width: 700
2805 },
2806 larger: {
2807 width: 900
2808 },
2809 full: {
2810 // These can be non-numeric because they are never used in calculations
2811 width: '100%',
2812 height: '100%'
2813 }
2814 };
2815
2816 /**
2817 * Symbolic name of the default window size.
2818 *
2819 * The default size is used if the window's requested size is not recognized.
2820 *
2821 * @static
2822 * @inheritable
2823 * @property {string}
2824 */
2825 OO.ui.WindowManager.static.defaultSize = 'medium';
2826
2827 /* Methods */
2828
2829 /**
2830 * Handle window resize events.
2831 *
2832 * @private
2833 * @param {jQuery.Event} e Window resize event
2834 */
2835 OO.ui.WindowManager.prototype.onWindowResize = function () {
2836 clearTimeout( this.onWindowResizeTimeout );
2837 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2838 };
2839
2840 /**
2841 * Handle window resize events.
2842 *
2843 * @private
2844 * @param {jQuery.Event} e Window resize event
2845 */
2846 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2847 if ( this.currentWindow ) {
2848 this.updateWindowSize( this.currentWindow );
2849 }
2850 };
2851
2852 /**
2853 * Check if window is opening.
2854 *
2855 * @return {boolean} Window is opening
2856 */
2857 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2858 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2859 };
2860
2861 /**
2862 * Check if window is closing.
2863 *
2864 * @return {boolean} Window is closing
2865 */
2866 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2867 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2868 };
2869
2870 /**
2871 * Check if window is opened.
2872 *
2873 * @return {boolean} Window is opened
2874 */
2875 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2876 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2877 };
2878
2879 /**
2880 * Check if a window is being managed.
2881 *
2882 * @param {OO.ui.Window} win Window to check
2883 * @return {boolean} Window is being managed
2884 */
2885 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2886 var name;
2887
2888 for ( name in this.windows ) {
2889 if ( this.windows[ name ] === win ) {
2890 return true;
2891 }
2892 }
2893
2894 return false;
2895 };
2896
2897 /**
2898 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2899 *
2900 * @param {OO.ui.Window} win Window being opened
2901 * @param {Object} [data] Window opening data
2902 * @return {number} Milliseconds to wait
2903 */
2904 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2905 return 0;
2906 };
2907
2908 /**
2909 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2910 *
2911 * @param {OO.ui.Window} win Window being opened
2912 * @param {Object} [data] Window opening data
2913 * @return {number} Milliseconds to wait
2914 */
2915 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2916 return 0;
2917 };
2918
2919 /**
2920 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2921 *
2922 * @param {OO.ui.Window} win Window being closed
2923 * @param {Object} [data] Window closing data
2924 * @return {number} Milliseconds to wait
2925 */
2926 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2927 return 0;
2928 };
2929
2930 /**
2931 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2932 * executing the ‘teardown’ process.
2933 *
2934 * @param {OO.ui.Window} win Window being closed
2935 * @param {Object} [data] Window closing data
2936 * @return {number} Milliseconds to wait
2937 */
2938 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2939 return this.modal ? 250 : 0;
2940 };
2941
2942 /**
2943 * Get a window by its symbolic name.
2944 *
2945 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2946 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2947 * for more information about using factories.
2948 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2949 *
2950 * @param {string} name Symbolic name of the window
2951 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2952 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2953 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2954 */
2955 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2956 var deferred = $.Deferred(),
2957 win = this.windows[ name ];
2958
2959 if ( !( win instanceof OO.ui.Window ) ) {
2960 if ( this.factory ) {
2961 if ( !this.factory.lookup( name ) ) {
2962 deferred.reject( new OO.ui.Error(
2963 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2964 ) );
2965 } else {
2966 win = this.factory.create( name );
2967 this.addWindows( [ win ] );
2968 deferred.resolve( win );
2969 }
2970 } else {
2971 deferred.reject( new OO.ui.Error(
2972 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2973 ) );
2974 }
2975 } else {
2976 deferred.resolve( win );
2977 }
2978
2979 return deferred.promise();
2980 };
2981
2982 /**
2983 * Get current window.
2984 *
2985 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2986 */
2987 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2988 return this.currentWindow;
2989 };
2990
2991 /**
2992 * Open a window.
2993 *
2994 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2995 * @param {Object} [data] Window opening data
2996 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
2997 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
2998 * @fires opening
2999 */
3000 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3001 var manager = this,
3002 opening = $.Deferred();
3003
3004 // Argument handling
3005 if ( typeof win === 'string' ) {
3006 return this.getWindow( win ).then( function ( win ) {
3007 return manager.openWindow( win, data );
3008 } );
3009 }
3010
3011 // Error handling
3012 if ( !this.hasWindow( win ) ) {
3013 opening.reject( new OO.ui.Error(
3014 'Cannot open window: window is not attached to manager'
3015 ) );
3016 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3017 opening.reject( new OO.ui.Error(
3018 'Cannot open window: another window is opening or open'
3019 ) );
3020 }
3021
3022 // Window opening
3023 if ( opening.state() !== 'rejected' ) {
3024 // If a window is currently closing, wait for it to complete
3025 this.preparingToOpen = $.when( this.closing );
3026 // Ensure handlers get called after preparingToOpen is set
3027 this.preparingToOpen.done( function () {
3028 if ( manager.modal ) {
3029 manager.toggleGlobalEvents( true );
3030 manager.toggleAriaIsolation( true );
3031 }
3032 manager.currentWindow = win;
3033 manager.opening = opening;
3034 manager.preparingToOpen = null;
3035 manager.emit( 'opening', win, opening, data );
3036 setTimeout( function () {
3037 win.setup( data ).then( function () {
3038 manager.updateWindowSize( win );
3039 manager.opening.notify( { state: 'setup' } );
3040 setTimeout( function () {
3041 win.ready( data ).then( function () {
3042 manager.opening.notify( { state: 'ready' } );
3043 manager.opening = null;
3044 manager.opened = $.Deferred();
3045 opening.resolve( manager.opened.promise(), data );
3046 } );
3047 }, manager.getReadyDelay() );
3048 } );
3049 }, manager.getSetupDelay() );
3050 } );
3051 }
3052
3053 return opening.promise();
3054 };
3055
3056 /**
3057 * Close a window.
3058 *
3059 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3060 * @param {Object} [data] Window closing data
3061 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3062 * See {@link #event-closing 'closing' event} for more information about closing promises.
3063 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3064 * @fires closing
3065 */
3066 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3067 var manager = this,
3068 closing = $.Deferred(),
3069 opened;
3070
3071 // Argument handling
3072 if ( typeof win === 'string' ) {
3073 win = this.windows[ win ];
3074 } else if ( !this.hasWindow( win ) ) {
3075 win = null;
3076 }
3077
3078 // Error handling
3079 if ( !win ) {
3080 closing.reject( new OO.ui.Error(
3081 'Cannot close window: window is not attached to manager'
3082 ) );
3083 } else if ( win !== this.currentWindow ) {
3084 closing.reject( new OO.ui.Error(
3085 'Cannot close window: window already closed with different data'
3086 ) );
3087 } else if ( this.preparingToClose || this.closing ) {
3088 closing.reject( new OO.ui.Error(
3089 'Cannot close window: window already closing with different data'
3090 ) );
3091 }
3092
3093 // Window closing
3094 if ( closing.state() !== 'rejected' ) {
3095 // If the window is currently opening, close it when it's done
3096 this.preparingToClose = $.when( this.opening );
3097 // Ensure handlers get called after preparingToClose is set
3098 this.preparingToClose.done( function () {
3099 manager.closing = closing;
3100 manager.preparingToClose = null;
3101 manager.emit( 'closing', win, closing, data );
3102 opened = manager.opened;
3103 manager.opened = null;
3104 opened.resolve( closing.promise(), data );
3105 setTimeout( function () {
3106 win.hold( data ).then( function () {
3107 closing.notify( { state: 'hold' } );
3108 setTimeout( function () {
3109 win.teardown( data ).then( function () {
3110 closing.notify( { state: 'teardown' } );
3111 if ( manager.modal ) {
3112 manager.toggleGlobalEvents( false );
3113 manager.toggleAriaIsolation( false );
3114 }
3115 manager.closing = null;
3116 manager.currentWindow = null;
3117 closing.resolve( data );
3118 } );
3119 }, manager.getTeardownDelay() );
3120 } );
3121 }, manager.getHoldDelay() );
3122 } );
3123 }
3124
3125 return closing.promise();
3126 };
3127
3128 /**
3129 * Add windows to the window manager.
3130 *
3131 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3132 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3133 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3134 *
3135 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3136 * by reference, symbolic name, or explicitly defined symbolic names.
3137 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3138 * explicit nor a statically configured symbolic name.
3139 */
3140 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3141 var i, len, win, name, list;
3142
3143 if ( Array.isArray( windows ) ) {
3144 // Convert to map of windows by looking up symbolic names from static configuration
3145 list = {};
3146 for ( i = 0, len = windows.length; i < len; i++ ) {
3147 name = windows[ i ].constructor.static.name;
3148 if ( typeof name !== 'string' ) {
3149 throw new Error( 'Cannot add window' );
3150 }
3151 list[ name ] = windows[ i ];
3152 }
3153 } else if ( OO.isPlainObject( windows ) ) {
3154 list = windows;
3155 }
3156
3157 // Add windows
3158 for ( name in list ) {
3159 win = list[ name ];
3160 this.windows[ name ] = win.toggle( false );
3161 this.$element.append( win.$element );
3162 win.setManager( this );
3163 }
3164 };
3165
3166 /**
3167 * Remove the specified windows from the windows manager.
3168 *
3169 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3170 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3171 * longer listens to events, use the #destroy method.
3172 *
3173 * @param {string[]} names Symbolic names of windows to remove
3174 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3175 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3176 */
3177 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3178 var i, len, win, name, cleanupWindow,
3179 manager = this,
3180 promises = [],
3181 cleanup = function ( name, win ) {
3182 delete manager.windows[ name ];
3183 win.$element.detach();
3184 };
3185
3186 for ( i = 0, len = names.length; i < len; i++ ) {
3187 name = names[ i ];
3188 win = this.windows[ name ];
3189 if ( !win ) {
3190 throw new Error( 'Cannot remove window' );
3191 }
3192 cleanupWindow = cleanup.bind( null, name, win );
3193 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3194 }
3195
3196 return $.when.apply( $, promises );
3197 };
3198
3199 /**
3200 * Remove all windows from the window manager.
3201 *
3202 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3203 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3204 * To remove just a subset of windows, use the #removeWindows method.
3205 *
3206 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3207 */
3208 OO.ui.WindowManager.prototype.clearWindows = function () {
3209 return this.removeWindows( Object.keys( this.windows ) );
3210 };
3211
3212 /**
3213 * Set dialog size. In general, this method should not be called directly.
3214 *
3215 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3216 *
3217 * @chainable
3218 */
3219 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3220 // Bypass for non-current, and thus invisible, windows
3221 if ( win !== this.currentWindow ) {
3222 return;
3223 }
3224
3225 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3226 sizes = this.constructor.static.sizes,
3227 size = win.getSize();
3228
3229 if ( !sizes[ size ] ) {
3230 size = this.constructor.static.defaultSize;
3231 }
3232 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3233 size = 'full';
3234 }
3235
3236 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3237 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3238 win.setDimensions( sizes[ size ] );
3239
3240 this.emit( 'resize', win );
3241
3242 return this;
3243 };
3244
3245 /**
3246 * Bind or unbind global events for scrolling.
3247 *
3248 * @private
3249 * @param {boolean} [on] Bind global events
3250 * @chainable
3251 */
3252 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3253 on = on === undefined ? !!this.globalEvents : !!on;
3254
3255 var $body = $( this.getElementDocument().body ),
3256 // We could have multiple window managers open to only modify
3257 // the body class at the bottom of the stack
3258 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3259
3260 if ( on ) {
3261 if ( !this.globalEvents ) {
3262 $( this.getElementWindow() ).on( {
3263 // Start listening for top-level window dimension changes
3264 'orientationchange resize': this.onWindowResizeHandler
3265 } );
3266 if ( stackDepth === 0 ) {
3267 $body.css( 'overflow', 'hidden' );
3268 }
3269 stackDepth++;
3270 this.globalEvents = true;
3271 }
3272 } else if ( this.globalEvents ) {
3273 $( this.getElementWindow() ).off( {
3274 // Stop listening for top-level window dimension changes
3275 'orientationchange resize': this.onWindowResizeHandler
3276 } );
3277 stackDepth--;
3278 if ( stackDepth === 0 ) {
3279 $( this.getElementDocument().body ).css( 'overflow', '' );
3280 }
3281 this.globalEvents = false;
3282 }
3283 $body.data( 'windowManagerGlobalEvents', stackDepth );
3284
3285 return this;
3286 };
3287
3288 /**
3289 * Toggle screen reader visibility of content other than the window manager.
3290 *
3291 * @private
3292 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3293 * @chainable
3294 */
3295 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3296 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3297
3298 if ( isolate ) {
3299 if ( !this.$ariaHidden ) {
3300 // Hide everything other than the window manager from screen readers
3301 this.$ariaHidden = $( 'body' )
3302 .children()
3303 .not( this.$element.parentsUntil( 'body' ).last() )
3304 .attr( 'aria-hidden', '' );
3305 }
3306 } else if ( this.$ariaHidden ) {
3307 // Restore screen reader visibility
3308 this.$ariaHidden.removeAttr( 'aria-hidden' );
3309 this.$ariaHidden = null;
3310 }
3311
3312 return this;
3313 };
3314
3315 /**
3316 * Destroy the window manager.
3317 *
3318 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3319 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3320 * instead.
3321 */
3322 OO.ui.WindowManager.prototype.destroy = function () {
3323 this.toggleGlobalEvents( false );
3324 this.toggleAriaIsolation( false );
3325 this.clearWindows();
3326 this.$element.remove();
3327 };
3328
3329 /**
3330 * @class
3331 *
3332 * @constructor
3333 * @param {string|jQuery} message Description of error
3334 * @param {Object} [config] Configuration options
3335 * @cfg {boolean} [recoverable=true] Error is recoverable
3336 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3337 */
3338 OO.ui.Error = function OoUiError( message, config ) {
3339 // Allow passing positional parameters inside the config object
3340 if ( OO.isPlainObject( message ) && config === undefined ) {
3341 config = message;
3342 message = config.message;
3343 }
3344
3345 // Configuration initialization
3346 config = config || {};
3347
3348 // Properties
3349 this.message = message instanceof jQuery ? message : String( message );
3350 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3351 this.warning = !!config.warning;
3352 };
3353
3354 /* Setup */
3355
3356 OO.initClass( OO.ui.Error );
3357
3358 /* Methods */
3359
3360 /**
3361 * Check if error can be recovered from.
3362 *
3363 * @return {boolean} Error is recoverable
3364 */
3365 OO.ui.Error.prototype.isRecoverable = function () {
3366 return this.recoverable;
3367 };
3368
3369 /**
3370 * Check if the error is a warning
3371 *
3372 * @return {boolean} Error is warning
3373 */
3374 OO.ui.Error.prototype.isWarning = function () {
3375 return this.warning;
3376 };
3377
3378 /**
3379 * Get error message as DOM nodes.
3380 *
3381 * @return {jQuery} Error message in DOM nodes
3382 */
3383 OO.ui.Error.prototype.getMessage = function () {
3384 return this.message instanceof jQuery ?
3385 this.message.clone() :
3386 $( '<div>' ).text( this.message ).contents();
3387 };
3388
3389 /**
3390 * Get error message as text.
3391 *
3392 * @return {string} Error message
3393 */
3394 OO.ui.Error.prototype.getMessageText = function () {
3395 return this.message instanceof jQuery ? this.message.text() : this.message;
3396 };
3397
3398 /**
3399 * Wraps an HTML snippet for use with configuration values which default
3400 * to strings. This bypasses the default html-escaping done to string
3401 * values.
3402 *
3403 * @class
3404 *
3405 * @constructor
3406 * @param {string} [content] HTML content
3407 */
3408 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3409 // Properties
3410 this.content = content;
3411 };
3412
3413 /* Setup */
3414
3415 OO.initClass( OO.ui.HtmlSnippet );
3416
3417 /* Methods */
3418
3419 /**
3420 * Render into HTML.
3421 *
3422 * @return {string} Unchanged HTML snippet.
3423 */
3424 OO.ui.HtmlSnippet.prototype.toString = function () {
3425 return this.content;
3426 };
3427
3428 /**
3429 * A list of functions, called in sequence.
3430 *
3431 * If a function added to a process returns boolean false the process will stop; if it returns an
3432 * object with a `promise` method the process will use the promise to either continue to the next
3433 * step when the promise is resolved or stop when the promise is rejected.
3434 *
3435 * @class
3436 *
3437 * @constructor
3438 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3439 * call, see #createStep for more information
3440 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3441 * or a promise
3442 * @return {Object} Step object, with `callback` and `context` properties
3443 */
3444 OO.ui.Process = function ( step, context ) {
3445 // Properties
3446 this.steps = [];
3447
3448 // Initialization
3449 if ( step !== undefined ) {
3450 this.next( step, context );
3451 }
3452 };
3453
3454 /* Setup */
3455
3456 OO.initClass( OO.ui.Process );
3457
3458 /* Methods */
3459
3460 /**
3461 * Start the process.
3462 *
3463 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3464 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3465 * process, the remaining steps will not be taken
3466 */
3467 OO.ui.Process.prototype.execute = function () {
3468 var i, len, promise;
3469
3470 /**
3471 * Continue execution.
3472 *
3473 * @ignore
3474 * @param {Array} step A function and the context it should be called in
3475 * @return {Function} Function that continues the process
3476 */
3477 function proceed( step ) {
3478 return function () {
3479 // Execute step in the correct context
3480 var deferred,
3481 result = step.callback.call( step.context );
3482
3483 if ( result === false ) {
3484 // Use rejected promise for boolean false results
3485 return $.Deferred().reject( [] ).promise();
3486 }
3487 if ( typeof result === 'number' ) {
3488 if ( result < 0 ) {
3489 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3490 }
3491 // Use a delayed promise for numbers, expecting them to be in milliseconds
3492 deferred = $.Deferred();
3493 setTimeout( deferred.resolve, result );
3494 return deferred.promise();
3495 }
3496 if ( result instanceof OO.ui.Error ) {
3497 // Use rejected promise for error
3498 return $.Deferred().reject( [ result ] ).promise();
3499 }
3500 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3501 // Use rejected promise for list of errors
3502 return $.Deferred().reject( result ).promise();
3503 }
3504 // Duck-type the object to see if it can produce a promise
3505 if ( result && $.isFunction( result.promise ) ) {
3506 // Use a promise generated from the result
3507 return result.promise();
3508 }
3509 // Use resolved promise for other results
3510 return $.Deferred().resolve().promise();
3511 };
3512 }
3513
3514 if ( this.steps.length ) {
3515 // Generate a chain reaction of promises
3516 promise = proceed( this.steps[ 0 ] )();
3517 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3518 promise = promise.then( proceed( this.steps[ i ] ) );
3519 }
3520 } else {
3521 promise = $.Deferred().resolve().promise();
3522 }
3523
3524 return promise;
3525 };
3526
3527 /**
3528 * Create a process step.
3529 *
3530 * @private
3531 * @param {number|jQuery.Promise|Function} step
3532 *
3533 * - Number of milliseconds to wait; or
3534 * - Promise to wait to be resolved; or
3535 * - Function to execute
3536 * - If it returns boolean false the process will stop
3537 * - If it returns an object with a `promise` method the process will use the promise to either
3538 * continue to the next step when the promise is resolved or stop when the promise is rejected
3539 * - If it returns a number, the process will wait for that number of milliseconds before
3540 * proceeding
3541 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3542 * or a promise
3543 * @return {Object} Step object, with `callback` and `context` properties
3544 */
3545 OO.ui.Process.prototype.createStep = function ( step, context ) {
3546 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3547 return {
3548 callback: function () {
3549 return step;
3550 },
3551 context: null
3552 };
3553 }
3554 if ( $.isFunction( step ) ) {
3555 return {
3556 callback: step,
3557 context: context
3558 };
3559 }
3560 throw new Error( 'Cannot create process step: number, promise or function expected' );
3561 };
3562
3563 /**
3564 * Add step to the beginning of the process.
3565 *
3566 * @inheritdoc #createStep
3567 * @return {OO.ui.Process} this
3568 * @chainable
3569 */
3570 OO.ui.Process.prototype.first = function ( step, context ) {
3571 this.steps.unshift( this.createStep( step, context ) );
3572 return this;
3573 };
3574
3575 /**
3576 * Add step to the end of the process.
3577 *
3578 * @inheritdoc #createStep
3579 * @return {OO.ui.Process} this
3580 * @chainable
3581 */
3582 OO.ui.Process.prototype.next = function ( step, context ) {
3583 this.steps.push( this.createStep( step, context ) );
3584 return this;
3585 };
3586
3587 /**
3588 * Factory for tools.
3589 *
3590 * @class
3591 * @extends OO.Factory
3592 * @constructor
3593 */
3594 OO.ui.ToolFactory = function OoUiToolFactory() {
3595 // Parent constructor
3596 OO.ui.ToolFactory.super.call( this );
3597 };
3598
3599 /* Setup */
3600
3601 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3602
3603 /* Methods */
3604
3605 /**
3606 * Get tools from the factory
3607 *
3608 * @param {Array} include Included tools
3609 * @param {Array} exclude Excluded tools
3610 * @param {Array} promote Promoted tools
3611 * @param {Array} demote Demoted tools
3612 * @return {string[]} List of tools
3613 */
3614 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3615 var i, len, included, promoted, demoted,
3616 auto = [],
3617 used = {};
3618
3619 // Collect included and not excluded tools
3620 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3621
3622 // Promotion
3623 promoted = this.extract( promote, used );
3624 demoted = this.extract( demote, used );
3625
3626 // Auto
3627 for ( i = 0, len = included.length; i < len; i++ ) {
3628 if ( !used[ included[ i ] ] ) {
3629 auto.push( included[ i ] );
3630 }
3631 }
3632
3633 return promoted.concat( auto ).concat( demoted );
3634 };
3635
3636 /**
3637 * Get a flat list of names from a list of names or groups.
3638 *
3639 * Tools can be specified in the following ways:
3640 *
3641 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3642 * - All tools in a group: `{ group: 'group-name' }`
3643 * - All tools: `'*'`
3644 *
3645 * @private
3646 * @param {Array|string} collection List of tools
3647 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3648 * names will be added as properties
3649 * @return {string[]} List of extracted names
3650 */
3651 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3652 var i, len, item, name, tool,
3653 names = [];
3654
3655 if ( collection === '*' ) {
3656 for ( name in this.registry ) {
3657 tool = this.registry[ name ];
3658 if (
3659 // Only add tools by group name when auto-add is enabled
3660 tool.static.autoAddToCatchall &&
3661 // Exclude already used tools
3662 ( !used || !used[ name ] )
3663 ) {
3664 names.push( name );
3665 if ( used ) {
3666 used[ name ] = true;
3667 }
3668 }
3669 }
3670 } else if ( Array.isArray( collection ) ) {
3671 for ( i = 0, len = collection.length; i < len; i++ ) {
3672 item = collection[ i ];
3673 // Allow plain strings as shorthand for named tools
3674 if ( typeof item === 'string' ) {
3675 item = { name: item };
3676 }
3677 if ( OO.isPlainObject( item ) ) {
3678 if ( item.group ) {
3679 for ( name in this.registry ) {
3680 tool = this.registry[ name ];
3681 if (
3682 // Include tools with matching group
3683 tool.static.group === item.group &&
3684 // Only add tools by group name when auto-add is enabled
3685 tool.static.autoAddToGroup &&
3686 // Exclude already used tools
3687 ( !used || !used[ name ] )
3688 ) {
3689 names.push( name );
3690 if ( used ) {
3691 used[ name ] = true;
3692 }
3693 }
3694 }
3695 // Include tools with matching name and exclude already used tools
3696 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3697 names.push( item.name );
3698 if ( used ) {
3699 used[ item.name ] = true;
3700 }
3701 }
3702 }
3703 }
3704 }
3705 return names;
3706 };
3707
3708 /**
3709 * Factory for tool groups.
3710 *
3711 * @class
3712 * @extends OO.Factory
3713 * @constructor
3714 */
3715 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3716 // Parent constructor
3717 OO.Factory.call( this );
3718
3719 var i, l,
3720 defaultClasses = this.constructor.static.getDefaultClasses();
3721
3722 // Register default toolgroups
3723 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3724 this.register( defaultClasses[ i ] );
3725 }
3726 };
3727
3728 /* Setup */
3729
3730 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3731
3732 /* Static Methods */
3733
3734 /**
3735 * Get a default set of classes to be registered on construction
3736 *
3737 * @return {Function[]} Default classes
3738 */
3739 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3740 return [
3741 OO.ui.BarToolGroup,
3742 OO.ui.ListToolGroup,
3743 OO.ui.MenuToolGroup
3744 ];
3745 };
3746
3747 /**
3748 * Theme logic.
3749 *
3750 * @abstract
3751 * @class
3752 *
3753 * @constructor
3754 * @param {Object} [config] Configuration options
3755 */
3756 OO.ui.Theme = function OoUiTheme( config ) {
3757 // Configuration initialization
3758 config = config || {};
3759 };
3760
3761 /* Setup */
3762
3763 OO.initClass( OO.ui.Theme );
3764
3765 /* Methods */
3766
3767 /**
3768 * Get a list of classes to be applied to a widget.
3769 *
3770 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3771 * otherwise state transitions will not work properly.
3772 *
3773 * @param {OO.ui.Element} element Element for which to get classes
3774 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3775 */
3776 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3777 return { on: [], off: [] };
3778 };
3779
3780 /**
3781 * Update CSS classes provided by the theme.
3782 *
3783 * For elements with theme logic hooks, this should be called any time there's a state change.
3784 *
3785 * @param {OO.ui.Element} element Element for which to update classes
3786 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3787 */
3788 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3789 var classes = this.getElementClasses( element );
3790
3791 element.$element
3792 .removeClass( classes.off.join( ' ' ) )
3793 .addClass( classes.on.join( ' ' ) );
3794 };
3795
3796 /**
3797 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3798 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3799 * order in which users will navigate through the focusable elements via the "tab" key.
3800 *
3801 * @example
3802 * // TabIndexedElement is mixed into the ButtonWidget class
3803 * // to provide a tabIndex property.
3804 * var button1 = new OO.ui.ButtonWidget( {
3805 * label: 'fourth',
3806 * tabIndex: 4
3807 * } );
3808 * var button2 = new OO.ui.ButtonWidget( {
3809 * label: 'second',
3810 * tabIndex: 2
3811 * } );
3812 * var button3 = new OO.ui.ButtonWidget( {
3813 * label: 'third',
3814 * tabIndex: 3
3815 * } );
3816 * var button4 = new OO.ui.ButtonWidget( {
3817 * label: 'first',
3818 * tabIndex: 1
3819 * } );
3820 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3821 *
3822 * @abstract
3823 * @class
3824 *
3825 * @constructor
3826 * @param {Object} [config] Configuration options
3827 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3828 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3829 * functionality will be applied to it instead.
3830 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3831 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3832 * to remove the element from the tab-navigation flow.
3833 */
3834 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3835 // Configuration initialization
3836 config = $.extend( { tabIndex: 0 }, config );
3837
3838 // Properties
3839 this.$tabIndexed = null;
3840 this.tabIndex = null;
3841
3842 // Events
3843 this.connect( this, { disable: 'onDisable' } );
3844
3845 // Initialization
3846 this.setTabIndex( config.tabIndex );
3847 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3848 };
3849
3850 /* Setup */
3851
3852 OO.initClass( OO.ui.TabIndexedElement );
3853
3854 /* Methods */
3855
3856 /**
3857 * Set the element that should use the tabindex functionality.
3858 *
3859 * This method is used to retarget a tabindex mixin so that its functionality applies
3860 * to the specified element. If an element is currently using the functionality, the mixin’s
3861 * effect on that element is removed before the new element is set up.
3862 *
3863 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3864 * @chainable
3865 */
3866 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3867 var tabIndex = this.tabIndex;
3868 // Remove attributes from old $tabIndexed
3869 this.setTabIndex( null );
3870 // Force update of new $tabIndexed
3871 this.$tabIndexed = $tabIndexed;
3872 this.tabIndex = tabIndex;
3873 return this.updateTabIndex();
3874 };
3875
3876 /**
3877 * Set the value of the tabindex.
3878 *
3879 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3880 * @chainable
3881 */
3882 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3883 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3884
3885 if ( this.tabIndex !== tabIndex ) {
3886 this.tabIndex = tabIndex;
3887 this.updateTabIndex();
3888 }
3889
3890 return this;
3891 };
3892
3893 /**
3894 * Update the `tabindex` attribute, in case of changes to tab index or
3895 * disabled state.
3896 *
3897 * @chainable
3898 */
3899 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3900 if ( this.$tabIndexed ) {
3901 if ( this.tabIndex !== null ) {
3902 // Do not index over disabled elements
3903 this.$tabIndexed.attr( {
3904 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3905 // ChromeVox and NVDA do not seem to inherit this from parent elements
3906 'aria-disabled': this.isDisabled().toString()
3907 } );
3908 } else {
3909 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3910 }
3911 }
3912 return this;
3913 };
3914
3915 /**
3916 * Handle disable events.
3917 *
3918 * @private
3919 * @param {boolean} disabled Element is disabled
3920 */
3921 OO.ui.TabIndexedElement.prototype.onDisable = function () {
3922 this.updateTabIndex();
3923 };
3924
3925 /**
3926 * Get the value of the tabindex.
3927 *
3928 * @return {number|null} Tabindex value
3929 */
3930 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3931 return this.tabIndex;
3932 };
3933
3934 /**
3935 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3936 * interface element that can be configured with access keys for accessibility.
3937 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3938 *
3939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3940 * @abstract
3941 * @class
3942 *
3943 * @constructor
3944 * @param {Object} [config] Configuration options
3945 * @cfg {jQuery} [$button] Button node, assigned to #$button, omit to use a generated `<a>`
3946 * @cfg {boolean} [framed=true] Render button with a frame
3947 * @cfg {string} [accessKey] Button's access key
3948 */
3949 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3950 // Configuration initialization
3951 config = config || {};
3952
3953 // Properties
3954 this.$button = null;
3955 this.framed = null;
3956 this.accessKey = null;
3957 this.active = false;
3958 this.onMouseUpHandler = this.onMouseUp.bind( this );
3959 this.onMouseDownHandler = this.onMouseDown.bind( this );
3960 this.onKeyDownHandler = this.onKeyDown.bind( this );
3961 this.onKeyUpHandler = this.onKeyUp.bind( this );
3962 this.onClickHandler = this.onClick.bind( this );
3963 this.onKeyPressHandler = this.onKeyPress.bind( this );
3964
3965 // Initialization
3966 this.$element.addClass( 'oo-ui-buttonElement' );
3967 this.toggleFramed( config.framed === undefined || config.framed );
3968 this.setAccessKey( config.accessKey );
3969 this.setButtonElement( config.$button || $( '<a>' ) );
3970 };
3971
3972 /* Setup */
3973
3974 OO.initClass( OO.ui.ButtonElement );
3975
3976 /* Static Properties */
3977
3978 /**
3979 * Cancel mouse down events.
3980 *
3981 * @static
3982 * @inheritable
3983 * @property {boolean}
3984 */
3985 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
3986
3987 /* Events */
3988
3989 /**
3990 * @event click
3991 */
3992
3993 /* Methods */
3994
3995 /**
3996 * Set the button element.
3997 *
3998 * If an element is already set, it will be cleaned up before setting up the new element.
3999 *
4000 * @param {jQuery} $button Element to use as button
4001 */
4002 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4003 if ( this.$button ) {
4004 this.$button
4005 .removeClass( 'oo-ui-buttonElement-button' )
4006 .removeAttr( 'role accesskey' )
4007 .off( {
4008 mousedown: this.onMouseDownHandler,
4009 keydown: this.onKeyDownHandler,
4010 click: this.onClickHandler,
4011 keypress: this.onKeyPressHandler
4012 } );
4013 }
4014
4015 this.$button = $button
4016 .addClass( 'oo-ui-buttonElement-button' )
4017 .attr( { role: 'button', accesskey: this.accessKey } )
4018 .on( {
4019 mousedown: this.onMouseDownHandler,
4020 keydown: this.onKeyDownHandler,
4021 click: this.onClickHandler,
4022 keypress: this.onKeyPressHandler
4023 } );
4024 };
4025
4026 /**
4027 * Handles mouse down events.
4028 *
4029 * @protected
4030 * @param {jQuery.Event} e Mouse down event
4031 */
4032 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4033 if ( this.isDisabled() || e.which !== 1 ) {
4034 return;
4035 }
4036 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4037 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4038 // reliably remove the pressed class
4039 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4040 // Prevent change of focus unless specifically configured otherwise
4041 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4042 return false;
4043 }
4044 };
4045
4046 /**
4047 * Handles mouse up events.
4048 *
4049 * @protected
4050 * @param {jQuery.Event} e Mouse up event
4051 */
4052 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4053 if ( this.isDisabled() || e.which !== 1 ) {
4054 return;
4055 }
4056 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4057 // Stop listening for mouseup, since we only needed this once
4058 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4059 };
4060
4061 /**
4062 * Handles mouse click events.
4063 *
4064 * @protected
4065 * @param {jQuery.Event} e Mouse click event
4066 * @fires click
4067 */
4068 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4069 if ( !this.isDisabled() && e.which === 1 ) {
4070 this.emit( 'click' );
4071 }
4072 return false;
4073 };
4074
4075 /**
4076 * Handles key down events.
4077 *
4078 * @protected
4079 * @param {jQuery.Event} e Key down event
4080 */
4081 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4082 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4083 return;
4084 }
4085 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4086 // Run the keyup handler no matter where the key is when the button is let go, so we can
4087 // reliably remove the pressed class
4088 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4089 };
4090
4091 /**
4092 * Handles key up events.
4093 *
4094 * @protected
4095 * @param {jQuery.Event} e Key up event
4096 */
4097 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4098 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4099 return;
4100 }
4101 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4102 // Stop listening for keyup, since we only needed this once
4103 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4104 };
4105
4106 /**
4107 * Handles key press events.
4108 *
4109 * @protected
4110 * @param {jQuery.Event} e Key press event
4111 * @fires click
4112 */
4113 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4114 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4115 this.emit( 'click' );
4116 return false;
4117 }
4118 };
4119
4120 /**
4121 * Check if button has a frame.
4122 *
4123 * @return {boolean} Button is framed
4124 */
4125 OO.ui.ButtonElement.prototype.isFramed = function () {
4126 return this.framed;
4127 };
4128
4129 /**
4130 * Toggle frame.
4131 *
4132 * @param {boolean} [framed] Make button framed, omit to toggle
4133 * @chainable
4134 */
4135 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4136 framed = framed === undefined ? !this.framed : !!framed;
4137 if ( framed !== this.framed ) {
4138 this.framed = framed;
4139 this.$element
4140 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4141 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4142 this.updateThemeClasses();
4143 }
4144
4145 return this;
4146 };
4147
4148 /**
4149 * Set access key.
4150 *
4151 * @param {string} accessKey Button's access key, use empty string to remove
4152 * @chainable
4153 */
4154 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4155 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4156
4157 if ( this.accessKey !== accessKey ) {
4158 if ( this.$button ) {
4159 if ( accessKey !== null ) {
4160 this.$button.attr( 'accesskey', accessKey );
4161 } else {
4162 this.$button.removeAttr( 'accesskey' );
4163 }
4164 }
4165 this.accessKey = accessKey;
4166 }
4167
4168 return this;
4169 };
4170
4171 /**
4172 * Set active state.
4173 *
4174 * @param {boolean} [value] Make button active
4175 * @chainable
4176 */
4177 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4178 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4179 return this;
4180 };
4181
4182 /**
4183 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4184 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4185 * items from the group is done through the interface the class provides.
4186 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4187 *
4188 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4189 *
4190 * @abstract
4191 * @class
4192 *
4193 * @constructor
4194 * @param {Object} [config] Configuration options
4195 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4196 * is omitted, the group element will use a generated `<div>`.
4197 */
4198 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4199 // Configuration initialization
4200 config = config || {};
4201
4202 // Properties
4203 this.$group = null;
4204 this.items = [];
4205 this.aggregateItemEvents = {};
4206
4207 // Initialization
4208 this.setGroupElement( config.$group || $( '<div>' ) );
4209 };
4210
4211 /* Methods */
4212
4213 /**
4214 * Set the group element.
4215 *
4216 * If an element is already set, items will be moved to the new element.
4217 *
4218 * @param {jQuery} $group Element to use as group
4219 */
4220 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4221 var i, len;
4222
4223 this.$group = $group;
4224 for ( i = 0, len = this.items.length; i < len; i++ ) {
4225 this.$group.append( this.items[ i ].$element );
4226 }
4227 };
4228
4229 /**
4230 * Check if a group contains no items.
4231 *
4232 * @return {boolean} Group is empty
4233 */
4234 OO.ui.GroupElement.prototype.isEmpty = function () {
4235 return !this.items.length;
4236 };
4237
4238 /**
4239 * Get all items in the group.
4240 *
4241 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4242 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4243 * from a group).
4244 *
4245 * @return {OO.ui.Element[]} An array of items.
4246 */
4247 OO.ui.GroupElement.prototype.getItems = function () {
4248 return this.items.slice( 0 );
4249 };
4250
4251 /**
4252 * Get an item by its data.
4253 *
4254 * Only the first item with matching data will be returned. To return all matching items,
4255 * use the #getItemsFromData method.
4256 *
4257 * @param {Object} data Item data to search for
4258 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4259 */
4260 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4261 var i, len, item,
4262 hash = OO.getHash( data );
4263
4264 for ( i = 0, len = this.items.length; i < len; i++ ) {
4265 item = this.items[ i ];
4266 if ( hash === OO.getHash( item.getData() ) ) {
4267 return item;
4268 }
4269 }
4270
4271 return null;
4272 };
4273
4274 /**
4275 * Get items by their data.
4276 *
4277 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4278 *
4279 * @param {Object} data Item data to search for
4280 * @return {OO.ui.Element[]} Items with equivalent data
4281 */
4282 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4283 var i, len, item,
4284 hash = OO.getHash( data ),
4285 items = [];
4286
4287 for ( i = 0, len = this.items.length; i < len; i++ ) {
4288 item = this.items[ i ];
4289 if ( hash === OO.getHash( item.getData() ) ) {
4290 items.push( item );
4291 }
4292 }
4293
4294 return items;
4295 };
4296
4297 /**
4298 * Aggregate the events emitted by the group.
4299 *
4300 * When events are aggregated, the group will listen to all contained items for the event,
4301 * and then emit the event under a new name. The new event will contain an additional leading
4302 * parameter containing the item that emitted the original event. Other arguments emitted from
4303 * the original event are passed through.
4304 *
4305 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4306 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4307 * A `null` value will remove aggregated events.
4308
4309 * @throws {Error} An error is thrown if aggregation already exists.
4310 */
4311 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4312 var i, len, item, add, remove, itemEvent, groupEvent;
4313
4314 for ( itemEvent in events ) {
4315 groupEvent = events[ itemEvent ];
4316
4317 // Remove existing aggregated event
4318 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4319 // Don't allow duplicate aggregations
4320 if ( groupEvent ) {
4321 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4322 }
4323 // Remove event aggregation from existing items
4324 for ( i = 0, len = this.items.length; i < len; i++ ) {
4325 item = this.items[ i ];
4326 if ( item.connect && item.disconnect ) {
4327 remove = {};
4328 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4329 item.disconnect( this, remove );
4330 }
4331 }
4332 // Prevent future items from aggregating event
4333 delete this.aggregateItemEvents[ itemEvent ];
4334 }
4335
4336 // Add new aggregate event
4337 if ( groupEvent ) {
4338 // Make future items aggregate event
4339 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4340 // Add event aggregation to existing items
4341 for ( i = 0, len = this.items.length; i < len; i++ ) {
4342 item = this.items[ i ];
4343 if ( item.connect && item.disconnect ) {
4344 add = {};
4345 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4346 item.connect( this, add );
4347 }
4348 }
4349 }
4350 }
4351 };
4352
4353 /**
4354 * Add items to the group.
4355 *
4356 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4357 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4358 *
4359 * @param {OO.ui.Element[]} items An array of items to add to the group
4360 * @param {number} [index] Index of the insertion point
4361 * @chainable
4362 */
4363 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4364 var i, len, item, event, events, currentIndex,
4365 itemElements = [];
4366
4367 for ( i = 0, len = items.length; i < len; i++ ) {
4368 item = items[ i ];
4369
4370 // Check if item exists then remove it first, effectively "moving" it
4371 currentIndex = $.inArray( item, this.items );
4372 if ( currentIndex >= 0 ) {
4373 this.removeItems( [ item ] );
4374 // Adjust index to compensate for removal
4375 if ( currentIndex < index ) {
4376 index--;
4377 }
4378 }
4379 // Add the item
4380 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4381 events = {};
4382 for ( event in this.aggregateItemEvents ) {
4383 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4384 }
4385 item.connect( this, events );
4386 }
4387 item.setElementGroup( this );
4388 itemElements.push( item.$element.get( 0 ) );
4389 }
4390
4391 if ( index === undefined || index < 0 || index >= this.items.length ) {
4392 this.$group.append( itemElements );
4393 this.items.push.apply( this.items, items );
4394 } else if ( index === 0 ) {
4395 this.$group.prepend( itemElements );
4396 this.items.unshift.apply( this.items, items );
4397 } else {
4398 this.items[ index ].$element.before( itemElements );
4399 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4400 }
4401
4402 return this;
4403 };
4404
4405 /**
4406 * Remove the specified items from a group.
4407 *
4408 * Removed items are detached (not removed) from the DOM so that they may be reused.
4409 * To remove all items from a group, you may wish to use the #clearItems method instead.
4410 *
4411 * @param {OO.ui.Element[]} items An array of items to remove
4412 * @chainable
4413 */
4414 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4415 var i, len, item, index, remove, itemEvent;
4416
4417 // Remove specific items
4418 for ( i = 0, len = items.length; i < len; i++ ) {
4419 item = items[ i ];
4420 index = $.inArray( item, this.items );
4421 if ( index !== -1 ) {
4422 if (
4423 item.connect && item.disconnect &&
4424 !$.isEmptyObject( this.aggregateItemEvents )
4425 ) {
4426 remove = {};
4427 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4428 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4429 }
4430 item.disconnect( this, remove );
4431 }
4432 item.setElementGroup( null );
4433 this.items.splice( index, 1 );
4434 item.$element.detach();
4435 }
4436 }
4437
4438 return this;
4439 };
4440
4441 /**
4442 * Clear all items from the group.
4443 *
4444 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4445 * To remove only a subset of items from a group, use the #removeItems method.
4446 *
4447 * @chainable
4448 */
4449 OO.ui.GroupElement.prototype.clearItems = function () {
4450 var i, len, item, remove, itemEvent;
4451
4452 // Remove all items
4453 for ( i = 0, len = this.items.length; i < len; i++ ) {
4454 item = this.items[ i ];
4455 if (
4456 item.connect && item.disconnect &&
4457 !$.isEmptyObject( this.aggregateItemEvents )
4458 ) {
4459 remove = {};
4460 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4461 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4462 }
4463 item.disconnect( this, remove );
4464 }
4465 item.setElementGroup( null );
4466 item.$element.detach();
4467 }
4468
4469 this.items = [];
4470 return this;
4471 };
4472
4473 /**
4474 * DraggableElement is a mixin class used to create elements that can be clicked
4475 * and dragged by a mouse to a new position within a group. This class must be used
4476 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4477 * the draggable elements.
4478 *
4479 * @abstract
4480 * @class
4481 *
4482 * @constructor
4483 */
4484 OO.ui.DraggableElement = function OoUiDraggableElement() {
4485 // Properties
4486 this.index = null;
4487
4488 // Initialize and events
4489 this.$element
4490 .attr( 'draggable', true )
4491 .addClass( 'oo-ui-draggableElement' )
4492 .on( {
4493 dragstart: this.onDragStart.bind( this ),
4494 dragover: this.onDragOver.bind( this ),
4495 dragend: this.onDragEnd.bind( this ),
4496 drop: this.onDrop.bind( this )
4497 } );
4498 };
4499
4500 OO.initClass( OO.ui.DraggableElement );
4501
4502 /* Events */
4503
4504 /**
4505 * @event dragstart
4506 *
4507 * A dragstart event is emitted when the user clicks and begins dragging an item.
4508 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4509 */
4510
4511 /**
4512 * @event dragend
4513 * A dragend event is emitted when the user drags an item and releases the mouse,
4514 * thus terminating the drag operation.
4515 */
4516
4517 /**
4518 * @event drop
4519 * A drop event is emitted when the user drags an item and then releases the mouse button
4520 * over a valid target.
4521 */
4522
4523 /* Static Properties */
4524
4525 /**
4526 * @inheritdoc OO.ui.ButtonElement
4527 */
4528 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4529
4530 /* Methods */
4531
4532 /**
4533 * Respond to dragstart event.
4534 *
4535 * @private
4536 * @param {jQuery.Event} event jQuery event
4537 * @fires dragstart
4538 */
4539 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4540 var dataTransfer = e.originalEvent.dataTransfer;
4541 // Define drop effect
4542 dataTransfer.dropEffect = 'none';
4543 dataTransfer.effectAllowed = 'move';
4544 // We must set up a dataTransfer data property or Firefox seems to
4545 // ignore the fact the element is draggable.
4546 try {
4547 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4548 } catch ( err ) {
4549 // The above is only for firefox. No need to set a catch clause
4550 // if it fails, move on.
4551 }
4552 // Add dragging class
4553 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4554 // Emit event
4555 this.emit( 'dragstart', this );
4556 return true;
4557 };
4558
4559 /**
4560 * Respond to dragend event.
4561 *
4562 * @private
4563 * @fires dragend
4564 */
4565 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4566 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4567 this.emit( 'dragend' );
4568 };
4569
4570 /**
4571 * Handle drop event.
4572 *
4573 * @private
4574 * @param {jQuery.Event} event jQuery event
4575 * @fires drop
4576 */
4577 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4578 e.preventDefault();
4579 this.emit( 'drop', e );
4580 };
4581
4582 /**
4583 * In order for drag/drop to work, the dragover event must
4584 * return false and stop propogation.
4585 *
4586 * @private
4587 */
4588 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4589 e.preventDefault();
4590 };
4591
4592 /**
4593 * Set item index.
4594 * Store it in the DOM so we can access from the widget drag event
4595 *
4596 * @private
4597 * @param {number} Item index
4598 */
4599 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4600 if ( this.index !== index ) {
4601 this.index = index;
4602 this.$element.data( 'index', index );
4603 }
4604 };
4605
4606 /**
4607 * Get item index
4608 *
4609 * @private
4610 * @return {number} Item index
4611 */
4612 OO.ui.DraggableElement.prototype.getIndex = function () {
4613 return this.index;
4614 };
4615
4616 /**
4617 * DraggableGroupElement is a mixin class used to create a group element to
4618 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4619 * The class is used with OO.ui.DraggableElement.
4620 *
4621 * @abstract
4622 * @class
4623 * @mixins OO.ui.GroupElement
4624 *
4625 * @constructor
4626 * @param {Object} [config] Configuration options
4627 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4628 * should match the layout of the items. Items displayed in a single row
4629 * or in several rows should use horizontal orientation. The vertical orientation should only be
4630 * used when the items are displayed in a single column. Defaults to 'vertical'
4631 */
4632 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4633 // Configuration initialization
4634 config = config || {};
4635
4636 // Parent constructor
4637 OO.ui.GroupElement.call( this, config );
4638
4639 // Properties
4640 this.orientation = config.orientation || 'vertical';
4641 this.dragItem = null;
4642 this.itemDragOver = null;
4643 this.itemKeys = {};
4644 this.sideInsertion = '';
4645
4646 // Events
4647 this.aggregate( {
4648 dragstart: 'itemDragStart',
4649 dragend: 'itemDragEnd',
4650 drop: 'itemDrop'
4651 } );
4652 this.connect( this, {
4653 itemDragStart: 'onItemDragStart',
4654 itemDrop: 'onItemDrop',
4655 itemDragEnd: 'onItemDragEnd'
4656 } );
4657 this.$element.on( {
4658 dragover: $.proxy( this.onDragOver, this ),
4659 dragleave: $.proxy( this.onDragLeave, this )
4660 } );
4661
4662 // Initialize
4663 if ( Array.isArray( config.items ) ) {
4664 this.addItems( config.items );
4665 }
4666 this.$placeholder = $( '<div>' )
4667 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4668 this.$element
4669 .addClass( 'oo-ui-draggableGroupElement' )
4670 .append( this.$status )
4671 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4672 .prepend( this.$placeholder );
4673 };
4674
4675 /* Setup */
4676 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4677
4678 /* Events */
4679
4680 /**
4681 * A 'reorder' event is emitted when the order of items in the group changes.
4682 *
4683 * @event reorder
4684 * @param {OO.ui.DraggableElement} item Reordered item
4685 * @param {number} [newIndex] New index for the item
4686 */
4687
4688 /* Methods */
4689
4690 /**
4691 * Respond to item drag start event
4692 *
4693 * @private
4694 * @param {OO.ui.DraggableElement} item Dragged item
4695 */
4696 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4697 var i, len;
4698
4699 // Map the index of each object
4700 for ( i = 0, len = this.items.length; i < len; i++ ) {
4701 this.items[ i ].setIndex( i );
4702 }
4703
4704 if ( this.orientation === 'horizontal' ) {
4705 // Set the height of the indicator
4706 this.$placeholder.css( {
4707 height: item.$element.outerHeight(),
4708 width: 2
4709 } );
4710 } else {
4711 // Set the width of the indicator
4712 this.$placeholder.css( {
4713 height: 2,
4714 width: item.$element.outerWidth()
4715 } );
4716 }
4717 this.setDragItem( item );
4718 };
4719
4720 /**
4721 * Respond to item drag end event
4722 *
4723 * @private
4724 */
4725 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4726 this.unsetDragItem();
4727 return false;
4728 };
4729
4730 /**
4731 * Handle drop event and switch the order of the items accordingly
4732 *
4733 * @private
4734 * @param {OO.ui.DraggableElement} item Dropped item
4735 * @fires reorder
4736 */
4737 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4738 var toIndex = item.getIndex();
4739 // Check if the dropped item is from the current group
4740 // TODO: Figure out a way to configure a list of legally droppable
4741 // elements even if they are not yet in the list
4742 if ( this.getDragItem() ) {
4743 // If the insertion point is 'after', the insertion index
4744 // is shifted to the right (or to the left in RTL, hence 'after')
4745 if ( this.sideInsertion === 'after' ) {
4746 toIndex++;
4747 }
4748 // Emit change event
4749 this.emit( 'reorder', this.getDragItem(), toIndex );
4750 }
4751 this.unsetDragItem();
4752 // Return false to prevent propogation
4753 return false;
4754 };
4755
4756 /**
4757 * Handle dragleave event.
4758 *
4759 * @private
4760 */
4761 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4762 // This means the item was dragged outside the widget
4763 this.$placeholder
4764 .css( 'left', 0 )
4765 .addClass( 'oo-ui-element-hidden' );
4766 };
4767
4768 /**
4769 * Respond to dragover event
4770 *
4771 * @private
4772 * @param {jQuery.Event} event Event details
4773 */
4774 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4775 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4776 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4777 clientX = e.originalEvent.clientX,
4778 clientY = e.originalEvent.clientY;
4779
4780 // Get the OptionWidget item we are dragging over
4781 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4782 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4783 if ( $optionWidget[ 0 ] ) {
4784 itemOffset = $optionWidget.offset();
4785 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4786 itemPosition = $optionWidget.position();
4787 itemIndex = $optionWidget.data( 'index' );
4788 }
4789
4790 if (
4791 itemOffset &&
4792 this.isDragging() &&
4793 itemIndex !== this.getDragItem().getIndex()
4794 ) {
4795 if ( this.orientation === 'horizontal' ) {
4796 // Calculate where the mouse is relative to the item width
4797 itemSize = itemBoundingRect.width;
4798 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4799 dragPosition = clientX;
4800 // Which side of the item we hover over will dictate
4801 // where the placeholder will appear, on the left or
4802 // on the right
4803 cssOutput = {
4804 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4805 top: itemPosition.top
4806 };
4807 } else {
4808 // Calculate where the mouse is relative to the item height
4809 itemSize = itemBoundingRect.height;
4810 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4811 dragPosition = clientY;
4812 // Which side of the item we hover over will dictate
4813 // where the placeholder will appear, on the top or
4814 // on the bottom
4815 cssOutput = {
4816 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4817 left: itemPosition.left
4818 };
4819 }
4820 // Store whether we are before or after an item to rearrange
4821 // For horizontal layout, we need to account for RTL, as this is flipped
4822 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4823 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4824 } else {
4825 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4826 }
4827 // Add drop indicator between objects
4828 this.$placeholder
4829 .css( cssOutput )
4830 .removeClass( 'oo-ui-element-hidden' );
4831 } else {
4832 // This means the item was dragged outside the widget
4833 this.$placeholder
4834 .css( 'left', 0 )
4835 .addClass( 'oo-ui-element-hidden' );
4836 }
4837 // Prevent default
4838 e.preventDefault();
4839 };
4840
4841 /**
4842 * Set a dragged item
4843 *
4844 * @param {OO.ui.DraggableElement} item Dragged item
4845 */
4846 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4847 this.dragItem = item;
4848 };
4849
4850 /**
4851 * Unset the current dragged item
4852 */
4853 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4854 this.dragItem = null;
4855 this.itemDragOver = null;
4856 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4857 this.sideInsertion = '';
4858 };
4859
4860 /**
4861 * Get the item that is currently being dragged.
4862 *
4863 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4864 */
4865 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4866 return this.dragItem;
4867 };
4868
4869 /**
4870 * Check if an item in the group is currently being dragged.
4871 *
4872 * @return {Boolean} Item is being dragged
4873 */
4874 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4875 return this.getDragItem() !== null;
4876 };
4877
4878 /**
4879 * IconElement is often mixed into other classes to generate an icon.
4880 * Icons are graphics, about the size of normal text. They are used to aid the user
4881 * in locating a control or to convey information in a space-efficient way. See the
4882 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4883 * included in the library.
4884 *
4885 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4886 *
4887 * @abstract
4888 * @class
4889 *
4890 * @constructor
4891 * @param {Object} [config] Configuration options
4892 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4893 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4894 * the icon element be set to an existing icon instead of the one generated by this class, set a
4895 * value using a jQuery selection. For example:
4896 *
4897 * // Use a <div> tag instead of a <span>
4898 * $icon: $("<div>")
4899 * // Use an existing icon element instead of the one generated by the class
4900 * $icon: this.$element
4901 * // Use an icon element from a child widget
4902 * $icon: this.childwidget.$element
4903 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4904 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4905 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4906 * by the user's language.
4907 *
4908 * Example of an i18n map:
4909 *
4910 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4911 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4912 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4913 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4914 * text. The icon title is displayed when users move the mouse over the icon.
4915 */
4916 OO.ui.IconElement = function OoUiIconElement( config ) {
4917 // Configuration initialization
4918 config = config || {};
4919
4920 // Properties
4921 this.$icon = null;
4922 this.icon = null;
4923 this.iconTitle = null;
4924
4925 // Initialization
4926 this.setIcon( config.icon || this.constructor.static.icon );
4927 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4928 this.setIconElement( config.$icon || $( '<span>' ) );
4929 };
4930
4931 /* Setup */
4932
4933 OO.initClass( OO.ui.IconElement );
4934
4935 /* Static Properties */
4936
4937 /**
4938 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4939 * for i18n purposes and contains a `default` icon name and additional names keyed by
4940 * language code. The `default` name is used when no icon is keyed by the user's language.
4941 *
4942 * Example of an i18n map:
4943 *
4944 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4945 *
4946 * Note: the static property will be overridden if the #icon configuration is used.
4947 *
4948 * @static
4949 * @inheritable
4950 * @property {Object|string}
4951 */
4952 OO.ui.IconElement.static.icon = null;
4953
4954 /**
4955 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4956 * function that returns title text, or `null` for no title.
4957 *
4958 * The static property will be overridden if the #iconTitle configuration is used.
4959 *
4960 * @static
4961 * @inheritable
4962 * @property {string|Function|null}
4963 */
4964 OO.ui.IconElement.static.iconTitle = null;
4965
4966 /* Methods */
4967
4968 /**
4969 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
4970 * applies to the specified icon element instead of the one created by the class. If an icon
4971 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
4972 * and mixin methods will no longer affect the element.
4973 *
4974 * @param {jQuery} $icon Element to use as icon
4975 */
4976 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
4977 if ( this.$icon ) {
4978 this.$icon
4979 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
4980 .removeAttr( 'title' );
4981 }
4982
4983 this.$icon = $icon
4984 .addClass( 'oo-ui-iconElement-icon' )
4985 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
4986 if ( this.iconTitle !== null ) {
4987 this.$icon.attr( 'title', this.iconTitle );
4988 }
4989 };
4990
4991 /**
4992 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
4993 * The icon parameter can also be set to a map of icon names. See the #icon config setting
4994 * for an example.
4995 *
4996 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
4997 * by language code, or `null` to remove the icon.
4998 * @chainable
4999 */
5000 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5001 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5002 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5003
5004 if ( this.icon !== icon ) {
5005 if ( this.$icon ) {
5006 if ( this.icon !== null ) {
5007 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5008 }
5009 if ( icon !== null ) {
5010 this.$icon.addClass( 'oo-ui-icon-' + icon );
5011 }
5012 }
5013 this.icon = icon;
5014 }
5015
5016 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5017 this.updateThemeClasses();
5018
5019 return this;
5020 };
5021
5022 /**
5023 * Set the icon title. Use `null` to remove the title.
5024 *
5025 * @param {string|Function|null} iconTitle A text string used as the icon title,
5026 * a function that returns title text, or `null` for no title.
5027 * @chainable
5028 */
5029 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5030 iconTitle = typeof iconTitle === 'function' ||
5031 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5032 OO.ui.resolveMsg( iconTitle ) : null;
5033
5034 if ( this.iconTitle !== iconTitle ) {
5035 this.iconTitle = iconTitle;
5036 if ( this.$icon ) {
5037 if ( this.iconTitle !== null ) {
5038 this.$icon.attr( 'title', iconTitle );
5039 } else {
5040 this.$icon.removeAttr( 'title' );
5041 }
5042 }
5043 }
5044
5045 return this;
5046 };
5047
5048 /**
5049 * Get the symbolic name of the icon.
5050 *
5051 * @return {string} Icon name
5052 */
5053 OO.ui.IconElement.prototype.getIcon = function () {
5054 return this.icon;
5055 };
5056
5057 /**
5058 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5059 *
5060 * @return {string} Icon title text
5061 */
5062 OO.ui.IconElement.prototype.getIconTitle = function () {
5063 return this.iconTitle;
5064 };
5065
5066 /**
5067 * IndicatorElement is often mixed into other classes to generate an indicator.
5068 * Indicators are small graphics that are generally used in two ways:
5069 *
5070 * - To draw attention to the status of an item. For example, an indicator might be
5071 * used to show that an item in a list has errors that need to be resolved.
5072 * - To clarify the function of a control that acts in an exceptional way (a button
5073 * that opens a menu instead of performing an action directly, for example).
5074 *
5075 * For a list of indicators included in the library, please see the
5076 * [OOjs UI documentation on MediaWiki] [1].
5077 *
5078 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5079 *
5080 * @abstract
5081 * @class
5082 *
5083 * @constructor
5084 * @param {Object} [config] Configuration options
5085 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5086 * configuration is omitted, the indicator element will use a generated `<span>`.
5087 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5088 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5089 * in the library.
5090 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5091 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5092 * or a function that returns title text. The indicator title is displayed when users move
5093 * the mouse over the indicator.
5094 */
5095 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5096 // Configuration initialization
5097 config = config || {};
5098
5099 // Properties
5100 this.$indicator = null;
5101 this.indicator = null;
5102 this.indicatorTitle = null;
5103
5104 // Initialization
5105 this.setIndicator( config.indicator || this.constructor.static.indicator );
5106 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5107 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5108 };
5109
5110 /* Setup */
5111
5112 OO.initClass( OO.ui.IndicatorElement );
5113
5114 /* Static Properties */
5115
5116 /**
5117 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5118 * The static property will be overridden if the #indicator configuration is used.
5119 *
5120 * @static
5121 * @inheritable
5122 * @property {string|null}
5123 */
5124 OO.ui.IndicatorElement.static.indicator = null;
5125
5126 /**
5127 * A text string used as the indicator title, a function that returns title text, or `null`
5128 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5129 *
5130 * @static
5131 * @inheritable
5132 * @property {string|Function|null}
5133 */
5134 OO.ui.IndicatorElement.static.indicatorTitle = null;
5135
5136 /* Methods */
5137
5138 /**
5139 * Set the indicator element.
5140 *
5141 * If an element is already set, it will be cleaned up before setting up the new element.
5142 *
5143 * @param {jQuery} $indicator Element to use as indicator
5144 */
5145 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5146 if ( this.$indicator ) {
5147 this.$indicator
5148 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5149 .removeAttr( 'title' );
5150 }
5151
5152 this.$indicator = $indicator
5153 .addClass( 'oo-ui-indicatorElement-indicator' )
5154 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5155 if ( this.indicatorTitle !== null ) {
5156 this.$indicator.attr( 'title', this.indicatorTitle );
5157 }
5158 };
5159
5160 /**
5161 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5162 *
5163 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5164 * @chainable
5165 */
5166 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5167 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5168
5169 if ( this.indicator !== indicator ) {
5170 if ( this.$indicator ) {
5171 if ( this.indicator !== null ) {
5172 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5173 }
5174 if ( indicator !== null ) {
5175 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5176 }
5177 }
5178 this.indicator = indicator;
5179 }
5180
5181 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5182 this.updateThemeClasses();
5183
5184 return this;
5185 };
5186
5187 /**
5188 * Set the indicator title.
5189 *
5190 * The title is displayed when a user moves the mouse over the indicator.
5191 *
5192 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5193 * `null` for no indicator title
5194 * @chainable
5195 */
5196 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5197 indicatorTitle = typeof indicatorTitle === 'function' ||
5198 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5199 OO.ui.resolveMsg( indicatorTitle ) : null;
5200
5201 if ( this.indicatorTitle !== indicatorTitle ) {
5202 this.indicatorTitle = indicatorTitle;
5203 if ( this.$indicator ) {
5204 if ( this.indicatorTitle !== null ) {
5205 this.$indicator.attr( 'title', indicatorTitle );
5206 } else {
5207 this.$indicator.removeAttr( 'title' );
5208 }
5209 }
5210 }
5211
5212 return this;
5213 };
5214
5215 /**
5216 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5217 *
5218 * @return {string} Symbolic name of indicator
5219 */
5220 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5221 return this.indicator;
5222 };
5223
5224 /**
5225 * Get the indicator title.
5226 *
5227 * The title is displayed when a user moves the mouse over the indicator.
5228 *
5229 * @return {string} Indicator title text
5230 */
5231 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5232 return this.indicatorTitle;
5233 };
5234
5235 /**
5236 * LabelElement is often mixed into other classes to generate a label, which
5237 * helps identify the function of an interface element.
5238 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5239 *
5240 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5241 *
5242 * @abstract
5243 * @class
5244 *
5245 * @constructor
5246 * @param {Object} [config] Configuration options
5247 * @cfg {jQuery} [$label] The label element created by the class. If this
5248 * configuration is omitted, the label element will use a generated `<span>`.
5249 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5250 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5251 * [OOjs UI documentation on MediaWiki] [2] for examples.
5252 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5253 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5254 * The label will be truncated to fit if necessary.
5255 */
5256 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5257 // Configuration initialization
5258 config = config || {};
5259
5260 // Properties
5261 this.$label = null;
5262 this.label = null;
5263 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5264
5265 // Initialization
5266 this.setLabel( config.label || this.constructor.static.label );
5267 this.setLabelElement( config.$label || $( '<span>' ) );
5268 };
5269
5270 /* Setup */
5271
5272 OO.initClass( OO.ui.LabelElement );
5273
5274 /* Events */
5275
5276 /**
5277 * @event labelChange
5278 * @param {string} value
5279 */
5280
5281 /* Static Properties */
5282
5283 /**
5284 * The label text. The label can be specified as a plaintext string, a function that will
5285 * produce a string in the future, or `null` for no label. The static value will
5286 * be overridden if a label is specified with the #label config option.
5287 *
5288 * @static
5289 * @inheritable
5290 * @property {string|Function|null}
5291 */
5292 OO.ui.LabelElement.static.label = null;
5293
5294 /* Methods */
5295
5296 /**
5297 * Set the label element.
5298 *
5299 * If an element is already set, it will be cleaned up before setting up the new element.
5300 *
5301 * @param {jQuery} $label Element to use as label
5302 */
5303 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5304 if ( this.$label ) {
5305 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5306 }
5307
5308 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5309 this.setLabelContent( this.label );
5310 };
5311
5312 /**
5313 * Set the label.
5314 *
5315 * An empty string will result in the label being hidden. A string containing only whitespace will
5316 * be converted to a single `&nbsp;`.
5317 *
5318 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5319 * text; or null for no label
5320 * @chainable
5321 */
5322 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5323 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5324 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5325
5326 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5327
5328 if ( this.label !== label ) {
5329 if ( this.$label ) {
5330 this.setLabelContent( label );
5331 }
5332 this.label = label;
5333 this.emit( 'labelChange' );
5334 }
5335
5336 return this;
5337 };
5338
5339 /**
5340 * Get the label.
5341 *
5342 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5343 * text; or null for no label
5344 */
5345 OO.ui.LabelElement.prototype.getLabel = function () {
5346 return this.label;
5347 };
5348
5349 /**
5350 * Fit the label.
5351 *
5352 * @chainable
5353 */
5354 OO.ui.LabelElement.prototype.fitLabel = function () {
5355 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5356 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5357 }
5358
5359 return this;
5360 };
5361
5362 /**
5363 * Set the content of the label.
5364 *
5365 * Do not call this method until after the label element has been set by #setLabelElement.
5366 *
5367 * @private
5368 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5369 * text; or null for no label
5370 */
5371 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5372 if ( typeof label === 'string' ) {
5373 if ( label.match( /^\s*$/ ) ) {
5374 // Convert whitespace only string to a single non-breaking space
5375 this.$label.html( '&nbsp;' );
5376 } else {
5377 this.$label.text( label );
5378 }
5379 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5380 this.$label.html( label.toString() );
5381 } else if ( label instanceof jQuery ) {
5382 this.$label.empty().append( label );
5383 } else {
5384 this.$label.empty();
5385 }
5386 };
5387
5388 /**
5389 * Mixin that adds a menu showing suggested values for a OO.ui.TextInputWidget.
5390 *
5391 * Subclasses that set the value of #lookupInput from #onLookupMenuItemChoose should
5392 * be aware that this will cause new suggestions to be looked up for the new value. If this is
5393 * not desired, disable lookups with #setLookupsDisabled, then set the value, then re-enable lookups.
5394 *
5395 * @class
5396 * @abstract
5397 *
5398 * @constructor
5399 * @param {Object} [config] Configuration options
5400 * @cfg {jQuery} [$overlay] Overlay for dropdown; defaults to relative positioning
5401 * @cfg {jQuery} [$container=this.$element] Element to render menu under
5402 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Whether suggestions will be requested
5403 * and shown when the user has not typed anything yet.
5404 */
5405 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5406 // Configuration initialization
5407 config = config || {};
5408
5409 // Properties
5410 this.$overlay = config.$overlay || this.$element;
5411 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5412 widget: this,
5413 input: this,
5414 $container: config.$container
5415 } );
5416
5417 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5418
5419 this.lookupCache = {};
5420 this.lookupQuery = null;
5421 this.lookupRequest = null;
5422 this.lookupsDisabled = false;
5423 this.lookupInputFocused = false;
5424
5425 // Events
5426 this.$input.on( {
5427 focus: this.onLookupInputFocus.bind( this ),
5428 blur: this.onLookupInputBlur.bind( this ),
5429 mousedown: this.onLookupInputMouseDown.bind( this )
5430 } );
5431 this.connect( this, { change: 'onLookupInputChange' } );
5432 this.lookupMenu.connect( this, {
5433 toggle: 'onLookupMenuToggle',
5434 choose: 'onLookupMenuItemChoose'
5435 } );
5436
5437 // Initialization
5438 this.$element.addClass( 'oo-ui-lookupElement' );
5439 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5440 this.$overlay.append( this.lookupMenu.$element );
5441 };
5442
5443 /* Methods */
5444
5445 /**
5446 * Handle input focus event.
5447 *
5448 * @param {jQuery.Event} e Input focus event
5449 */
5450 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5451 this.lookupInputFocused = true;
5452 this.populateLookupMenu();
5453 };
5454
5455 /**
5456 * Handle input blur event.
5457 *
5458 * @param {jQuery.Event} e Input blur event
5459 */
5460 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5461 this.closeLookupMenu();
5462 this.lookupInputFocused = false;
5463 };
5464
5465 /**
5466 * Handle input mouse down event.
5467 *
5468 * @param {jQuery.Event} e Input mouse down event
5469 */
5470 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5471 // Only open the menu if the input was already focused.
5472 // This way we allow the user to open the menu again after closing it with Esc
5473 // by clicking in the input. Opening (and populating) the menu when initially
5474 // clicking into the input is handled by the focus handler.
5475 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5476 this.populateLookupMenu();
5477 }
5478 };
5479
5480 /**
5481 * Handle input change event.
5482 *
5483 * @param {string} value New input value
5484 */
5485 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5486 if ( this.lookupInputFocused ) {
5487 this.populateLookupMenu();
5488 }
5489 };
5490
5491 /**
5492 * Handle the lookup menu being shown/hidden.
5493 *
5494 * @param {boolean} visible Whether the lookup menu is now visible.
5495 */
5496 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5497 if ( !visible ) {
5498 // When the menu is hidden, abort any active request and clear the menu.
5499 // This has to be done here in addition to closeLookupMenu(), because
5500 // MenuSelectWidget will close itself when the user presses Esc.
5501 this.abortLookupRequest();
5502 this.lookupMenu.clearItems();
5503 }
5504 };
5505
5506 /**
5507 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5508 *
5509 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5510 */
5511 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5512 if ( item ) {
5513 this.setValue( item.getData() );
5514 }
5515 };
5516
5517 /**
5518 * Get lookup menu.
5519 *
5520 * @return {OO.ui.TextInputMenuSelectWidget}
5521 */
5522 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5523 return this.lookupMenu;
5524 };
5525
5526 /**
5527 * Disable or re-enable lookups.
5528 *
5529 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5530 *
5531 * @param {boolean} disabled Disable lookups
5532 */
5533 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5534 this.lookupsDisabled = !!disabled;
5535 };
5536
5537 /**
5538 * Open the menu. If there are no entries in the menu, this does nothing.
5539 *
5540 * @chainable
5541 */
5542 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5543 if ( !this.lookupMenu.isEmpty() ) {
5544 this.lookupMenu.toggle( true );
5545 }
5546 return this;
5547 };
5548
5549 /**
5550 * Close the menu, empty it, and abort any pending request.
5551 *
5552 * @chainable
5553 */
5554 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5555 this.lookupMenu.toggle( false );
5556 this.abortLookupRequest();
5557 this.lookupMenu.clearItems();
5558 return this;
5559 };
5560
5561 /**
5562 * Request menu items based on the input's current value, and when they arrive,
5563 * populate the menu with these items and show the menu.
5564 *
5565 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5566 *
5567 * @chainable
5568 */
5569 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5570 var widget = this,
5571 value = this.getValue();
5572
5573 if ( this.lookupsDisabled ) {
5574 return;
5575 }
5576
5577 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5578 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5579 this.closeLookupMenu();
5580 // Skip population if there is already a request pending for the current value
5581 } else if ( value !== this.lookupQuery ) {
5582 this.getLookupMenuItems()
5583 .done( function ( items ) {
5584 widget.lookupMenu.clearItems();
5585 if ( items.length ) {
5586 widget.lookupMenu
5587 .addItems( items )
5588 .toggle( true );
5589 widget.initializeLookupMenuSelection();
5590 } else {
5591 widget.lookupMenu.toggle( false );
5592 }
5593 } )
5594 .fail( function () {
5595 widget.lookupMenu.clearItems();
5596 } );
5597 }
5598
5599 return this;
5600 };
5601
5602 /**
5603 * Select and highlight the first selectable item in the menu.
5604 *
5605 * @chainable
5606 */
5607 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5608 if ( !this.lookupMenu.getSelectedItem() ) {
5609 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5610 }
5611 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5612 };
5613
5614 /**
5615 * Get lookup menu items for the current query.
5616 *
5617 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5618 * the done event. If the request was aborted to make way for a subsequent request, this promise
5619 * will not be rejected: it will remain pending forever.
5620 */
5621 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5622 var widget = this,
5623 value = this.getValue(),
5624 deferred = $.Deferred(),
5625 ourRequest;
5626
5627 this.abortLookupRequest();
5628 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5629 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5630 } else {
5631 this.pushPending();
5632 this.lookupQuery = value;
5633 ourRequest = this.lookupRequest = this.getLookupRequest();
5634 ourRequest
5635 .always( function () {
5636 // We need to pop pending even if this is an old request, otherwise
5637 // the widget will remain pending forever.
5638 // TODO: this assumes that an aborted request will fail or succeed soon after
5639 // being aborted, or at least eventually. It would be nice if we could popPending()
5640 // at abort time, but only if we knew that we hadn't already called popPending()
5641 // for that request.
5642 widget.popPending();
5643 } )
5644 .done( function ( data ) {
5645 // If this is an old request (and aborting it somehow caused it to still succeed),
5646 // ignore its success completely
5647 if ( ourRequest === widget.lookupRequest ) {
5648 widget.lookupQuery = null;
5649 widget.lookupRequest = null;
5650 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( data );
5651 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5652 }
5653 } )
5654 .fail( function () {
5655 // If this is an old request (or a request failing because it's being aborted),
5656 // ignore its failure completely
5657 if ( ourRequest === widget.lookupRequest ) {
5658 widget.lookupQuery = null;
5659 widget.lookupRequest = null;
5660 deferred.reject();
5661 }
5662 } );
5663 }
5664 return deferred.promise();
5665 };
5666
5667 /**
5668 * Abort the currently pending lookup request, if any.
5669 */
5670 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5671 var oldRequest = this.lookupRequest;
5672 if ( oldRequest ) {
5673 // First unset this.lookupRequest to the fail handler will notice
5674 // that the request is no longer current
5675 this.lookupRequest = null;
5676 this.lookupQuery = null;
5677 oldRequest.abort();
5678 }
5679 };
5680
5681 /**
5682 * Get a new request object of the current lookup query value.
5683 *
5684 * @abstract
5685 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5686 */
5687 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5688 // Stub, implemented in subclass
5689 return null;
5690 };
5691
5692 /**
5693 * Pre-process data returned by the request from #getLookupRequest.
5694 *
5695 * The return value of this function will be cached, and any further queries for the given value
5696 * will use the cache rather than doing API requests.
5697 *
5698 * @abstract
5699 * @param {Mixed} data Response from server
5700 * @return {Mixed} Cached result data
5701 */
5702 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5703 // Stub, implemented in subclass
5704 return [];
5705 };
5706
5707 /**
5708 * Get a list of menu option widgets from the (possibly cached) data returned by
5709 * #getLookupCacheDataFromResponse.
5710 *
5711 * @abstract
5712 * @param {Mixed} data Cached result data, usually an array
5713 * @return {OO.ui.MenuOptionWidget[]} Menu items
5714 */
5715 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5716 // Stub, implemented in subclass
5717 return [];
5718 };
5719
5720 /**
5721 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5722 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5723 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5724 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5725 *
5726 * @abstract
5727 * @class
5728 *
5729 * @constructor
5730 * @param {Object} [config] Configuration options
5731 * @cfg {Object} [popup] Configuration to pass to popup
5732 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5733 */
5734 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5735 // Configuration initialization
5736 config = config || {};
5737
5738 // Properties
5739 this.popup = new OO.ui.PopupWidget( $.extend(
5740 { autoClose: true },
5741 config.popup,
5742 { $autoCloseIgnore: this.$element }
5743 ) );
5744 };
5745
5746 /* Methods */
5747
5748 /**
5749 * Get popup.
5750 *
5751 * @return {OO.ui.PopupWidget} Popup widget
5752 */
5753 OO.ui.PopupElement.prototype.getPopup = function () {
5754 return this.popup;
5755 };
5756
5757 /**
5758 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5759 * additional functionality to an element created by another class. The class provides
5760 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5761 * which are used to customize the look and feel of a widget to better describe its
5762 * importance and functionality.
5763 *
5764 * The library currently contains the following styling flags for general use:
5765 *
5766 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5767 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5768 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5769 *
5770 * The flags affect the appearance of the buttons:
5771 *
5772 * @example
5773 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5774 * var button1 = new OO.ui.ButtonWidget( {
5775 * label: 'Constructive',
5776 * flags: 'constructive'
5777 * } );
5778 * var button2 = new OO.ui.ButtonWidget( {
5779 * label: 'Destructive',
5780 * flags: 'destructive'
5781 * } );
5782 * var button3 = new OO.ui.ButtonWidget( {
5783 * label: 'Progressive',
5784 * flags: 'progressive'
5785 * } );
5786 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5787 *
5788 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5789 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5790 *
5791 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5792 *
5793 * @abstract
5794 * @class
5795 *
5796 * @constructor
5797 * @param {Object} [config] Configuration options
5798 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5799 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5800 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5801 * @cfg {jQuery} [$flagged] The flagged element. By default,
5802 * the flagged functionality is applied to the element created by the class ($element).
5803 * If a different element is specified, the flagged functionality will be applied to it instead.
5804 */
5805 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5806 // Configuration initialization
5807 config = config || {};
5808
5809 // Properties
5810 this.flags = {};
5811 this.$flagged = null;
5812
5813 // Initialization
5814 this.setFlags( config.flags );
5815 this.setFlaggedElement( config.$flagged || this.$element );
5816 };
5817
5818 /* Events */
5819
5820 /**
5821 * @event flag
5822 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5823 * parameter contains the name of each modified flag and indicates whether it was
5824 * added or removed.
5825 *
5826 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5827 * that the flag was added, `false` that the flag was removed.
5828 */
5829
5830 /* Methods */
5831
5832 /**
5833 * Set the flagged element.
5834 *
5835 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5836 * If an element is already set, the method will remove the mixin’s effect on that element.
5837 *
5838 * @param {jQuery} $flagged Element that should be flagged
5839 */
5840 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5841 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5842 return 'oo-ui-flaggedElement-' + flag;
5843 } ).join( ' ' );
5844
5845 if ( this.$flagged ) {
5846 this.$flagged.removeClass( classNames );
5847 }
5848
5849 this.$flagged = $flagged.addClass( classNames );
5850 };
5851
5852 /**
5853 * Check if the specified flag is set.
5854 *
5855 * @param {string} flag Name of flag
5856 * @return {boolean} The flag is set
5857 */
5858 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5859 return flag in this.flags;
5860 };
5861
5862 /**
5863 * Get the names of all flags set.
5864 *
5865 * @return {string[]} Flag names
5866 */
5867 OO.ui.FlaggedElement.prototype.getFlags = function () {
5868 return Object.keys( this.flags );
5869 };
5870
5871 /**
5872 * Clear all flags.
5873 *
5874 * @chainable
5875 * @fires flag
5876 */
5877 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5878 var flag, className,
5879 changes = {},
5880 remove = [],
5881 classPrefix = 'oo-ui-flaggedElement-';
5882
5883 for ( flag in this.flags ) {
5884 className = classPrefix + flag;
5885 changes[ flag ] = false;
5886 delete this.flags[ flag ];
5887 remove.push( className );
5888 }
5889
5890 if ( this.$flagged ) {
5891 this.$flagged.removeClass( remove.join( ' ' ) );
5892 }
5893
5894 this.updateThemeClasses();
5895 this.emit( 'flag', changes );
5896
5897 return this;
5898 };
5899
5900 /**
5901 * Add one or more flags.
5902 *
5903 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5904 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5905 * be added (`true`) or removed (`false`).
5906 * @chainable
5907 * @fires flag
5908 */
5909 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5910 var i, len, flag, className,
5911 changes = {},
5912 add = [],
5913 remove = [],
5914 classPrefix = 'oo-ui-flaggedElement-';
5915
5916 if ( typeof flags === 'string' ) {
5917 className = classPrefix + flags;
5918 // Set
5919 if ( !this.flags[ flags ] ) {
5920 this.flags[ flags ] = true;
5921 add.push( className );
5922 }
5923 } else if ( Array.isArray( flags ) ) {
5924 for ( i = 0, len = flags.length; i < len; i++ ) {
5925 flag = flags[ i ];
5926 className = classPrefix + flag;
5927 // Set
5928 if ( !this.flags[ flag ] ) {
5929 changes[ flag ] = true;
5930 this.flags[ flag ] = true;
5931 add.push( className );
5932 }
5933 }
5934 } else if ( OO.isPlainObject( flags ) ) {
5935 for ( flag in flags ) {
5936 className = classPrefix + flag;
5937 if ( flags[ flag ] ) {
5938 // Set
5939 if ( !this.flags[ flag ] ) {
5940 changes[ flag ] = true;
5941 this.flags[ flag ] = true;
5942 add.push( className );
5943 }
5944 } else {
5945 // Remove
5946 if ( this.flags[ flag ] ) {
5947 changes[ flag ] = false;
5948 delete this.flags[ flag ];
5949 remove.push( className );
5950 }
5951 }
5952 }
5953 }
5954
5955 if ( this.$flagged ) {
5956 this.$flagged
5957 .addClass( add.join( ' ' ) )
5958 .removeClass( remove.join( ' ' ) );
5959 }
5960
5961 this.updateThemeClasses();
5962 this.emit( 'flag', changes );
5963
5964 return this;
5965 };
5966
5967 /**
5968 * TitledElement is mixed into other classes to provide a `title` attribute.
5969 * Titles are rendered by the browser and are made visible when the user moves
5970 * the mouse over the element. Titles are not visible on touch devices.
5971 *
5972 * @example
5973 * // TitledElement provides a 'title' attribute to the
5974 * // ButtonWidget class
5975 * var button = new OO.ui.ButtonWidget( {
5976 * label: 'Button with Title',
5977 * title: 'I am a button'
5978 * } );
5979 * $( 'body' ).append( button.$element );
5980 *
5981 * @abstract
5982 * @class
5983 *
5984 * @constructor
5985 * @param {Object} [config] Configuration options
5986 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
5987 * If this config is omitted, the title functionality is applied to $element, the
5988 * element created by the class.
5989 * @cfg {string|Function} [title] The title text or a function that returns text. If
5990 * this config is omitted, the value of the {@link #static-title static title} property is used.
5991 */
5992 OO.ui.TitledElement = function OoUiTitledElement( config ) {
5993 // Configuration initialization
5994 config = config || {};
5995
5996 // Properties
5997 this.$titled = null;
5998 this.title = null;
5999
6000 // Initialization
6001 this.setTitle( config.title || this.constructor.static.title );
6002 this.setTitledElement( config.$titled || this.$element );
6003 };
6004
6005 /* Setup */
6006
6007 OO.initClass( OO.ui.TitledElement );
6008
6009 /* Static Properties */
6010
6011 /**
6012 * The title text, a function that returns text, or `null` for no title. The value of the static property
6013 * is overridden if the #title config option is used.
6014 *
6015 * @static
6016 * @inheritable
6017 * @property {string|Function|null}
6018 */
6019 OO.ui.TitledElement.static.title = null;
6020
6021 /* Methods */
6022
6023 /**
6024 * Set the titled element.
6025 *
6026 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6027 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6028 *
6029 * @param {jQuery} $titled Element that should use the 'titled' functionality
6030 */
6031 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6032 if ( this.$titled ) {
6033 this.$titled.removeAttr( 'title' );
6034 }
6035
6036 this.$titled = $titled;
6037 if ( this.title ) {
6038 this.$titled.attr( 'title', this.title );
6039 }
6040 };
6041
6042 /**
6043 * Set title.
6044 *
6045 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6046 * @chainable
6047 */
6048 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6049 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6050
6051 if ( this.title !== title ) {
6052 if ( this.$titled ) {
6053 if ( title !== null ) {
6054 this.$titled.attr( 'title', title );
6055 } else {
6056 this.$titled.removeAttr( 'title' );
6057 }
6058 }
6059 this.title = title;
6060 }
6061
6062 return this;
6063 };
6064
6065 /**
6066 * Get title.
6067 *
6068 * @return {string} Title string
6069 */
6070 OO.ui.TitledElement.prototype.getTitle = function () {
6071 return this.title;
6072 };
6073
6074 /**
6075 * Element that can be automatically clipped to visible boundaries.
6076 *
6077 * Whenever the element's natural height changes, you have to call
6078 * #clip to make sure it's still clipping correctly.
6079 *
6080 * @abstract
6081 * @class
6082 *
6083 * @constructor
6084 * @param {Object} [config] Configuration options
6085 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6086 */
6087 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6088 // Configuration initialization
6089 config = config || {};
6090
6091 // Properties
6092 this.$clippable = null;
6093 this.clipping = false;
6094 this.clippedHorizontally = false;
6095 this.clippedVertically = false;
6096 this.$clippableContainer = null;
6097 this.$clippableScroller = null;
6098 this.$clippableWindow = null;
6099 this.idealWidth = null;
6100 this.idealHeight = null;
6101 this.onClippableContainerScrollHandler = this.clip.bind( this );
6102 this.onClippableWindowResizeHandler = this.clip.bind( this );
6103
6104 // Initialization
6105 this.setClippableElement( config.$clippable || this.$element );
6106 };
6107
6108 /* Methods */
6109
6110 /**
6111 * Set clippable element.
6112 *
6113 * If an element is already set, it will be cleaned up before setting up the new element.
6114 *
6115 * @param {jQuery} $clippable Element to make clippable
6116 */
6117 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6118 if ( this.$clippable ) {
6119 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6120 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6121 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6122 }
6123
6124 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6125 this.clip();
6126 };
6127
6128 /**
6129 * Toggle clipping.
6130 *
6131 * Do not turn clipping on until after the element is attached to the DOM and visible.
6132 *
6133 * @param {boolean} [clipping] Enable clipping, omit to toggle
6134 * @chainable
6135 */
6136 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6137 clipping = clipping === undefined ? !this.clipping : !!clipping;
6138
6139 if ( this.clipping !== clipping ) {
6140 this.clipping = clipping;
6141 if ( clipping ) {
6142 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6143 // If the clippable container is the root, we have to listen to scroll events and check
6144 // jQuery.scrollTop on the window because of browser inconsistencies
6145 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6146 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6147 this.$clippableContainer;
6148 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6149 this.$clippableWindow = $( this.getElementWindow() )
6150 .on( 'resize', this.onClippableWindowResizeHandler );
6151 // Initial clip after visible
6152 this.clip();
6153 } else {
6154 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6155 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6156
6157 this.$clippableContainer = null;
6158 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6159 this.$clippableScroller = null;
6160 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6161 this.$clippableWindow = null;
6162 }
6163 }
6164
6165 return this;
6166 };
6167
6168 /**
6169 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6170 *
6171 * @return {boolean} Element will be clipped to the visible area
6172 */
6173 OO.ui.ClippableElement.prototype.isClipping = function () {
6174 return this.clipping;
6175 };
6176
6177 /**
6178 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6179 *
6180 * @return {boolean} Part of the element is being clipped
6181 */
6182 OO.ui.ClippableElement.prototype.isClipped = function () {
6183 return this.clippedHorizontally || this.clippedVertically;
6184 };
6185
6186 /**
6187 * Check if the right of the element is being clipped by the nearest scrollable container.
6188 *
6189 * @return {boolean} Part of the element is being clipped
6190 */
6191 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6192 return this.clippedHorizontally;
6193 };
6194
6195 /**
6196 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6197 *
6198 * @return {boolean} Part of the element is being clipped
6199 */
6200 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6201 return this.clippedVertically;
6202 };
6203
6204 /**
6205 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6206 *
6207 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6208 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6209 */
6210 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6211 this.idealWidth = width;
6212 this.idealHeight = height;
6213
6214 if ( !this.clipping ) {
6215 // Update dimensions
6216 this.$clippable.css( { width: width, height: height } );
6217 }
6218 // While clipping, idealWidth and idealHeight are not considered
6219 };
6220
6221 /**
6222 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6223 * the element's natural height changes.
6224 *
6225 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6226 * overlapped by, the visible area of the nearest scrollable container.
6227 *
6228 * @chainable
6229 */
6230 OO.ui.ClippableElement.prototype.clip = function () {
6231 if ( !this.clipping ) {
6232 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6233 return this;
6234 }
6235
6236 var buffer = 7, // Chosen by fair dice roll
6237 cOffset = this.$clippable.offset(),
6238 $container = this.$clippableContainer.is( 'html, body' ) ?
6239 this.$clippableWindow : this.$clippableContainer,
6240 ccOffset = $container.offset() || { top: 0, left: 0 },
6241 ccHeight = $container.innerHeight() - buffer,
6242 ccWidth = $container.innerWidth() - buffer,
6243 cHeight = this.$clippable.outerHeight() + buffer,
6244 cWidth = this.$clippable.outerWidth() + buffer,
6245 scrollTop = this.$clippableScroller.scrollTop(),
6246 scrollLeft = this.$clippableScroller.scrollLeft(),
6247 desiredWidth = cOffset.left < 0 ?
6248 cWidth + cOffset.left :
6249 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6250 desiredHeight = cOffset.top < 0 ?
6251 cHeight + cOffset.top :
6252 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6253 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6254 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6255 clipWidth = desiredWidth < naturalWidth,
6256 clipHeight = desiredHeight < naturalHeight;
6257
6258 if ( clipWidth ) {
6259 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6260 } else {
6261 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6262 }
6263 if ( clipHeight ) {
6264 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6265 } else {
6266 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6267 }
6268
6269 // If we stopped clipping in at least one of the dimensions
6270 if ( !clipWidth || !clipHeight ) {
6271 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6272 }
6273
6274 this.clippedHorizontally = clipWidth;
6275 this.clippedVertically = clipHeight;
6276
6277 return this;
6278 };
6279
6280 /**
6281 * Generic toolbar tool.
6282 *
6283 * @abstract
6284 * @class
6285 * @extends OO.ui.Widget
6286 * @mixins OO.ui.IconElement
6287 * @mixins OO.ui.FlaggedElement
6288 *
6289 * @constructor
6290 * @param {OO.ui.ToolGroup} toolGroup
6291 * @param {Object} [config] Configuration options
6292 * @cfg {string|Function} [title] Title text or a function that returns text
6293 */
6294 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6295 // Allow passing positional parameters inside the config object
6296 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6297 config = toolGroup;
6298 toolGroup = config.toolGroup;
6299 }
6300
6301 // Configuration initialization
6302 config = config || {};
6303
6304 // Parent constructor
6305 OO.ui.Tool.super.call( this, config );
6306
6307 // Mixin constructors
6308 OO.ui.IconElement.call( this, config );
6309 OO.ui.FlaggedElement.call( this, config );
6310
6311 // Properties
6312 this.toolGroup = toolGroup;
6313 this.toolbar = this.toolGroup.getToolbar();
6314 this.active = false;
6315 this.$title = $( '<span>' );
6316 this.$accel = $( '<span>' );
6317 this.$link = $( '<a>' );
6318 this.title = null;
6319
6320 // Events
6321 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6322
6323 // Initialization
6324 this.$title.addClass( 'oo-ui-tool-title' );
6325 this.$accel
6326 .addClass( 'oo-ui-tool-accel' )
6327 .prop( {
6328 // This may need to be changed if the key names are ever localized,
6329 // but for now they are essentially written in English
6330 dir: 'ltr',
6331 lang: 'en'
6332 } );
6333 this.$link
6334 .addClass( 'oo-ui-tool-link' )
6335 .append( this.$icon, this.$title, this.$accel )
6336 .prop( 'tabIndex', 0 )
6337 .attr( 'role', 'button' );
6338 this.$element
6339 .data( 'oo-ui-tool', this )
6340 .addClass(
6341 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6342 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6343 )
6344 .append( this.$link );
6345 this.setTitle( config.title || this.constructor.static.title );
6346 };
6347
6348 /* Setup */
6349
6350 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6351 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6352 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6353
6354 /* Events */
6355
6356 /**
6357 * @event select
6358 */
6359
6360 /* Static Properties */
6361
6362 /**
6363 * @static
6364 * @inheritdoc
6365 */
6366 OO.ui.Tool.static.tagName = 'span';
6367
6368 /**
6369 * Symbolic name of tool.
6370 *
6371 * @abstract
6372 * @static
6373 * @inheritable
6374 * @property {string}
6375 */
6376 OO.ui.Tool.static.name = '';
6377
6378 /**
6379 * Tool group.
6380 *
6381 * @abstract
6382 * @static
6383 * @inheritable
6384 * @property {string}
6385 */
6386 OO.ui.Tool.static.group = '';
6387
6388 /**
6389 * Tool title.
6390 *
6391 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6392 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6393 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6394 * appended to the title if the tool is part of a bar tool group.
6395 *
6396 * @abstract
6397 * @static
6398 * @inheritable
6399 * @property {string|Function} Title text or a function that returns text
6400 */
6401 OO.ui.Tool.static.title = '';
6402
6403 /**
6404 * Tool can be automatically added to catch-all groups.
6405 *
6406 * @static
6407 * @inheritable
6408 * @property {boolean}
6409 */
6410 OO.ui.Tool.static.autoAddToCatchall = true;
6411
6412 /**
6413 * Tool can be automatically added to named groups.
6414 *
6415 * @static
6416 * @property {boolean}
6417 * @inheritable
6418 */
6419 OO.ui.Tool.static.autoAddToGroup = true;
6420
6421 /**
6422 * Check if this tool is compatible with given data.
6423 *
6424 * @static
6425 * @inheritable
6426 * @param {Mixed} data Data to check
6427 * @return {boolean} Tool can be used with data
6428 */
6429 OO.ui.Tool.static.isCompatibleWith = function () {
6430 return false;
6431 };
6432
6433 /* Methods */
6434
6435 /**
6436 * Handle the toolbar state being updated.
6437 *
6438 * This is an abstract method that must be overridden in a concrete subclass.
6439 *
6440 * @abstract
6441 */
6442 OO.ui.Tool.prototype.onUpdateState = function () {
6443 throw new Error(
6444 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6445 );
6446 };
6447
6448 /**
6449 * Handle the tool being selected.
6450 *
6451 * This is an abstract method that must be overridden in a concrete subclass.
6452 *
6453 * @abstract
6454 */
6455 OO.ui.Tool.prototype.onSelect = function () {
6456 throw new Error(
6457 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6458 );
6459 };
6460
6461 /**
6462 * Check if the button is active.
6463 *
6464 * @return {boolean} Button is active
6465 */
6466 OO.ui.Tool.prototype.isActive = function () {
6467 return this.active;
6468 };
6469
6470 /**
6471 * Make the button appear active or inactive.
6472 *
6473 * @param {boolean} state Make button appear active
6474 */
6475 OO.ui.Tool.prototype.setActive = function ( state ) {
6476 this.active = !!state;
6477 if ( this.active ) {
6478 this.$element.addClass( 'oo-ui-tool-active' );
6479 } else {
6480 this.$element.removeClass( 'oo-ui-tool-active' );
6481 }
6482 };
6483
6484 /**
6485 * Get the tool title.
6486 *
6487 * @param {string|Function} title Title text or a function that returns text
6488 * @chainable
6489 */
6490 OO.ui.Tool.prototype.setTitle = function ( title ) {
6491 this.title = OO.ui.resolveMsg( title );
6492 this.updateTitle();
6493 return this;
6494 };
6495
6496 /**
6497 * Get the tool title.
6498 *
6499 * @return {string} Title text
6500 */
6501 OO.ui.Tool.prototype.getTitle = function () {
6502 return this.title;
6503 };
6504
6505 /**
6506 * Get the tool's symbolic name.
6507 *
6508 * @return {string} Symbolic name of tool
6509 */
6510 OO.ui.Tool.prototype.getName = function () {
6511 return this.constructor.static.name;
6512 };
6513
6514 /**
6515 * Update the title.
6516 */
6517 OO.ui.Tool.prototype.updateTitle = function () {
6518 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6519 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6520 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6521 tooltipParts = [];
6522
6523 this.$title.text( this.title );
6524 this.$accel.text( accel );
6525
6526 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6527 tooltipParts.push( this.title );
6528 }
6529 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6530 tooltipParts.push( accel );
6531 }
6532 if ( tooltipParts.length ) {
6533 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6534 } else {
6535 this.$link.removeAttr( 'title' );
6536 }
6537 };
6538
6539 /**
6540 * Destroy tool.
6541 */
6542 OO.ui.Tool.prototype.destroy = function () {
6543 this.toolbar.disconnect( this );
6544 this.$element.remove();
6545 };
6546
6547 /**
6548 * Collection of tool groups.
6549 *
6550 * @class
6551 * @extends OO.ui.Element
6552 * @mixins OO.EventEmitter
6553 * @mixins OO.ui.GroupElement
6554 *
6555 * @constructor
6556 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6557 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6558 * @param {Object} [config] Configuration options
6559 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6560 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6561 */
6562 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6563 // Allow passing positional parameters inside the config object
6564 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6565 config = toolFactory;
6566 toolFactory = config.toolFactory;
6567 toolGroupFactory = config.toolGroupFactory;
6568 }
6569
6570 // Configuration initialization
6571 config = config || {};
6572
6573 // Parent constructor
6574 OO.ui.Toolbar.super.call( this, config );
6575
6576 // Mixin constructors
6577 OO.EventEmitter.call( this );
6578 OO.ui.GroupElement.call( this, config );
6579
6580 // Properties
6581 this.toolFactory = toolFactory;
6582 this.toolGroupFactory = toolGroupFactory;
6583 this.groups = [];
6584 this.tools = {};
6585 this.$bar = $( '<div>' );
6586 this.$actions = $( '<div>' );
6587 this.initialized = false;
6588 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6589
6590 // Events
6591 this.$element
6592 .add( this.$bar ).add( this.$group ).add( this.$actions )
6593 .on( 'mousedown', this.onPointerDown.bind( this ) );
6594
6595 // Initialization
6596 this.$group.addClass( 'oo-ui-toolbar-tools' );
6597 if ( config.actions ) {
6598 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6599 }
6600 this.$bar
6601 .addClass( 'oo-ui-toolbar-bar' )
6602 .append( this.$group, '<div style="clear:both"></div>' );
6603 if ( config.shadow ) {
6604 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6605 }
6606 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6607 };
6608
6609 /* Setup */
6610
6611 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6612 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6613 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6614
6615 /* Methods */
6616
6617 /**
6618 * Get the tool factory.
6619 *
6620 * @return {OO.ui.ToolFactory} Tool factory
6621 */
6622 OO.ui.Toolbar.prototype.getToolFactory = function () {
6623 return this.toolFactory;
6624 };
6625
6626 /**
6627 * Get the tool group factory.
6628 *
6629 * @return {OO.Factory} Tool group factory
6630 */
6631 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6632 return this.toolGroupFactory;
6633 };
6634
6635 /**
6636 * Handles mouse down events.
6637 *
6638 * @param {jQuery.Event} e Mouse down event
6639 */
6640 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6641 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6642 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6643 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6644 return false;
6645 }
6646 };
6647
6648 /**
6649 * Handle window resize event.
6650 *
6651 * @private
6652 * @param {jQuery.Event} e Window resize event
6653 */
6654 OO.ui.Toolbar.prototype.onWindowResize = function () {
6655 this.$element.toggleClass(
6656 'oo-ui-toolbar-narrow',
6657 this.$bar.width() <= this.narrowThreshold
6658 );
6659 };
6660
6661 /**
6662 * Sets up handles and preloads required information for the toolbar to work.
6663 * This must be called after it is attached to a visible document and before doing anything else.
6664 */
6665 OO.ui.Toolbar.prototype.initialize = function () {
6666 this.initialized = true;
6667 this.narrowThreshold = this.$group.width() + this.$actions.width();
6668 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6669 this.onWindowResize();
6670 };
6671
6672 /**
6673 * Setup toolbar.
6674 *
6675 * Tools can be specified in the following ways:
6676 *
6677 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6678 * - All tools in a group: `{ group: 'group-name' }`
6679 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6680 *
6681 * @param {Object.<string,Array>} groups List of tool group configurations
6682 * @param {Array|string} [groups.include] Tools to include
6683 * @param {Array|string} [groups.exclude] Tools to exclude
6684 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6685 * @param {Array|string} [groups.demote] Tools to demote to the end
6686 */
6687 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6688 var i, len, type, group,
6689 items = [],
6690 defaultType = 'bar';
6691
6692 // Cleanup previous groups
6693 this.reset();
6694
6695 // Build out new groups
6696 for ( i = 0, len = groups.length; i < len; i++ ) {
6697 group = groups[ i ];
6698 if ( group.include === '*' ) {
6699 // Apply defaults to catch-all groups
6700 if ( group.type === undefined ) {
6701 group.type = 'list';
6702 }
6703 if ( group.label === undefined ) {
6704 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6705 }
6706 }
6707 // Check type has been registered
6708 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6709 items.push(
6710 this.getToolGroupFactory().create( type, this, group )
6711 );
6712 }
6713 this.addItems( items );
6714 };
6715
6716 /**
6717 * Remove all tools and groups from the toolbar.
6718 */
6719 OO.ui.Toolbar.prototype.reset = function () {
6720 var i, len;
6721
6722 this.groups = [];
6723 this.tools = {};
6724 for ( i = 0, len = this.items.length; i < len; i++ ) {
6725 this.items[ i ].destroy();
6726 }
6727 this.clearItems();
6728 };
6729
6730 /**
6731 * Destroys toolbar, removing event handlers and DOM elements.
6732 *
6733 * Call this whenever you are done using a toolbar.
6734 */
6735 OO.ui.Toolbar.prototype.destroy = function () {
6736 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
6737 this.reset();
6738 this.$element.remove();
6739 };
6740
6741 /**
6742 * Check if tool has not been used yet.
6743 *
6744 * @param {string} name Symbolic name of tool
6745 * @return {boolean} Tool is available
6746 */
6747 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6748 return !this.tools[ name ];
6749 };
6750
6751 /**
6752 * Prevent tool from being used again.
6753 *
6754 * @param {OO.ui.Tool} tool Tool to reserve
6755 */
6756 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6757 this.tools[ tool.getName() ] = tool;
6758 };
6759
6760 /**
6761 * Allow tool to be used again.
6762 *
6763 * @param {OO.ui.Tool} tool Tool to release
6764 */
6765 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6766 delete this.tools[ tool.getName() ];
6767 };
6768
6769 /**
6770 * Get accelerator label for tool.
6771 *
6772 * This is a stub that should be overridden to provide access to accelerator information.
6773 *
6774 * @param {string} name Symbolic name of tool
6775 * @return {string|undefined} Tool accelerator label if available
6776 */
6777 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6778 return undefined;
6779 };
6780
6781 /**
6782 * Collection of tools.
6783 *
6784 * Tools can be specified in the following ways:
6785 *
6786 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6787 * - All tools in a group: `{ group: 'group-name' }`
6788 * - All tools: `'*'`
6789 *
6790 * @abstract
6791 * @class
6792 * @extends OO.ui.Widget
6793 * @mixins OO.ui.GroupElement
6794 *
6795 * @constructor
6796 * @param {OO.ui.Toolbar} toolbar
6797 * @param {Object} [config] Configuration options
6798 * @cfg {Array|string} [include=[]] List of tools to include
6799 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6800 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6801 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6802 */
6803 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6804 // Allow passing positional parameters inside the config object
6805 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
6806 config = toolbar;
6807 toolbar = config.toolbar;
6808 }
6809
6810 // Configuration initialization
6811 config = config || {};
6812
6813 // Parent constructor
6814 OO.ui.ToolGroup.super.call( this, config );
6815
6816 // Mixin constructors
6817 OO.ui.GroupElement.call( this, config );
6818
6819 // Properties
6820 this.toolbar = toolbar;
6821 this.tools = {};
6822 this.pressed = null;
6823 this.autoDisabled = false;
6824 this.include = config.include || [];
6825 this.exclude = config.exclude || [];
6826 this.promote = config.promote || [];
6827 this.demote = config.demote || [];
6828 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6829
6830 // Events
6831 this.$element.on( {
6832 mousedown: this.onPointerDown.bind( this ),
6833 mouseup: this.onPointerUp.bind( this ),
6834 mouseover: this.onMouseOver.bind( this ),
6835 mouseout: this.onMouseOut.bind( this )
6836 } );
6837 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6838 this.aggregate( { disable: 'itemDisable' } );
6839 this.connect( this, { itemDisable: 'updateDisabled' } );
6840
6841 // Initialization
6842 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6843 this.$element
6844 .addClass( 'oo-ui-toolGroup' )
6845 .append( this.$group );
6846 this.populate();
6847 };
6848
6849 /* Setup */
6850
6851 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6852 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6853
6854 /* Events */
6855
6856 /**
6857 * @event update
6858 */
6859
6860 /* Static Properties */
6861
6862 /**
6863 * Show labels in tooltips.
6864 *
6865 * @static
6866 * @inheritable
6867 * @property {boolean}
6868 */
6869 OO.ui.ToolGroup.static.titleTooltips = false;
6870
6871 /**
6872 * Show acceleration labels in tooltips.
6873 *
6874 * @static
6875 * @inheritable
6876 * @property {boolean}
6877 */
6878 OO.ui.ToolGroup.static.accelTooltips = false;
6879
6880 /**
6881 * Automatically disable the toolgroup when all tools are disabled
6882 *
6883 * @static
6884 * @inheritable
6885 * @property {boolean}
6886 */
6887 OO.ui.ToolGroup.static.autoDisable = true;
6888
6889 /* Methods */
6890
6891 /**
6892 * @inheritdoc
6893 */
6894 OO.ui.ToolGroup.prototype.isDisabled = function () {
6895 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6896 };
6897
6898 /**
6899 * @inheritdoc
6900 */
6901 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6902 var i, item, allDisabled = true;
6903
6904 if ( this.constructor.static.autoDisable ) {
6905 for ( i = this.items.length - 1; i >= 0; i-- ) {
6906 item = this.items[ i ];
6907 if ( !item.isDisabled() ) {
6908 allDisabled = false;
6909 break;
6910 }
6911 }
6912 this.autoDisabled = allDisabled;
6913 }
6914 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6915 };
6916
6917 /**
6918 * Handle mouse down events.
6919 *
6920 * @param {jQuery.Event} e Mouse down event
6921 */
6922 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6923 if ( !this.isDisabled() && e.which === 1 ) {
6924 this.pressed = this.getTargetTool( e );
6925 if ( this.pressed ) {
6926 this.pressed.setActive( true );
6927 this.getElementDocument().addEventListener(
6928 'mouseup', this.onCapturedMouseUpHandler, true
6929 );
6930 }
6931 }
6932 return false;
6933 };
6934
6935 /**
6936 * Handle captured mouse up events.
6937 *
6938 * @param {Event} e Mouse up event
6939 */
6940 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6941 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6942 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6943 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6944 this.onPointerUp( e );
6945 };
6946
6947 /**
6948 * Handle mouse up events.
6949 *
6950 * @param {jQuery.Event} e Mouse up event
6951 */
6952 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
6953 var tool = this.getTargetTool( e );
6954
6955 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
6956 this.pressed.onSelect();
6957 }
6958
6959 this.pressed = null;
6960 return false;
6961 };
6962
6963 /**
6964 * Handle mouse over events.
6965 *
6966 * @param {jQuery.Event} e Mouse over event
6967 */
6968 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
6969 var tool = this.getTargetTool( e );
6970
6971 if ( this.pressed && this.pressed === tool ) {
6972 this.pressed.setActive( true );
6973 }
6974 };
6975
6976 /**
6977 * Handle mouse out events.
6978 *
6979 * @param {jQuery.Event} e Mouse out event
6980 */
6981 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
6982 var tool = this.getTargetTool( e );
6983
6984 if ( this.pressed && this.pressed === tool ) {
6985 this.pressed.setActive( false );
6986 }
6987 };
6988
6989 /**
6990 * Get the closest tool to a jQuery.Event.
6991 *
6992 * Only tool links are considered, which prevents other elements in the tool such as popups from
6993 * triggering tool group interactions.
6994 *
6995 * @private
6996 * @param {jQuery.Event} e
6997 * @return {OO.ui.Tool|null} Tool, `null` if none was found
6998 */
6999 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7000 var tool,
7001 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7002
7003 if ( $item.length ) {
7004 tool = $item.parent().data( 'oo-ui-tool' );
7005 }
7006
7007 return tool && !tool.isDisabled() ? tool : null;
7008 };
7009
7010 /**
7011 * Handle tool registry register events.
7012 *
7013 * If a tool is registered after the group is created, we must repopulate the list to account for:
7014 *
7015 * - a tool being added that may be included
7016 * - a tool already included being overridden
7017 *
7018 * @param {string} name Symbolic name of tool
7019 */
7020 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7021 this.populate();
7022 };
7023
7024 /**
7025 * Get the toolbar this group is in.
7026 *
7027 * @return {OO.ui.Toolbar} Toolbar of group
7028 */
7029 OO.ui.ToolGroup.prototype.getToolbar = function () {
7030 return this.toolbar;
7031 };
7032
7033 /**
7034 * Add and remove tools based on configuration.
7035 */
7036 OO.ui.ToolGroup.prototype.populate = function () {
7037 var i, len, name, tool,
7038 toolFactory = this.toolbar.getToolFactory(),
7039 names = {},
7040 add = [],
7041 remove = [],
7042 list = this.toolbar.getToolFactory().getTools(
7043 this.include, this.exclude, this.promote, this.demote
7044 );
7045
7046 // Build a list of needed tools
7047 for ( i = 0, len = list.length; i < len; i++ ) {
7048 name = list[ i ];
7049 if (
7050 // Tool exists
7051 toolFactory.lookup( name ) &&
7052 // Tool is available or is already in this group
7053 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7054 ) {
7055 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7056 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7057 this.toolbar.tools[ name ] = true;
7058 tool = this.tools[ name ];
7059 if ( !tool ) {
7060 // Auto-initialize tools on first use
7061 this.tools[ name ] = tool = toolFactory.create( name, this );
7062 tool.updateTitle();
7063 }
7064 this.toolbar.reserveTool( tool );
7065 add.push( tool );
7066 names[ name ] = true;
7067 }
7068 }
7069 // Remove tools that are no longer needed
7070 for ( name in this.tools ) {
7071 if ( !names[ name ] ) {
7072 this.tools[ name ].destroy();
7073 this.toolbar.releaseTool( this.tools[ name ] );
7074 remove.push( this.tools[ name ] );
7075 delete this.tools[ name ];
7076 }
7077 }
7078 if ( remove.length ) {
7079 this.removeItems( remove );
7080 }
7081 // Update emptiness state
7082 if ( add.length ) {
7083 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7084 } else {
7085 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7086 }
7087 // Re-add tools (moving existing ones to new locations)
7088 this.addItems( add );
7089 // Disabled state may depend on items
7090 this.updateDisabled();
7091 };
7092
7093 /**
7094 * Destroy tool group.
7095 */
7096 OO.ui.ToolGroup.prototype.destroy = function () {
7097 var name;
7098
7099 this.clearItems();
7100 this.toolbar.getToolFactory().disconnect( this );
7101 for ( name in this.tools ) {
7102 this.toolbar.releaseTool( this.tools[ name ] );
7103 this.tools[ name ].disconnect( this ).destroy();
7104 delete this.tools[ name ];
7105 }
7106 this.$element.remove();
7107 };
7108
7109 /**
7110 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7111 * consists of a header that contains the dialog title, a body with the message, and a footer that
7112 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7113 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7114 *
7115 * There are two basic types of message dialogs, confirmation and alert:
7116 *
7117 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7118 * more details about the consequences.
7119 * - **alert**: the dialog title describes which event occurred and the message provides more information
7120 * about why the event occurred.
7121 *
7122 * The MessageDialog class specifies two actions: ‘accept’, the primary
7123 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7124 * passing along the selected action.
7125 *
7126 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7127 *
7128 * @example
7129 * // Example: Creating and opening a message dialog window.
7130 * var messageDialog = new OO.ui.MessageDialog();
7131 *
7132 * // Create and append a window manager.
7133 * var windowManager = new OO.ui.WindowManager();
7134 * $( 'body' ).append( windowManager.$element );
7135 * windowManager.addWindows( [ messageDialog ] );
7136 * // Open the window.
7137 * windowManager.openWindow( messageDialog, {
7138 * title: 'Basic message dialog',
7139 * message: 'This is the message'
7140 * } );
7141 *
7142 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7143 *
7144 * @class
7145 * @extends OO.ui.Dialog
7146 *
7147 * @constructor
7148 * @param {Object} [config] Configuration options
7149 */
7150 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7151 // Parent constructor
7152 OO.ui.MessageDialog.super.call( this, config );
7153
7154 // Properties
7155 this.verticalActionLayout = null;
7156
7157 // Initialization
7158 this.$element.addClass( 'oo-ui-messageDialog' );
7159 };
7160
7161 /* Inheritance */
7162
7163 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7164
7165 /* Static Properties */
7166
7167 OO.ui.MessageDialog.static.name = 'message';
7168
7169 OO.ui.MessageDialog.static.size = 'small';
7170
7171 OO.ui.MessageDialog.static.verbose = false;
7172
7173 /**
7174 * Dialog title.
7175 *
7176 * The title of a confirmation dialog describes what a progressive action will do. The
7177 * title of an alert dialog describes which event occurred.
7178 *
7179 * @static
7180 * @inheritable
7181 * @property {jQuery|string|Function|null}
7182 */
7183 OO.ui.MessageDialog.static.title = null;
7184
7185 /**
7186 * The message displayed in the dialog body.
7187 *
7188 * A confirmation message describes the consequences of a progressive action. An alert
7189 * message describes why an event occurred.
7190 *
7191 * @static
7192 * @inheritable
7193 * @property {jQuery|string|Function|null}
7194 */
7195 OO.ui.MessageDialog.static.message = null;
7196
7197 OO.ui.MessageDialog.static.actions = [
7198 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7199 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7200 ];
7201
7202 /* Methods */
7203
7204 /**
7205 * @inheritdoc
7206 */
7207 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7208 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7209
7210 // Events
7211 this.manager.connect( this, {
7212 resize: 'onResize'
7213 } );
7214
7215 return this;
7216 };
7217
7218 /**
7219 * @inheritdoc
7220 */
7221 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7222 this.fitActions();
7223 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7224 };
7225
7226 /**
7227 * Handle window resized events.
7228 *
7229 * @private
7230 */
7231 OO.ui.MessageDialog.prototype.onResize = function () {
7232 var dialog = this;
7233 dialog.fitActions();
7234 // Wait for CSS transition to finish and do it again :(
7235 setTimeout( function () {
7236 dialog.fitActions();
7237 }, 300 );
7238 };
7239
7240 /**
7241 * Toggle action layout between vertical and horizontal.
7242 *
7243 *
7244 * @private
7245 * @param {boolean} [value] Layout actions vertically, omit to toggle
7246 * @chainable
7247 */
7248 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7249 value = value === undefined ? !this.verticalActionLayout : !!value;
7250
7251 if ( value !== this.verticalActionLayout ) {
7252 this.verticalActionLayout = value;
7253 this.$actions
7254 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7255 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7256 }
7257
7258 return this;
7259 };
7260
7261 /**
7262 * @inheritdoc
7263 */
7264 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7265 if ( action ) {
7266 return new OO.ui.Process( function () {
7267 this.close( { action: action } );
7268 }, this );
7269 }
7270 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7271 };
7272
7273 /**
7274 * @inheritdoc
7275 *
7276 * @param {Object} [data] Dialog opening data
7277 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7278 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7279 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7280 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7281 * action item
7282 */
7283 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7284 data = data || {};
7285
7286 // Parent method
7287 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7288 .next( function () {
7289 this.title.setLabel(
7290 data.title !== undefined ? data.title : this.constructor.static.title
7291 );
7292 this.message.setLabel(
7293 data.message !== undefined ? data.message : this.constructor.static.message
7294 );
7295 this.message.$element.toggleClass(
7296 'oo-ui-messageDialog-message-verbose',
7297 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7298 );
7299 }, this );
7300 };
7301
7302 /**
7303 * @inheritdoc
7304 */
7305 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7306 var bodyHeight, oldOverflow,
7307 $scrollable = this.container.$element;
7308
7309 oldOverflow = $scrollable[ 0 ].style.overflow;
7310 $scrollable[ 0 ].style.overflow = 'hidden';
7311
7312 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7313
7314 bodyHeight = this.text.$element.outerHeight( true );
7315 $scrollable[ 0 ].style.overflow = oldOverflow;
7316
7317 return bodyHeight;
7318 };
7319
7320 /**
7321 * @inheritdoc
7322 */
7323 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7324 var $scrollable = this.container.$element;
7325 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7326
7327 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7328 // Need to do it after transition completes (250ms), add 50ms just in case.
7329 setTimeout( function () {
7330 var oldOverflow = $scrollable[ 0 ].style.overflow;
7331 $scrollable[ 0 ].style.overflow = 'hidden';
7332
7333 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7334
7335 $scrollable[ 0 ].style.overflow = oldOverflow;
7336 }, 300 );
7337
7338 return this;
7339 };
7340
7341 /**
7342 * @inheritdoc
7343 */
7344 OO.ui.MessageDialog.prototype.initialize = function () {
7345 // Parent method
7346 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7347
7348 // Properties
7349 this.$actions = $( '<div>' );
7350 this.container = new OO.ui.PanelLayout( {
7351 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7352 } );
7353 this.text = new OO.ui.PanelLayout( {
7354 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7355 } );
7356 this.message = new OO.ui.LabelWidget( {
7357 classes: [ 'oo-ui-messageDialog-message' ]
7358 } );
7359
7360 // Initialization
7361 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7362 this.$content.addClass( 'oo-ui-messageDialog-content' );
7363 this.container.$element.append( this.text.$element );
7364 this.text.$element.append( this.title.$element, this.message.$element );
7365 this.$body.append( this.container.$element );
7366 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7367 this.$foot.append( this.$actions );
7368 };
7369
7370 /**
7371 * @inheritdoc
7372 */
7373 OO.ui.MessageDialog.prototype.attachActions = function () {
7374 var i, len, other, special, others;
7375
7376 // Parent method
7377 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7378
7379 special = this.actions.getSpecial();
7380 others = this.actions.getOthers();
7381 if ( special.safe ) {
7382 this.$actions.append( special.safe.$element );
7383 special.safe.toggleFramed( false );
7384 }
7385 if ( others.length ) {
7386 for ( i = 0, len = others.length; i < len; i++ ) {
7387 other = others[ i ];
7388 this.$actions.append( other.$element );
7389 other.toggleFramed( false );
7390 }
7391 }
7392 if ( special.primary ) {
7393 this.$actions.append( special.primary.$element );
7394 special.primary.toggleFramed( false );
7395 }
7396
7397 if ( !this.isOpening() ) {
7398 // If the dialog is currently opening, this will be called automatically soon.
7399 // This also calls #fitActions.
7400 this.updateSize();
7401 }
7402 };
7403
7404 /**
7405 * Fit action actions into columns or rows.
7406 *
7407 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7408 *
7409 * @private
7410 */
7411 OO.ui.MessageDialog.prototype.fitActions = function () {
7412 var i, len, action,
7413 previous = this.verticalActionLayout,
7414 actions = this.actions.get();
7415
7416 // Detect clipping
7417 this.toggleVerticalActionLayout( false );
7418 for ( i = 0, len = actions.length; i < len; i++ ) {
7419 action = actions[ i ];
7420 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7421 this.toggleVerticalActionLayout( true );
7422 break;
7423 }
7424 }
7425
7426 // Move the body out of the way of the foot
7427 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7428
7429 if ( this.verticalActionLayout !== previous ) {
7430 // We changed the layout, window height might need to be updated.
7431 this.updateSize();
7432 }
7433 };
7434
7435 /**
7436 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7437 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7438 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7439 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7440 * required for each process.
7441 *
7442 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7443 * processes with an animation. The header contains the dialog title as well as
7444 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7445 * a ‘primary’ action on the right (e.g., ‘Done’).
7446 *
7447 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7448 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7449 *
7450 * @example
7451 * // Example: Creating and opening a process dialog window.
7452 * function MyProcessDialog( config ) {
7453 * MyProcessDialog.super.call( this, config );
7454 * }
7455 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7456 *
7457 * MyProcessDialog.static.title = 'Process dialog';
7458 * MyProcessDialog.static.actions = [
7459 * { action: 'save', label: 'Done', flags: 'primary' },
7460 * { label: 'Cancel', flags: 'safe' }
7461 * ];
7462 *
7463 * MyProcessDialog.prototype.initialize = function () {
7464 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7465 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7466 * 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>' );
7467 * this.$body.append( this.content.$element );
7468 * };
7469 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7470 * var dialog = this;
7471 * if ( action ) {
7472 * return new OO.ui.Process( function () {
7473 * dialog.close( { action: action } );
7474 * } );
7475 * }
7476 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7477 * };
7478 *
7479 * var windowManager = new OO.ui.WindowManager();
7480 * $( 'body' ).append( windowManager.$element );
7481 *
7482 * var dialog = new MyProcessDialog();
7483 * windowManager.addWindows( [ dialog ] );
7484 * windowManager.openWindow( dialog );
7485 *
7486 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7487 *
7488 * @abstract
7489 * @class
7490 * @extends OO.ui.Dialog
7491 *
7492 * @constructor
7493 * @param {Object} [config] Configuration options
7494 */
7495 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7496 // Parent constructor
7497 OO.ui.ProcessDialog.super.call( this, config );
7498
7499 // Initialization
7500 this.$element.addClass( 'oo-ui-processDialog' );
7501 };
7502
7503 /* Setup */
7504
7505 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7506
7507 /* Methods */
7508
7509 /**
7510 * Handle dismiss button click events.
7511 *
7512 * Hides errors.
7513 *
7514 * @private
7515 */
7516 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7517 this.hideErrors();
7518 };
7519
7520 /**
7521 * Handle retry button click events.
7522 *
7523 * Hides errors and then tries again.
7524 *
7525 * @private
7526 */
7527 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7528 this.hideErrors();
7529 this.executeAction( this.currentAction );
7530 };
7531
7532 /**
7533 * @inheritdoc
7534 */
7535 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7536 if ( this.actions.isSpecial( action ) ) {
7537 this.fitLabel();
7538 }
7539 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7540 };
7541
7542 /**
7543 * @inheritdoc
7544 */
7545 OO.ui.ProcessDialog.prototype.initialize = function () {
7546 // Parent method
7547 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7548
7549 // Properties
7550 this.$navigation = $( '<div>' );
7551 this.$location = $( '<div>' );
7552 this.$safeActions = $( '<div>' );
7553 this.$primaryActions = $( '<div>' );
7554 this.$otherActions = $( '<div>' );
7555 this.dismissButton = new OO.ui.ButtonWidget( {
7556 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7557 } );
7558 this.retryButton = new OO.ui.ButtonWidget();
7559 this.$errors = $( '<div>' );
7560 this.$errorsTitle = $( '<div>' );
7561
7562 // Events
7563 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7564 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7565
7566 // Initialization
7567 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7568 this.$location
7569 .append( this.title.$element )
7570 .addClass( 'oo-ui-processDialog-location' );
7571 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7572 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7573 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7574 this.$errorsTitle
7575 .addClass( 'oo-ui-processDialog-errors-title' )
7576 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7577 this.$errors
7578 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7579 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7580 this.$content
7581 .addClass( 'oo-ui-processDialog-content' )
7582 .append( this.$errors );
7583 this.$navigation
7584 .addClass( 'oo-ui-processDialog-navigation' )
7585 .append( this.$safeActions, this.$location, this.$primaryActions );
7586 this.$head.append( this.$navigation );
7587 this.$foot.append( this.$otherActions );
7588 };
7589
7590 /**
7591 * @inheritdoc
7592 */
7593 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7594 var i, len, widgets = [];
7595 for ( i = 0, len = actions.length; i < len; i++ ) {
7596 widgets.push(
7597 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7598 );
7599 }
7600 return widgets;
7601 };
7602
7603 /**
7604 * @inheritdoc
7605 */
7606 OO.ui.ProcessDialog.prototype.attachActions = function () {
7607 var i, len, other, special, others;
7608
7609 // Parent method
7610 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7611
7612 special = this.actions.getSpecial();
7613 others = this.actions.getOthers();
7614 if ( special.primary ) {
7615 this.$primaryActions.append( special.primary.$element );
7616 }
7617 for ( i = 0, len = others.length; i < len; i++ ) {
7618 other = others[ i ];
7619 this.$otherActions.append( other.$element );
7620 }
7621 if ( special.safe ) {
7622 this.$safeActions.append( special.safe.$element );
7623 }
7624
7625 this.fitLabel();
7626 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7627 };
7628
7629 /**
7630 * @inheritdoc
7631 */
7632 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7633 var process = this;
7634 OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7635 .fail( function ( errors ) {
7636 process.showErrors( errors || [] );
7637 } );
7638 };
7639
7640 /**
7641 * Fit label between actions.
7642 *
7643 * @private
7644 * @chainable
7645 */
7646 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7647 var width = Math.max(
7648 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7649 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7650 );
7651 this.$location.css( { paddingLeft: width, paddingRight: width } );
7652
7653 return this;
7654 };
7655
7656 /**
7657 * Handle errors that occurred during accept or reject processes.
7658 *
7659 * @private
7660 * @param {OO.ui.Error[]} errors Errors to be handled
7661 */
7662 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7663 var i, len, $item, actions,
7664 items = [],
7665 abilities = {},
7666 recoverable = true,
7667 warning = false;
7668
7669 for ( i = 0, len = errors.length; i < len; i++ ) {
7670 if ( !errors[ i ].isRecoverable() ) {
7671 recoverable = false;
7672 }
7673 if ( errors[ i ].isWarning() ) {
7674 warning = true;
7675 }
7676 $item = $( '<div>' )
7677 .addClass( 'oo-ui-processDialog-error' )
7678 .append( errors[ i ].getMessage() );
7679 items.push( $item[ 0 ] );
7680 }
7681 this.$errorItems = $( items );
7682 if ( recoverable ) {
7683 abilities[this.currentAction] = true;
7684 // Copy the flags from the first matching action
7685 actions = this.actions.get( { actions: this.currentAction } );
7686 if ( actions.length ) {
7687 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7688 }
7689 } else {
7690 abilities[this.currentAction] = false;
7691 this.actions.setAbilities( abilities );
7692 }
7693 if ( warning ) {
7694 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7695 } else {
7696 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7697 }
7698 this.retryButton.toggle( recoverable );
7699 this.$errorsTitle.after( this.$errorItems );
7700 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7701 };
7702
7703 /**
7704 * Hide errors.
7705 *
7706 * @private
7707 */
7708 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7709 this.$errors.addClass( 'oo-ui-element-hidden' );
7710 if ( this.$errorItems ) {
7711 this.$errorItems.remove();
7712 this.$errorItems = null;
7713 }
7714 };
7715
7716 /**
7717 * @inheritdoc
7718 */
7719 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
7720 // Parent method
7721 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
7722 .first( function () {
7723 // Make sure to hide errors
7724 this.hideErrors();
7725 }, this );
7726 };
7727
7728 /**
7729 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7730 * which is a widget that is specified by reference before any optional configuration settings.
7731 *
7732 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7733 *
7734 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7735 * A left-alignment is used for forms with many fields.
7736 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7737 * A right-alignment is used for long but familiar forms which users tab through,
7738 * verifying the current field with a quick glance at the label.
7739 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7740 * that users fill out from top to bottom.
7741 * - **inline**: The label is placed after the field-widget and aligned to the left.
7742 * An inline-alignment is best used with checkboxes or radio buttons.
7743 *
7744 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7745 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7746 *
7747 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7748 * @class
7749 * @extends OO.ui.Layout
7750 * @mixins OO.ui.LabelElement
7751 *
7752 * @constructor
7753 * @param {OO.ui.Widget} fieldWidget Field widget
7754 * @param {Object} [config] Configuration options
7755 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7756 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7757 */
7758 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7759 // Allow passing positional parameters inside the config object
7760 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7761 config = fieldWidget;
7762 fieldWidget = config.fieldWidget;
7763 }
7764
7765 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7766
7767 // Configuration initialization
7768 config = $.extend( { align: 'left' }, config );
7769
7770 // Parent constructor
7771 OO.ui.FieldLayout.super.call( this, config );
7772
7773 // Mixin constructors
7774 OO.ui.LabelElement.call( this, config );
7775
7776 // Properties
7777 this.fieldWidget = fieldWidget;
7778 this.$field = $( '<div>' );
7779 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7780 this.align = null;
7781 if ( config.help ) {
7782 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7783 classes: [ 'oo-ui-fieldLayout-help' ],
7784 framed: false,
7785 icon: 'info'
7786 } );
7787
7788 this.popupButtonWidget.getPopup().$body.append(
7789 $( '<div>' )
7790 .text( config.help )
7791 .addClass( 'oo-ui-fieldLayout-help-content' )
7792 );
7793 this.$help = this.popupButtonWidget.$element;
7794 } else {
7795 this.$help = $( [] );
7796 }
7797
7798 // Events
7799 if ( hasInputWidget ) {
7800 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7801 }
7802 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7803
7804 // Initialization
7805 this.$element
7806 .addClass( 'oo-ui-fieldLayout' )
7807 .append( this.$help, this.$body );
7808 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7809 this.$field
7810 .addClass( 'oo-ui-fieldLayout-field' )
7811 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7812 .append( this.fieldWidget.$element );
7813
7814 this.setAlignment( config.align );
7815 };
7816
7817 /* Setup */
7818
7819 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7820 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7821
7822 /* Methods */
7823
7824 /**
7825 * Handle field disable events.
7826 *
7827 * @param {boolean} value Field is disabled
7828 */
7829 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7830 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7831 };
7832
7833 /**
7834 * Handle label mouse click events.
7835 *
7836 * @param {jQuery.Event} e Mouse click event
7837 */
7838 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7839 this.fieldWidget.simulateLabelClick();
7840 return false;
7841 };
7842
7843 /**
7844 * Get the field.
7845 *
7846 * @return {OO.ui.Widget} Field widget
7847 */
7848 OO.ui.FieldLayout.prototype.getField = function () {
7849 return this.fieldWidget;
7850 };
7851
7852 /**
7853 * Set the field alignment mode.
7854 *
7855 * @private
7856 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7857 * @chainable
7858 */
7859 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7860 if ( value !== this.align ) {
7861 // Default to 'left'
7862 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7863 value = 'left';
7864 }
7865 // Reorder elements
7866 if ( value === 'inline' ) {
7867 this.$body.append( this.$field, this.$label );
7868 } else {
7869 this.$body.append( this.$label, this.$field );
7870 }
7871 // Set classes. The following classes can be used here:
7872 // * oo-ui-fieldLayout-align-left
7873 // * oo-ui-fieldLayout-align-right
7874 // * oo-ui-fieldLayout-align-top
7875 // * oo-ui-fieldLayout-align-inline
7876 if ( this.align ) {
7877 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7878 }
7879 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7880 this.align = value;
7881 }
7882
7883 return this;
7884 };
7885
7886 /**
7887 * Layout made of a field, a button, and an optional label.
7888 *
7889 * @class
7890 * @extends OO.ui.FieldLayout
7891 *
7892 * @constructor
7893 * @param {OO.ui.Widget} fieldWidget Field widget
7894 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7895 * @param {Object} [config] Configuration options
7896 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7897 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7898 */
7899 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7900 // Allow passing positional parameters inside the config object
7901 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7902 config = fieldWidget;
7903 fieldWidget = config.fieldWidget;
7904 buttonWidget = config.buttonWidget;
7905 }
7906
7907 // Configuration initialization
7908 config = $.extend( { align: 'left' }, config );
7909
7910 // Parent constructor
7911 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7912
7913 // Properties
7914 this.fieldWidget = fieldWidget;
7915 this.buttonWidget = buttonWidget;
7916 this.$button = $( '<div>' )
7917 .addClass( 'oo-ui-actionFieldLayout-button' )
7918 .append( this.buttonWidget.$element );
7919 this.$input = $( '<div>' )
7920 .addClass( 'oo-ui-actionFieldLayout-input' )
7921 .append( this.fieldWidget.$element );
7922 this.$field
7923 .addClass( 'oo-ui-actionFieldLayout' )
7924 .append( this.$input, this.$button );
7925 };
7926
7927 /* Setup */
7928
7929 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7930
7931 /**
7932 * Layout made of a fieldset and optional legend.
7933 *
7934 * Just add OO.ui.FieldLayout items.
7935 *
7936 * @class
7937 * @extends OO.ui.Layout
7938 * @mixins OO.ui.IconElement
7939 * @mixins OO.ui.LabelElement
7940 * @mixins OO.ui.GroupElement
7941 *
7942 * @constructor
7943 * @param {Object} [config] Configuration options
7944 * @cfg {OO.ui.FieldLayout[]} [items] Items to add
7945 */
7946 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
7947 // Configuration initialization
7948 config = config || {};
7949
7950 // Parent constructor
7951 OO.ui.FieldsetLayout.super.call( this, config );
7952
7953 // Mixin constructors
7954 OO.ui.IconElement.call( this, config );
7955 OO.ui.LabelElement.call( this, config );
7956 OO.ui.GroupElement.call( this, config );
7957
7958 if ( config.help ) {
7959 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7960 classes: [ 'oo-ui-fieldsetLayout-help' ],
7961 framed: false,
7962 icon: 'info'
7963 } );
7964
7965 this.popupButtonWidget.getPopup().$body.append(
7966 $( '<div>' )
7967 .text( config.help )
7968 .addClass( 'oo-ui-fieldsetLayout-help-content' )
7969 );
7970 this.$help = this.popupButtonWidget.$element;
7971 } else {
7972 this.$help = $( [] );
7973 }
7974
7975 // Initialization
7976 this.$element
7977 .addClass( 'oo-ui-fieldsetLayout' )
7978 .prepend( this.$help, this.$icon, this.$label, this.$group );
7979 if ( Array.isArray( config.items ) ) {
7980 this.addItems( config.items );
7981 }
7982 };
7983
7984 /* Setup */
7985
7986 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
7987 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
7988 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
7989 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
7990
7991 /**
7992 * Layout with an HTML form.
7993 *
7994 * @class
7995 * @extends OO.ui.Layout
7996 * @mixins OO.ui.GroupElement
7997 *
7998 * @constructor
7999 * @param {Object} [config] Configuration options
8000 * @cfg {string} [method] HTML form `method` attribute
8001 * @cfg {string} [action] HTML form `action` attribute
8002 * @cfg {string} [enctype] HTML form `enctype` attribute
8003 * @cfg {OO.ui.FieldsetLayout[]} [items] Items to add
8004 */
8005 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8006 // Configuration initialization
8007 config = config || {};
8008
8009 // Parent constructor
8010 OO.ui.FormLayout.super.call( this, config );
8011
8012 // Mixin constructors
8013 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8014
8015 // Events
8016 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8017
8018 // Initialization
8019 this.$element
8020 .addClass( 'oo-ui-formLayout' )
8021 .attr( {
8022 method: config.method,
8023 action: config.action,
8024 enctype: config.enctype
8025 } );
8026 if ( Array.isArray( config.items ) ) {
8027 this.addItems( config.items );
8028 }
8029 };
8030
8031 /* Setup */
8032
8033 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8034 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8035
8036 /* Events */
8037
8038 /**
8039 * @event submit
8040 */
8041
8042 /* Static Properties */
8043
8044 OO.ui.FormLayout.static.tagName = 'form';
8045
8046 /* Methods */
8047
8048 /**
8049 * Handle form submit events.
8050 *
8051 * @param {jQuery.Event} e Submit event
8052 * @fires submit
8053 */
8054 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8055 this.emit( 'submit' );
8056 return false;
8057 };
8058
8059 /**
8060 * Layout with a content and menu area.
8061 *
8062 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8063 * all remaining space.
8064 *
8065 * @class
8066 * @extends OO.ui.Layout
8067 *
8068 * @constructor
8069 * @param {Object} [config] Configuration options
8070 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8071 * @cfg {boolean} [showMenu=true] Show menu
8072 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
8073 * @cfg {boolean} [collapse] Collapse the menu out of view
8074 */
8075 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8076 var positions = this.constructor.static.menuPositions;
8077
8078 // Configuration initialization
8079 config = config || {};
8080
8081 // Parent constructor
8082 OO.ui.MenuLayout.super.call( this, config );
8083
8084 // Properties
8085 this.showMenu = config.showMenu !== false;
8086 this.menuSize = config.menuSize || '18em';
8087 this.menuPosition = positions[ config.menuPosition ] || positions.before;
8088
8089 /**
8090 * Menu DOM node
8091 *
8092 * @property {jQuery}
8093 */
8094 this.$menu = $( '<div>' );
8095 /**
8096 * Content DOM node
8097 *
8098 * @property {jQuery}
8099 */
8100 this.$content = $( '<div>' );
8101
8102 // Initialization
8103 this.toggleMenu( this.showMenu );
8104 this.updateSizes();
8105 this.$menu
8106 .addClass( 'oo-ui-menuLayout-menu' )
8107 .css( this.menuPosition.sizeProperty, this.menuSize );
8108 this.$content.addClass( 'oo-ui-menuLayout-content' );
8109 this.$element
8110 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
8111 .append( this.$content, this.$menu );
8112 };
8113
8114 /* Setup */
8115
8116 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8117
8118 /* Static Properties */
8119
8120 OO.ui.MenuLayout.static.menuPositions = {
8121 top: {
8122 sizeProperty: 'height',
8123 className: 'oo-ui-menuLayout-top'
8124 },
8125 after: {
8126 sizeProperty: 'width',
8127 className: 'oo-ui-menuLayout-after'
8128 },
8129 bottom: {
8130 sizeProperty: 'height',
8131 className: 'oo-ui-menuLayout-bottom'
8132 },
8133 before: {
8134 sizeProperty: 'width',
8135 className: 'oo-ui-menuLayout-before'
8136 }
8137 };
8138
8139 /* Methods */
8140
8141 /**
8142 * Toggle menu.
8143 *
8144 * @param {boolean} showMenu Show menu, omit to toggle
8145 * @chainable
8146 */
8147 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8148 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8149
8150 if ( this.showMenu !== showMenu ) {
8151 this.showMenu = showMenu;
8152 this.updateSizes();
8153 }
8154
8155 return this;
8156 };
8157
8158 /**
8159 * Check if menu is visible
8160 *
8161 * @return {boolean} Menu is visible
8162 */
8163 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8164 return this.showMenu;
8165 };
8166
8167 /**
8168 * Set menu size.
8169 *
8170 * @param {number|string} size Size of menu in pixels or any CSS unit
8171 * @chainable
8172 */
8173 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
8174 this.menuSize = size;
8175 this.updateSizes();
8176
8177 return this;
8178 };
8179
8180 /**
8181 * Update menu and content CSS based on current menu size and visibility
8182 *
8183 * This method is called internally when size or position is changed.
8184 */
8185 OO.ui.MenuLayout.prototype.updateSizes = function () {
8186 if ( this.showMenu ) {
8187 this.$menu
8188 .css( this.menuPosition.sizeProperty, this.menuSize )
8189 .css( 'overflow', '' );
8190 // Set offsets on all sides. CSS resets all but one with
8191 // 'important' rules so directionality flips are supported
8192 this.$content.css( {
8193 top: this.menuSize,
8194 right: this.menuSize,
8195 bottom: this.menuSize,
8196 left: this.menuSize
8197 } );
8198 } else {
8199 this.$menu
8200 .css( this.menuPosition.sizeProperty, 0 )
8201 .css( 'overflow', 'hidden' );
8202 this.$content.css( {
8203 top: 0,
8204 right: 0,
8205 bottom: 0,
8206 left: 0
8207 } );
8208 }
8209 };
8210
8211 /**
8212 * Get menu size.
8213 *
8214 * @return {number|string} Menu size
8215 */
8216 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8217 return this.menuSize;
8218 };
8219
8220 /**
8221 * Set menu position.
8222 *
8223 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8224 * @throws {Error} If position value is not supported
8225 * @chainable
8226 */
8227 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8228 var positions = this.constructor.static.menuPositions;
8229
8230 if ( !positions[ position ] ) {
8231 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8232 }
8233
8234 this.$menu.css( this.menuPosition.sizeProperty, '' );
8235 this.$element.removeClass( this.menuPosition.className );
8236
8237 this.menuPosition = positions[ position ];
8238
8239 this.updateSizes();
8240 this.$element.addClass( this.menuPosition.className );
8241
8242 return this;
8243 };
8244
8245 /**
8246 * Get menu position.
8247 *
8248 * @return {string} Menu position
8249 */
8250 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8251 return this.menuPosition;
8252 };
8253
8254 /**
8255 * Layout containing a series of pages.
8256 *
8257 * @class
8258 * @extends OO.ui.MenuLayout
8259 *
8260 * @constructor
8261 * @param {Object} [config] Configuration options
8262 * @cfg {boolean} [continuous=false] Show all pages, one after another
8263 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
8264 * @cfg {boolean} [outlined=false] Show an outline
8265 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8266 */
8267 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8268 // Configuration initialization
8269 config = config || {};
8270
8271 // Parent constructor
8272 OO.ui.BookletLayout.super.call( this, config );
8273
8274 // Properties
8275 this.currentPageName = null;
8276 this.pages = {};
8277 this.ignoreFocus = false;
8278 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8279 this.$content.append( this.stackLayout.$element );
8280 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8281 this.outlineVisible = false;
8282 this.outlined = !!config.outlined;
8283 if ( this.outlined ) {
8284 this.editable = !!config.editable;
8285 this.outlineControlsWidget = null;
8286 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8287 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8288 this.$menu.append( this.outlinePanel.$element );
8289 this.outlineVisible = true;
8290 if ( this.editable ) {
8291 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8292 this.outlineSelectWidget
8293 );
8294 }
8295 }
8296 this.toggleMenu( this.outlined );
8297
8298 // Events
8299 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8300 if ( this.outlined ) {
8301 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8302 }
8303 if ( this.autoFocus ) {
8304 // Event 'focus' does not bubble, but 'focusin' does
8305 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8306 }
8307
8308 // Initialization
8309 this.$element.addClass( 'oo-ui-bookletLayout' );
8310 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8311 if ( this.outlined ) {
8312 this.outlinePanel.$element
8313 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8314 .append( this.outlineSelectWidget.$element );
8315 if ( this.editable ) {
8316 this.outlinePanel.$element
8317 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8318 .append( this.outlineControlsWidget.$element );
8319 }
8320 }
8321 };
8322
8323 /* Setup */
8324
8325 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8326
8327 /* Events */
8328
8329 /**
8330 * @event set
8331 * @param {OO.ui.PageLayout} page Current page
8332 */
8333
8334 /**
8335 * @event add
8336 * @param {OO.ui.PageLayout[]} page Added pages
8337 * @param {number} index Index pages were added at
8338 */
8339
8340 /**
8341 * @event remove
8342 * @param {OO.ui.PageLayout[]} pages Removed pages
8343 */
8344
8345 /* Methods */
8346
8347 /**
8348 * Handle stack layout focus.
8349 *
8350 * @param {jQuery.Event} e Focusin event
8351 */
8352 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8353 var name, $target;
8354
8355 // Find the page that an element was focused within
8356 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8357 for ( name in this.pages ) {
8358 // Check for page match, exclude current page to find only page changes
8359 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8360 this.setPage( name );
8361 break;
8362 }
8363 }
8364 };
8365
8366 /**
8367 * Handle stack layout set events.
8368 *
8369 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8370 */
8371 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8372 var layout = this;
8373 if ( page ) {
8374 page.scrollElementIntoView( { complete: function () {
8375 if ( layout.autoFocus ) {
8376 layout.focus();
8377 }
8378 } } );
8379 }
8380 };
8381
8382 /**
8383 * Focus the first input in the current page.
8384 *
8385 * If no page is selected, the first selectable page will be selected.
8386 * If the focus is already in an element on the current page, nothing will happen.
8387 */
8388 OO.ui.BookletLayout.prototype.focus = function () {
8389 var $input, page = this.stackLayout.getCurrentItem();
8390 if ( !page && this.outlined ) {
8391 this.selectFirstSelectablePage();
8392 page = this.stackLayout.getCurrentItem();
8393 }
8394 if ( !page ) {
8395 return;
8396 }
8397 // Only change the focus if is not already in the current page
8398 if ( !page.$element.find( ':focus' ).length ) {
8399 $input = page.$element.find( ':input:first' );
8400 if ( $input.length ) {
8401 $input[ 0 ].focus();
8402 }
8403 }
8404 };
8405
8406 /**
8407 * Handle outline widget select events.
8408 *
8409 * @param {OO.ui.OptionWidget|null} item Selected item
8410 */
8411 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8412 if ( item ) {
8413 this.setPage( item.getData() );
8414 }
8415 };
8416
8417 /**
8418 * Check if booklet has an outline.
8419 *
8420 * @return {boolean}
8421 */
8422 OO.ui.BookletLayout.prototype.isOutlined = function () {
8423 return this.outlined;
8424 };
8425
8426 /**
8427 * Check if booklet has editing controls.
8428 *
8429 * @return {boolean}
8430 */
8431 OO.ui.BookletLayout.prototype.isEditable = function () {
8432 return this.editable;
8433 };
8434
8435 /**
8436 * Check if booklet has a visible outline.
8437 *
8438 * @return {boolean}
8439 */
8440 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8441 return this.outlined && this.outlineVisible;
8442 };
8443
8444 /**
8445 * Hide or show the outline.
8446 *
8447 * @param {boolean} [show] Show outline, omit to invert current state
8448 * @chainable
8449 */
8450 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8451 if ( this.outlined ) {
8452 show = show === undefined ? !this.outlineVisible : !!show;
8453 this.outlineVisible = show;
8454 this.toggleMenu( show );
8455 }
8456
8457 return this;
8458 };
8459
8460 /**
8461 * Get the outline widget.
8462 *
8463 * @param {OO.ui.PageLayout} page Page to be selected
8464 * @return {OO.ui.PageLayout|null} Closest page to another
8465 */
8466 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8467 var next, prev, level,
8468 pages = this.stackLayout.getItems(),
8469 index = $.inArray( page, pages );
8470
8471 if ( index !== -1 ) {
8472 next = pages[ index + 1 ];
8473 prev = pages[ index - 1 ];
8474 // Prefer adjacent pages at the same level
8475 if ( this.outlined ) {
8476 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8477 if (
8478 prev &&
8479 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8480 ) {
8481 return prev;
8482 }
8483 if (
8484 next &&
8485 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8486 ) {
8487 return next;
8488 }
8489 }
8490 }
8491 return prev || next || null;
8492 };
8493
8494 /**
8495 * Get the outline widget.
8496 *
8497 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8498 */
8499 OO.ui.BookletLayout.prototype.getOutline = function () {
8500 return this.outlineSelectWidget;
8501 };
8502
8503 /**
8504 * Get the outline controls widget. If the outline is not editable, null is returned.
8505 *
8506 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8507 */
8508 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8509 return this.outlineControlsWidget;
8510 };
8511
8512 /**
8513 * Get a page by name.
8514 *
8515 * @param {string} name Symbolic name of page
8516 * @return {OO.ui.PageLayout|undefined} Page, if found
8517 */
8518 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8519 return this.pages[ name ];
8520 };
8521
8522 /**
8523 * Get the current page
8524 *
8525 * @return {OO.ui.PageLayout|undefined} Current page, if found
8526 */
8527 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8528 var name = this.getCurrentPageName();
8529 return name ? this.getPage( name ) : undefined;
8530 };
8531
8532 /**
8533 * Get the current page name.
8534 *
8535 * @return {string|null} Current page name
8536 */
8537 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8538 return this.currentPageName;
8539 };
8540
8541 /**
8542 * Add a page to the layout.
8543 *
8544 * When pages are added with the same names as existing pages, the existing pages will be
8545 * automatically removed before the new pages are added.
8546 *
8547 * @param {OO.ui.PageLayout[]} pages Pages to add
8548 * @param {number} index Index to insert pages after
8549 * @fires add
8550 * @chainable
8551 */
8552 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8553 var i, len, name, page, item, currentIndex,
8554 stackLayoutPages = this.stackLayout.getItems(),
8555 remove = [],
8556 items = [];
8557
8558 // Remove pages with same names
8559 for ( i = 0, len = pages.length; i < len; i++ ) {
8560 page = pages[ i ];
8561 name = page.getName();
8562
8563 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8564 // Correct the insertion index
8565 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8566 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8567 index--;
8568 }
8569 remove.push( this.pages[ name ] );
8570 }
8571 }
8572 if ( remove.length ) {
8573 this.removePages( remove );
8574 }
8575
8576 // Add new pages
8577 for ( i = 0, len = pages.length; i < len; i++ ) {
8578 page = pages[ i ];
8579 name = page.getName();
8580 this.pages[ page.getName() ] = page;
8581 if ( this.outlined ) {
8582 item = new OO.ui.OutlineOptionWidget( { data: name } );
8583 page.setOutlineItem( item );
8584 items.push( item );
8585 }
8586 }
8587
8588 if ( this.outlined && items.length ) {
8589 this.outlineSelectWidget.addItems( items, index );
8590 this.selectFirstSelectablePage();
8591 }
8592 this.stackLayout.addItems( pages, index );
8593 this.emit( 'add', pages, index );
8594
8595 return this;
8596 };
8597
8598 /**
8599 * Remove a page from the layout.
8600 *
8601 * @fires remove
8602 * @chainable
8603 */
8604 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8605 var i, len, name, page,
8606 items = [];
8607
8608 for ( i = 0, len = pages.length; i < len; i++ ) {
8609 page = pages[ i ];
8610 name = page.getName();
8611 delete this.pages[ name ];
8612 if ( this.outlined ) {
8613 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8614 page.setOutlineItem( null );
8615 }
8616 }
8617 if ( this.outlined && items.length ) {
8618 this.outlineSelectWidget.removeItems( items );
8619 this.selectFirstSelectablePage();
8620 }
8621 this.stackLayout.removeItems( pages );
8622 this.emit( 'remove', pages );
8623
8624 return this;
8625 };
8626
8627 /**
8628 * Clear all pages from the layout.
8629 *
8630 * @fires remove
8631 * @chainable
8632 */
8633 OO.ui.BookletLayout.prototype.clearPages = function () {
8634 var i, len,
8635 pages = this.stackLayout.getItems();
8636
8637 this.pages = {};
8638 this.currentPageName = null;
8639 if ( this.outlined ) {
8640 this.outlineSelectWidget.clearItems();
8641 for ( i = 0, len = pages.length; i < len; i++ ) {
8642 pages[ i ].setOutlineItem( null );
8643 }
8644 }
8645 this.stackLayout.clearItems();
8646
8647 this.emit( 'remove', pages );
8648
8649 return this;
8650 };
8651
8652 /**
8653 * Set the current page by name.
8654 *
8655 * @fires set
8656 * @param {string} name Symbolic name of page
8657 */
8658 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8659 var selectedItem,
8660 $focused,
8661 page = this.pages[ name ];
8662
8663 if ( name !== this.currentPageName ) {
8664 if ( this.outlined ) {
8665 selectedItem = this.outlineSelectWidget.getSelectedItem();
8666 if ( selectedItem && selectedItem.getData() !== name ) {
8667 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8668 }
8669 }
8670 if ( page ) {
8671 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8672 this.pages[ this.currentPageName ].setActive( false );
8673 // Blur anything focused if the next page doesn't have anything focusable - this
8674 // is not needed if the next page has something focusable because once it is focused
8675 // this blur happens automatically
8676 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8677 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8678 if ( $focused.length ) {
8679 $focused[ 0 ].blur();
8680 }
8681 }
8682 }
8683 this.currentPageName = name;
8684 this.stackLayout.setItem( page );
8685 page.setActive( true );
8686 this.emit( 'set', page );
8687 }
8688 }
8689 };
8690
8691 /**
8692 * Select the first selectable page.
8693 *
8694 * @chainable
8695 */
8696 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8697 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8698 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8699 }
8700
8701 return this;
8702 };
8703
8704 /**
8705 * Layout that expands to cover the entire area of its parent, with optional scrolling and padding.
8706 *
8707 * @class
8708 * @extends OO.ui.Layout
8709 *
8710 * @constructor
8711 * @param {Object} [config] Configuration options
8712 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8713 * @cfg {boolean} [padded=false] Pad the content from the edges
8714 * @cfg {boolean} [expanded=true] Expand size to fill the entire parent element
8715 * @cfg {boolean} [framed=false] Wrap in a frame to visually separate from outside content
8716 */
8717 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8718 // Configuration initialization
8719 config = $.extend( {
8720 scrollable: false,
8721 padded: false,
8722 expanded: true,
8723 framed: false
8724 }, config );
8725
8726 // Parent constructor
8727 OO.ui.PanelLayout.super.call( this, config );
8728
8729 // Initialization
8730 this.$element.addClass( 'oo-ui-panelLayout' );
8731 if ( config.scrollable ) {
8732 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8733 }
8734 if ( config.padded ) {
8735 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8736 }
8737 if ( config.expanded ) {
8738 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8739 }
8740 if ( config.framed ) {
8741 this.$element.addClass( 'oo-ui-panelLayout-framed' );
8742 }
8743 };
8744
8745 /* Setup */
8746
8747 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8748
8749 /**
8750 * Page within an booklet layout.
8751 *
8752 * @class
8753 * @extends OO.ui.PanelLayout
8754 *
8755 * @constructor
8756 * @param {string} name Unique symbolic name of page
8757 * @param {Object} [config] Configuration options
8758 */
8759 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8760 // Allow passing positional parameters inside the config object
8761 if ( OO.isPlainObject( name ) && config === undefined ) {
8762 config = name;
8763 name = config.name;
8764 }
8765
8766 // Configuration initialization
8767 config = $.extend( { scrollable: true }, config );
8768
8769 // Parent constructor
8770 OO.ui.PageLayout.super.call( this, config );
8771
8772 // Properties
8773 this.name = name;
8774 this.outlineItem = null;
8775 this.active = false;
8776
8777 // Initialization
8778 this.$element.addClass( 'oo-ui-pageLayout' );
8779 };
8780
8781 /* Setup */
8782
8783 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8784
8785 /* Events */
8786
8787 /**
8788 * @event active
8789 * @param {boolean} active Page is active
8790 */
8791
8792 /* Methods */
8793
8794 /**
8795 * Get page name.
8796 *
8797 * @return {string} Symbolic name of page
8798 */
8799 OO.ui.PageLayout.prototype.getName = function () {
8800 return this.name;
8801 };
8802
8803 /**
8804 * Check if page is active.
8805 *
8806 * @return {boolean} Page is active
8807 */
8808 OO.ui.PageLayout.prototype.isActive = function () {
8809 return this.active;
8810 };
8811
8812 /**
8813 * Get outline item.
8814 *
8815 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8816 */
8817 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8818 return this.outlineItem;
8819 };
8820
8821 /**
8822 * Set outline item.
8823 *
8824 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8825 * outline item as desired; this method is called for setting (with an object) and unsetting
8826 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8827 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8828 *
8829 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8830 * @chainable
8831 */
8832 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8833 this.outlineItem = outlineItem || null;
8834 if ( outlineItem ) {
8835 this.setupOutlineItem();
8836 }
8837 return this;
8838 };
8839
8840 /**
8841 * Setup outline item.
8842 *
8843 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8844 *
8845 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8846 * @chainable
8847 */
8848 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8849 return this;
8850 };
8851
8852 /**
8853 * Set page active state.
8854 *
8855 * @param {boolean} Page is active
8856 * @fires active
8857 */
8858 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8859 active = !!active;
8860
8861 if ( active !== this.active ) {
8862 this.active = active;
8863 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8864 this.emit( 'active', this.active );
8865 }
8866 };
8867
8868 /**
8869 * Layout containing a series of mutually exclusive pages.
8870 *
8871 * @class
8872 * @extends OO.ui.PanelLayout
8873 * @mixins OO.ui.GroupElement
8874 *
8875 * @constructor
8876 * @param {Object} [config] Configuration options
8877 * @cfg {boolean} [continuous=false] Show all pages, one after another
8878 * @cfg {OO.ui.Layout[]} [items] Layouts to add
8879 */
8880 OO.ui.StackLayout = function OoUiStackLayout( config ) {
8881 // Configuration initialization
8882 config = $.extend( { scrollable: true }, config );
8883
8884 // Parent constructor
8885 OO.ui.StackLayout.super.call( this, config );
8886
8887 // Mixin constructors
8888 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8889
8890 // Properties
8891 this.currentItem = null;
8892 this.continuous = !!config.continuous;
8893
8894 // Initialization
8895 this.$element.addClass( 'oo-ui-stackLayout' );
8896 if ( this.continuous ) {
8897 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
8898 }
8899 if ( Array.isArray( config.items ) ) {
8900 this.addItems( config.items );
8901 }
8902 };
8903
8904 /* Setup */
8905
8906 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
8907 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
8908
8909 /* Events */
8910
8911 /**
8912 * @event set
8913 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
8914 */
8915
8916 /* Methods */
8917
8918 /**
8919 * Get the current item.
8920 *
8921 * @return {OO.ui.Layout|null}
8922 */
8923 OO.ui.StackLayout.prototype.getCurrentItem = function () {
8924 return this.currentItem;
8925 };
8926
8927 /**
8928 * Unset the current item.
8929 *
8930 * @private
8931 * @param {OO.ui.StackLayout} layout
8932 * @fires set
8933 */
8934 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
8935 var prevItem = this.currentItem;
8936 if ( prevItem === null ) {
8937 return;
8938 }
8939
8940 this.currentItem = null;
8941 this.emit( 'set', null );
8942 };
8943
8944 /**
8945 * Add items.
8946 *
8947 * Adding an existing item (by value) will move it.
8948 *
8949 * @param {OO.ui.Layout[]} items Items to add
8950 * @param {number} [index] Index to insert items after
8951 * @chainable
8952 */
8953 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
8954 // Update the visibility
8955 this.updateHiddenState( items, this.currentItem );
8956
8957 // Mixin method
8958 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
8959
8960 if ( !this.currentItem && items.length ) {
8961 this.setItem( items[ 0 ] );
8962 }
8963
8964 return this;
8965 };
8966
8967 /**
8968 * Remove items.
8969 *
8970 * Items will be detached, not removed, so they can be used later.
8971 *
8972 * @param {OO.ui.Layout[]} items Items to remove
8973 * @chainable
8974 * @fires set
8975 */
8976 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
8977 // Mixin method
8978 OO.ui.GroupElement.prototype.removeItems.call( this, items );
8979
8980 if ( $.inArray( this.currentItem, items ) !== -1 ) {
8981 if ( this.items.length ) {
8982 this.setItem( this.items[ 0 ] );
8983 } else {
8984 this.unsetCurrentItem();
8985 }
8986 }
8987
8988 return this;
8989 };
8990
8991 /**
8992 * Clear all items.
8993 *
8994 * Items will be detached, not removed, so they can be used later.
8995 *
8996 * @chainable
8997 * @fires set
8998 */
8999 OO.ui.StackLayout.prototype.clearItems = function () {
9000 this.unsetCurrentItem();
9001 OO.ui.GroupElement.prototype.clearItems.call( this );
9002
9003 return this;
9004 };
9005
9006 /**
9007 * Show item.
9008 *
9009 * Any currently shown item will be hidden.
9010 *
9011 * FIXME: If the passed item to show has not been added in the items list, then
9012 * this method drops it and unsets the current item.
9013 *
9014 * @param {OO.ui.Layout} item Item to show
9015 * @chainable
9016 * @fires set
9017 */
9018 OO.ui.StackLayout.prototype.setItem = function ( item ) {
9019 if ( item !== this.currentItem ) {
9020 this.updateHiddenState( this.items, item );
9021
9022 if ( $.inArray( item, this.items ) !== -1 ) {
9023 this.currentItem = item;
9024 this.emit( 'set', item );
9025 } else {
9026 this.unsetCurrentItem();
9027 }
9028 }
9029
9030 return this;
9031 };
9032
9033 /**
9034 * Update the visibility of all items in case of non-continuous view.
9035 *
9036 * Ensure all items are hidden except for the selected one.
9037 * This method does nothing when the stack is continuous.
9038 *
9039 * @param {OO.ui.Layout[]} items Item list iterate over
9040 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9041 */
9042 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
9043 var i, len;
9044
9045 if ( !this.continuous ) {
9046 for ( i = 0, len = items.length; i < len; i++ ) {
9047 if ( !selectedItem || selectedItem !== items[ i ] ) {
9048 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
9049 }
9050 }
9051 if ( selectedItem ) {
9052 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
9053 }
9054 }
9055 };
9056
9057 /**
9058 * Horizontal bar layout of tools as icon buttons.
9059 *
9060 * @class
9061 * @extends OO.ui.ToolGroup
9062 *
9063 * @constructor
9064 * @param {OO.ui.Toolbar} toolbar
9065 * @param {Object} [config] Configuration options
9066 */
9067 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
9068 // Allow passing positional parameters inside the config object
9069 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9070 config = toolbar;
9071 toolbar = config.toolbar;
9072 }
9073
9074 // Parent constructor
9075 OO.ui.BarToolGroup.super.call( this, toolbar, config );
9076
9077 // Initialization
9078 this.$element.addClass( 'oo-ui-barToolGroup' );
9079 };
9080
9081 /* Setup */
9082
9083 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
9084
9085 /* Static Properties */
9086
9087 OO.ui.BarToolGroup.static.titleTooltips = true;
9088
9089 OO.ui.BarToolGroup.static.accelTooltips = true;
9090
9091 OO.ui.BarToolGroup.static.name = 'bar';
9092
9093 /**
9094 * Popup list of tools with an icon and optional label.
9095 *
9096 * @abstract
9097 * @class
9098 * @extends OO.ui.ToolGroup
9099 * @mixins OO.ui.IconElement
9100 * @mixins OO.ui.IndicatorElement
9101 * @mixins OO.ui.LabelElement
9102 * @mixins OO.ui.TitledElement
9103 * @mixins OO.ui.ClippableElement
9104 *
9105 * @constructor
9106 * @param {OO.ui.Toolbar} toolbar
9107 * @param {Object} [config] Configuration options
9108 * @cfg {string} [header] Text to display at the top of the pop-up
9109 */
9110 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
9111 // Allow passing positional parameters inside the config object
9112 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9113 config = toolbar;
9114 toolbar = config.toolbar;
9115 }
9116
9117 // Configuration initialization
9118 config = config || {};
9119
9120 // Parent constructor
9121 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
9122
9123 // Mixin constructors
9124 OO.ui.IconElement.call( this, config );
9125 OO.ui.IndicatorElement.call( this, config );
9126 OO.ui.LabelElement.call( this, config );
9127 OO.ui.TitledElement.call( this, config );
9128 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
9129
9130 // Properties
9131 this.active = false;
9132 this.dragging = false;
9133 this.onBlurHandler = this.onBlur.bind( this );
9134 this.$handle = $( '<span>' );
9135
9136 // Events
9137 this.$handle.on( {
9138 mousedown: this.onHandlePointerDown.bind( this ),
9139 mouseup: this.onHandlePointerUp.bind( this )
9140 } );
9141
9142 // Initialization
9143 this.$handle
9144 .addClass( 'oo-ui-popupToolGroup-handle' )
9145 .append( this.$icon, this.$label, this.$indicator );
9146 // If the pop-up should have a header, add it to the top of the toolGroup.
9147 // Note: If this feature is useful for other widgets, we could abstract it into an
9148 // OO.ui.HeaderedElement mixin constructor.
9149 if ( config.header !== undefined ) {
9150 this.$group
9151 .prepend( $( '<span>' )
9152 .addClass( 'oo-ui-popupToolGroup-header' )
9153 .text( config.header )
9154 );
9155 }
9156 this.$element
9157 .addClass( 'oo-ui-popupToolGroup' )
9158 .prepend( this.$handle );
9159 };
9160
9161 /* Setup */
9162
9163 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
9164 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
9165 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
9166 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
9167 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
9168 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
9169
9170 /* Static Properties */
9171
9172 /* Methods */
9173
9174 /**
9175 * @inheritdoc
9176 */
9177 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
9178 // Parent method
9179 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
9180
9181 if ( this.isDisabled() && this.isElementAttached() ) {
9182 this.setActive( false );
9183 }
9184 };
9185
9186 /**
9187 * Handle focus being lost.
9188 *
9189 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9190 *
9191 * @param {jQuery.Event} e Mouse up event
9192 */
9193 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
9194 // Only deactivate when clicking outside the dropdown element
9195 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
9196 this.setActive( false );
9197 }
9198 };
9199
9200 /**
9201 * @inheritdoc
9202 */
9203 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
9204 // Only close toolgroup when a tool was actually selected
9205 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9206 this.setActive( false );
9207 }
9208 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9209 };
9210
9211 /**
9212 * Handle mouse up events.
9213 *
9214 * @param {jQuery.Event} e Mouse up event
9215 */
9216 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9217 return false;
9218 };
9219
9220 /**
9221 * Handle mouse down events.
9222 *
9223 * @param {jQuery.Event} e Mouse down event
9224 */
9225 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9226 if ( !this.isDisabled() && e.which === 1 ) {
9227 this.setActive( !this.active );
9228 }
9229 return false;
9230 };
9231
9232 /**
9233 * Switch into active mode.
9234 *
9235 * When active, mouseup events anywhere in the document will trigger deactivation.
9236 */
9237 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9238 value = !!value;
9239 if ( this.active !== value ) {
9240 this.active = value;
9241 if ( value ) {
9242 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9243
9244 // Try anchoring the popup to the left first
9245 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9246 this.toggleClipping( true );
9247 if ( this.isClippedHorizontally() ) {
9248 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9249 this.toggleClipping( false );
9250 this.$element
9251 .removeClass( 'oo-ui-popupToolGroup-left' )
9252 .addClass( 'oo-ui-popupToolGroup-right' );
9253 this.toggleClipping( true );
9254 }
9255 } else {
9256 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9257 this.$element.removeClass(
9258 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9259 );
9260 this.toggleClipping( false );
9261 }
9262 }
9263 };
9264
9265 /**
9266 * Drop down list layout of tools as labeled icon buttons.
9267 *
9268 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9269 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9270 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9271 *
9272 * @class
9273 * @extends OO.ui.PopupToolGroup
9274 *
9275 * @constructor
9276 * @param {OO.ui.Toolbar} toolbar
9277 * @param {Object} [config] Configuration options
9278 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9279 * shown.
9280 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9281 * allowed to be collapsed.
9282 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9283 */
9284 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9285 // Allow passing positional parameters inside the config object
9286 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9287 config = toolbar;
9288 toolbar = config.toolbar;
9289 }
9290
9291 // Configuration initialization
9292 config = config || {};
9293
9294 // Properties (must be set before parent constructor, which calls #populate)
9295 this.allowCollapse = config.allowCollapse;
9296 this.forceExpand = config.forceExpand;
9297 this.expanded = config.expanded !== undefined ? config.expanded : false;
9298 this.collapsibleTools = [];
9299
9300 // Parent constructor
9301 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9302
9303 // Initialization
9304 this.$element.addClass( 'oo-ui-listToolGroup' );
9305 };
9306
9307 /* Setup */
9308
9309 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9310
9311 /* Static Properties */
9312
9313 OO.ui.ListToolGroup.static.accelTooltips = true;
9314
9315 OO.ui.ListToolGroup.static.name = 'list';
9316
9317 /* Methods */
9318
9319 /**
9320 * @inheritdoc
9321 */
9322 OO.ui.ListToolGroup.prototype.populate = function () {
9323 var i, len, allowCollapse = [];
9324
9325 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9326
9327 // Update the list of collapsible tools
9328 if ( this.allowCollapse !== undefined ) {
9329 allowCollapse = this.allowCollapse;
9330 } else if ( this.forceExpand !== undefined ) {
9331 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9332 }
9333
9334 this.collapsibleTools = [];
9335 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9336 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9337 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9338 }
9339 }
9340
9341 // Keep at the end, even when tools are added
9342 this.$group.append( this.getExpandCollapseTool().$element );
9343
9344 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9345 this.updateCollapsibleState();
9346 };
9347
9348 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9349 if ( this.expandCollapseTool === undefined ) {
9350 var ExpandCollapseTool = function () {
9351 ExpandCollapseTool.super.apply( this, arguments );
9352 };
9353
9354 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9355
9356 ExpandCollapseTool.prototype.onSelect = function () {
9357 this.toolGroup.expanded = !this.toolGroup.expanded;
9358 this.toolGroup.updateCollapsibleState();
9359 this.setActive( false );
9360 };
9361 ExpandCollapseTool.prototype.onUpdateState = function () {
9362 // Do nothing. Tool interface requires an implementation of this function.
9363 };
9364
9365 ExpandCollapseTool.static.name = 'more-fewer';
9366
9367 this.expandCollapseTool = new ExpandCollapseTool( this );
9368 }
9369 return this.expandCollapseTool;
9370 };
9371
9372 /**
9373 * @inheritdoc
9374 */
9375 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9376 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9377
9378 // Do not close the popup when the user wants to show more/fewer tools
9379 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9380 // Prevent the popup list from being hidden
9381 this.setActive( true );
9382 }
9383
9384 return ret;
9385 };
9386
9387 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9388 var i, len;
9389
9390 this.getExpandCollapseTool()
9391 .setIcon( this.expanded ? 'collapse' : 'expand' )
9392 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9393
9394 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9395 this.collapsibleTools[ i ].toggle( this.expanded );
9396 }
9397 };
9398
9399 /**
9400 * Drop down menu layout of tools as selectable menu items.
9401 *
9402 * @class
9403 * @extends OO.ui.PopupToolGroup
9404 *
9405 * @constructor
9406 * @param {OO.ui.Toolbar} toolbar
9407 * @param {Object} [config] Configuration options
9408 */
9409 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9410 // Allow passing positional parameters inside the config object
9411 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9412 config = toolbar;
9413 toolbar = config.toolbar;
9414 }
9415
9416 // Configuration initialization
9417 config = config || {};
9418
9419 // Parent constructor
9420 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9421
9422 // Events
9423 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9424
9425 // Initialization
9426 this.$element.addClass( 'oo-ui-menuToolGroup' );
9427 };
9428
9429 /* Setup */
9430
9431 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9432
9433 /* Static Properties */
9434
9435 OO.ui.MenuToolGroup.static.accelTooltips = true;
9436
9437 OO.ui.MenuToolGroup.static.name = 'menu';
9438
9439 /* Methods */
9440
9441 /**
9442 * Handle the toolbar state being updated.
9443 *
9444 * When the state changes, the title of each active item in the menu will be joined together and
9445 * used as a label for the group. The label will be empty if none of the items are active.
9446 */
9447 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9448 var name,
9449 labelTexts = [];
9450
9451 for ( name in this.tools ) {
9452 if ( this.tools[ name ].isActive() ) {
9453 labelTexts.push( this.tools[ name ].getTitle() );
9454 }
9455 }
9456
9457 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9458 };
9459
9460 /**
9461 * Tool that shows a popup when selected.
9462 *
9463 * @abstract
9464 * @class
9465 * @extends OO.ui.Tool
9466 * @mixins OO.ui.PopupElement
9467 *
9468 * @constructor
9469 * @param {OO.ui.ToolGroup} toolGroup
9470 * @param {Object} [config] Configuration options
9471 */
9472 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
9473 // Allow passing positional parameters inside the config object
9474 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9475 config = toolGroup;
9476 toolGroup = config.toolGroup;
9477 }
9478
9479 // Parent constructor
9480 OO.ui.PopupTool.super.call( this, toolGroup, config );
9481
9482 // Mixin constructors
9483 OO.ui.PopupElement.call( this, config );
9484
9485 // Initialization
9486 this.$element
9487 .addClass( 'oo-ui-popupTool' )
9488 .append( this.popup.$element );
9489 };
9490
9491 /* Setup */
9492
9493 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9494 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9495
9496 /* Methods */
9497
9498 /**
9499 * Handle the tool being selected.
9500 *
9501 * @inheritdoc
9502 */
9503 OO.ui.PopupTool.prototype.onSelect = function () {
9504 if ( !this.isDisabled() ) {
9505 this.popup.toggle();
9506 }
9507 this.setActive( false );
9508 return false;
9509 };
9510
9511 /**
9512 * Handle the toolbar state being updated.
9513 *
9514 * @inheritdoc
9515 */
9516 OO.ui.PopupTool.prototype.onUpdateState = function () {
9517 this.setActive( false );
9518 };
9519
9520 /**
9521 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9522 * menus in toolbars (T74159).
9523 *
9524 * @abstract
9525 * @class
9526 * @extends OO.ui.Tool
9527 *
9528 * @constructor
9529 * @param {OO.ui.ToolGroup} toolGroup
9530 * @param {Object} [config] Configuration options
9531 */
9532 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
9533 // Allow passing positional parameters inside the config object
9534 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9535 config = toolGroup;
9536 toolGroup = config.toolGroup;
9537 }
9538
9539 // Parent constructor
9540 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
9541
9542 // Properties
9543 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
9544
9545 // Initialization
9546 this.$link.remove();
9547 this.$element
9548 .addClass( 'oo-ui-toolGroupTool' )
9549 .append( this.innerToolGroup.$element );
9550 };
9551
9552 /* Setup */
9553
9554 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
9555
9556 /* Static Properties */
9557
9558 /**
9559 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9560 *
9561 * @property {Object.<string,Array>}
9562 */
9563 OO.ui.ToolGroupTool.static.groupConfig = {};
9564
9565 /* Methods */
9566
9567 /**
9568 * Handle the tool being selected.
9569 *
9570 * @inheritdoc
9571 */
9572 OO.ui.ToolGroupTool.prototype.onSelect = function () {
9573 this.innerToolGroup.setActive( !this.innerToolGroup.active );
9574 return false;
9575 };
9576
9577 /**
9578 * Handle the toolbar state being updated.
9579 *
9580 * @inheritdoc
9581 */
9582 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
9583 this.setActive( false );
9584 };
9585
9586 /**
9587 * Build a OO.ui.ToolGroup from the configuration.
9588 *
9589 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9590 * accepted values.
9591 * @return {OO.ui.ListToolGroup}
9592 */
9593 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
9594 if ( group.include === '*' ) {
9595 // Apply defaults to catch-all groups
9596 if ( group.label === undefined ) {
9597 group.label = OO.ui.msg( 'ooui-toolbar-more' );
9598 }
9599 }
9600
9601 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
9602 };
9603
9604 /**
9605 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9606 *
9607 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9608 *
9609 * @private
9610 * @abstract
9611 * @class
9612 * @extends OO.ui.GroupElement
9613 *
9614 * @constructor
9615 * @param {Object} [config] Configuration options
9616 */
9617 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9618 // Parent constructor
9619 OO.ui.GroupWidget.super.call( this, config );
9620 };
9621
9622 /* Setup */
9623
9624 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9625
9626 /* Methods */
9627
9628 /**
9629 * Set the disabled state of the widget.
9630 *
9631 * This will also update the disabled state of child widgets.
9632 *
9633 * @param {boolean} disabled Disable widget
9634 * @chainable
9635 */
9636 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9637 var i, len;
9638
9639 // Parent method
9640 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9641 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9642
9643 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9644 if ( this.items ) {
9645 for ( i = 0, len = this.items.length; i < len; i++ ) {
9646 this.items[ i ].updateDisabled();
9647 }
9648 }
9649
9650 return this;
9651 };
9652
9653 /**
9654 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9655 *
9656 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9657 * allows bidirectional communication.
9658 *
9659 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9660 *
9661 * @private
9662 * @abstract
9663 * @class
9664 *
9665 * @constructor
9666 */
9667 OO.ui.ItemWidget = function OoUiItemWidget() {
9668 //
9669 };
9670
9671 /* Methods */
9672
9673 /**
9674 * Check if widget is disabled.
9675 *
9676 * Checks parent if present, making disabled state inheritable.
9677 *
9678 * @return {boolean} Widget is disabled
9679 */
9680 OO.ui.ItemWidget.prototype.isDisabled = function () {
9681 return this.disabled ||
9682 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9683 };
9684
9685 /**
9686 * Set group element is in.
9687 *
9688 * @param {OO.ui.GroupElement|null} group Group element, null if none
9689 * @chainable
9690 */
9691 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9692 // Parent method
9693 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9694 OO.ui.Element.prototype.setElementGroup.call( this, group );
9695
9696 // Initialize item disabled states
9697 this.updateDisabled();
9698
9699 return this;
9700 };
9701
9702 /**
9703 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9704 * Controls include moving items up and down, removing items, and adding different kinds of items.
9705 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9706 *
9707 * @class
9708 * @extends OO.ui.Widget
9709 * @mixins OO.ui.GroupElement
9710 * @mixins OO.ui.IconElement
9711 *
9712 * @constructor
9713 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9714 * @param {Object} [config] Configuration options
9715 */
9716 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9717 // Allow passing positional parameters inside the config object
9718 if ( OO.isPlainObject( outline ) && config === undefined ) {
9719 config = outline;
9720 outline = config.outline;
9721 }
9722
9723 // Configuration initialization
9724 config = $.extend( { icon: 'add' }, config );
9725
9726 // Parent constructor
9727 OO.ui.OutlineControlsWidget.super.call( this, config );
9728
9729 // Mixin constructors
9730 OO.ui.GroupElement.call( this, config );
9731 OO.ui.IconElement.call( this, config );
9732
9733 // Properties
9734 this.outline = outline;
9735 this.$movers = $( '<div>' );
9736 this.upButton = new OO.ui.ButtonWidget( {
9737 framed: false,
9738 icon: 'collapse',
9739 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9740 } );
9741 this.downButton = new OO.ui.ButtonWidget( {
9742 framed: false,
9743 icon: 'expand',
9744 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9745 } );
9746 this.removeButton = new OO.ui.ButtonWidget( {
9747 framed: false,
9748 icon: 'remove',
9749 title: OO.ui.msg( 'ooui-outline-control-remove' )
9750 } );
9751
9752 // Events
9753 outline.connect( this, {
9754 select: 'onOutlineChange',
9755 add: 'onOutlineChange',
9756 remove: 'onOutlineChange'
9757 } );
9758 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9759 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9760 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9761
9762 // Initialization
9763 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9764 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9765 this.$movers
9766 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9767 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9768 this.$element.append( this.$icon, this.$group, this.$movers );
9769 };
9770
9771 /* Setup */
9772
9773 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9774 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9775 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9776
9777 /* Events */
9778
9779 /**
9780 * @event move
9781 * @param {number} places Number of places to move
9782 */
9783
9784 /**
9785 * @event remove
9786 */
9787
9788 /* Methods */
9789
9790 /**
9791 *
9792 * @private
9793 * Handle outline change events.
9794 */
9795 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9796 var i, len, firstMovable, lastMovable,
9797 items = this.outline.getItems(),
9798 selectedItem = this.outline.getSelectedItem(),
9799 movable = selectedItem && selectedItem.isMovable(),
9800 removable = selectedItem && selectedItem.isRemovable();
9801
9802 if ( movable ) {
9803 i = -1;
9804 len = items.length;
9805 while ( ++i < len ) {
9806 if ( items[ i ].isMovable() ) {
9807 firstMovable = items[ i ];
9808 break;
9809 }
9810 }
9811 i = len;
9812 while ( i-- ) {
9813 if ( items[ i ].isMovable() ) {
9814 lastMovable = items[ i ];
9815 break;
9816 }
9817 }
9818 }
9819 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9820 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9821 this.removeButton.setDisabled( !removable );
9822 };
9823
9824 /**
9825 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
9826 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
9827 *
9828 * @abstract
9829 * @class
9830 *
9831 * @constructor
9832 * @param {Object} [config] Configuration options
9833 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
9834 * By default, the toggle is in the 'off' state.
9835 */
9836 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9837 // Configuration initialization
9838 config = config || {};
9839
9840 // Properties
9841 this.value = null;
9842
9843 // Initialization
9844 this.$element.addClass( 'oo-ui-toggleWidget' );
9845 this.setValue( !!config.value );
9846 };
9847
9848 /* Events */
9849
9850 /**
9851 * @event change
9852 *
9853 * A change event is emitted when the on/off state of the toggle changes.
9854 *
9855 * @param {boolean} value Value representing the new state of the toggle
9856 */
9857
9858 /* Methods */
9859
9860 /**
9861 * Get the value representing the toggle’s state.
9862 *
9863 * @return {boolean} The on/off state of the toggle
9864 */
9865 OO.ui.ToggleWidget.prototype.getValue = function () {
9866 return this.value;
9867 };
9868
9869 /**
9870 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
9871 *
9872 * @param {boolean} value The state of the toggle
9873 * @fires change
9874 * @chainable
9875 */
9876 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
9877 value = !!value;
9878 if ( this.value !== value ) {
9879 this.value = value;
9880 this.emit( 'change', value );
9881 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
9882 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
9883 this.$element.attr( 'aria-checked', value.toString() );
9884 }
9885 return this;
9886 };
9887
9888 /**
9889 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
9890 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
9891 * removed, and cleared from the group.
9892 *
9893 * @example
9894 * // Example: A ButtonGroupWidget with two buttons
9895 * var button1 = new OO.ui.PopupButtonWidget( {
9896 * label: 'Select a category',
9897 * icon: 'menu',
9898 * popup: {
9899 * $content: $( '<p>List of categories...</p>' ),
9900 * padded: true,
9901 * align: 'left'
9902 * }
9903 * } );
9904 * var button2 = new OO.ui.ButtonWidget( {
9905 * label: 'Add item'
9906 * });
9907 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
9908 * items: [button1, button2]
9909 * } );
9910 * $( 'body' ).append( buttonGroup.$element );
9911 *
9912 * @class
9913 * @extends OO.ui.Widget
9914 * @mixins OO.ui.GroupElement
9915 *
9916 * @constructor
9917 * @param {Object} [config] Configuration options
9918 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
9919 */
9920 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
9921 // Configuration initialization
9922 config = config || {};
9923
9924 // Parent constructor
9925 OO.ui.ButtonGroupWidget.super.call( this, config );
9926
9927 // Mixin constructors
9928 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9929
9930 // Initialization
9931 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
9932 if ( Array.isArray( config.items ) ) {
9933 this.addItems( config.items );
9934 }
9935 };
9936
9937 /* Setup */
9938
9939 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
9940 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
9941
9942 /**
9943 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
9944 * feels, and functionality can be customized via the class’s configuration options
9945 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
9946 * and examples.
9947 *
9948 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
9949 *
9950 * @example
9951 * // A button widget
9952 * var button = new OO.ui.ButtonWidget( {
9953 * label: 'Button with Icon',
9954 * icon: 'remove',
9955 * iconTitle: 'Remove'
9956 * } );
9957 * $( 'body' ).append( button.$element );
9958 *
9959 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
9960 *
9961 * @class
9962 * @extends OO.ui.Widget
9963 * @mixins OO.ui.ButtonElement
9964 * @mixins OO.ui.IconElement
9965 * @mixins OO.ui.IndicatorElement
9966 * @mixins OO.ui.LabelElement
9967 * @mixins OO.ui.TitledElement
9968 * @mixins OO.ui.FlaggedElement
9969 * @mixins OO.ui.TabIndexedElement
9970 *
9971 * @constructor
9972 * @param {Object} [config] Configuration options
9973 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
9974 * @cfg {string} [target] The frame or window in which to open the hyperlink.
9975 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
9976 */
9977 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
9978 // Configuration initialization
9979 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
9980 config = $.extend( { noFollow: config && config.nofollow }, config );
9981
9982 // Parent constructor
9983 OO.ui.ButtonWidget.super.call( this, config );
9984
9985 // Mixin constructors
9986 OO.ui.ButtonElement.call( this, config );
9987 OO.ui.IconElement.call( this, config );
9988 OO.ui.IndicatorElement.call( this, config );
9989 OO.ui.LabelElement.call( this, config );
9990 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
9991 OO.ui.FlaggedElement.call( this, config );
9992 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
9993
9994 // Properties
9995 this.href = null;
9996 this.target = null;
9997 this.noFollow = false;
9998 this.isHyperlink = false;
9999
10000 // Initialization
10001 this.$button.append( this.$icon, this.$label, this.$indicator );
10002 this.$element
10003 .addClass( 'oo-ui-buttonWidget' )
10004 .append( this.$button );
10005 this.setHref( config.href );
10006 this.setTarget( config.target );
10007 this.setNoFollow( config.noFollow );
10008 };
10009
10010 /* Setup */
10011
10012 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10013 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10014 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10015 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10016 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10017 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10018 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10019 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10020
10021 /* Methods */
10022
10023 /**
10024 * @inheritdoc
10025 */
10026 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10027 if ( !this.isDisabled() ) {
10028 // Remove the tab-index while the button is down to prevent the button from stealing focus
10029 this.$button.removeAttr( 'tabindex' );
10030 }
10031
10032 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10033 };
10034
10035 /**
10036 * @inheritdoc
10037 */
10038 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10039 if ( !this.isDisabled() ) {
10040 // Restore the tab-index after the button is up to restore the button's accessibility
10041 this.$button.attr( 'tabindex', this.tabIndex );
10042 }
10043
10044 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10045 };
10046
10047 /**
10048 * @inheritdoc
10049 */
10050 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10051 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10052 if ( this.isHyperlink ) {
10053 return true;
10054 }
10055 return ret;
10056 };
10057
10058 /**
10059 * @inheritdoc
10060 */
10061 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10062 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10063 if ( this.isHyperlink ) {
10064 return true;
10065 }
10066 return ret;
10067 };
10068
10069 /**
10070 * Get hyperlink location.
10071 *
10072 * @return {string} Hyperlink location
10073 */
10074 OO.ui.ButtonWidget.prototype.getHref = function () {
10075 return this.href;
10076 };
10077
10078 /**
10079 * Get hyperlink target.
10080 *
10081 * @return {string} Hyperlink target
10082 */
10083 OO.ui.ButtonWidget.prototype.getTarget = function () {
10084 return this.target;
10085 };
10086
10087 /**
10088 * Get search engine traversal hint.
10089 *
10090 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10091 */
10092 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10093 return this.noFollow;
10094 };
10095
10096 /**
10097 * Set hyperlink location.
10098 *
10099 * @param {string|null} href Hyperlink location, null to remove
10100 */
10101 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10102 href = typeof href === 'string' ? href : null;
10103
10104 if ( href !== this.href ) {
10105 this.href = href;
10106 if ( href !== null ) {
10107 this.$button.attr( 'href', href );
10108 this.isHyperlink = true;
10109 } else {
10110 this.$button.removeAttr( 'href' );
10111 this.isHyperlink = false;
10112 }
10113 }
10114
10115 return this;
10116 };
10117
10118 /**
10119 * Set hyperlink target.
10120 *
10121 * @param {string|null} target Hyperlink target, null to remove
10122 */
10123 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10124 target = typeof target === 'string' ? target : null;
10125
10126 if ( target !== this.target ) {
10127 this.target = target;
10128 if ( target !== null ) {
10129 this.$button.attr( 'target', target );
10130 } else {
10131 this.$button.removeAttr( 'target' );
10132 }
10133 }
10134
10135 return this;
10136 };
10137
10138 /**
10139 * Set search engine traversal hint.
10140 *
10141 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10142 */
10143 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10144 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10145
10146 if ( noFollow !== this.noFollow ) {
10147 this.noFollow = noFollow;
10148 if ( noFollow ) {
10149 this.$button.attr( 'rel', 'nofollow' );
10150 } else {
10151 this.$button.removeAttr( 'rel' );
10152 }
10153 }
10154
10155 return this;
10156 };
10157
10158 /**
10159 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10160 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10161 * of the actions.
10162 *
10163 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10164 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10165 * and examples.
10166 *
10167 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10168 *
10169 * @class
10170 * @extends OO.ui.ButtonWidget
10171 * @mixins OO.ui.PendingElement
10172 *
10173 * @constructor
10174 * @param {Object} [config] Configuration options
10175 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10176 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10177 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10178 * for more information about setting modes.
10179 * @cfg {boolean} [framed=false] Render the action button with a frame
10180 */
10181 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10182 // Configuration initialization
10183 config = $.extend( { framed: false }, config );
10184
10185 // Parent constructor
10186 OO.ui.ActionWidget.super.call( this, config );
10187
10188 // Mixin constructors
10189 OO.ui.PendingElement.call( this, config );
10190
10191 // Properties
10192 this.action = config.action || '';
10193 this.modes = config.modes || [];
10194 this.width = 0;
10195 this.height = 0;
10196
10197 // Initialization
10198 this.$element.addClass( 'oo-ui-actionWidget' );
10199 };
10200
10201 /* Setup */
10202
10203 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10204 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10205
10206 /* Events */
10207
10208 /**
10209 * A resize event is emitted when the size of the widget changes.
10210 *
10211 * @event resize
10212 */
10213
10214 /* Methods */
10215
10216 /**
10217 * Check if the action is configured to be available in the specified `mode`.
10218 *
10219 * @param {string} mode Name of mode
10220 * @return {boolean} The action is configured with the mode
10221 */
10222 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10223 return this.modes.indexOf( mode ) !== -1;
10224 };
10225
10226 /**
10227 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10228 *
10229 * @return {string}
10230 */
10231 OO.ui.ActionWidget.prototype.getAction = function () {
10232 return this.action;
10233 };
10234
10235 /**
10236 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10237 *
10238 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10239 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10240 * are hidden.
10241 *
10242 * @return {string[]}
10243 */
10244 OO.ui.ActionWidget.prototype.getModes = function () {
10245 return this.modes.slice();
10246 };
10247
10248 /**
10249 * Emit a resize event if the size has changed.
10250 *
10251 * @private
10252 * @chainable
10253 */
10254 OO.ui.ActionWidget.prototype.propagateResize = function () {
10255 var width, height;
10256
10257 if ( this.isElementAttached() ) {
10258 width = this.$element.width();
10259 height = this.$element.height();
10260
10261 if ( width !== this.width || height !== this.height ) {
10262 this.width = width;
10263 this.height = height;
10264 this.emit( 'resize' );
10265 }
10266 }
10267
10268 return this;
10269 };
10270
10271 /**
10272 * @inheritdoc
10273 */
10274 OO.ui.ActionWidget.prototype.setIcon = function () {
10275 // Mixin method
10276 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10277 this.propagateResize();
10278
10279 return this;
10280 };
10281
10282 /**
10283 * @inheritdoc
10284 */
10285 OO.ui.ActionWidget.prototype.setLabel = function () {
10286 // Mixin method
10287 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10288 this.propagateResize();
10289
10290 return this;
10291 };
10292
10293 /**
10294 * @inheritdoc
10295 */
10296 OO.ui.ActionWidget.prototype.setFlags = function () {
10297 // Mixin method
10298 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10299 this.propagateResize();
10300
10301 return this;
10302 };
10303
10304 /**
10305 * @inheritdoc
10306 */
10307 OO.ui.ActionWidget.prototype.clearFlags = function () {
10308 // Mixin method
10309 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10310 this.propagateResize();
10311
10312 return this;
10313 };
10314
10315 /**
10316 * Toggle the visibility of the action button.
10317 *
10318 * @param {boolean} [show] Show button, omit to toggle visibility
10319 * @chainable
10320 */
10321 OO.ui.ActionWidget.prototype.toggle = function () {
10322 // Parent method
10323 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10324 this.propagateResize();
10325
10326 return this;
10327 };
10328
10329 /**
10330 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10331 * which is used to display additional information or options.
10332 *
10333 * @example
10334 * // Example of a popup button.
10335 * var popupButton = new OO.ui.PopupButtonWidget( {
10336 * label: 'Popup button with options',
10337 * icon: 'menu',
10338 * popup: {
10339 * $content: $( '<p>Additional options here.</p>' ),
10340 * padded: true,
10341 * align: 'left'
10342 * }
10343 * } );
10344 * // Append the button to the DOM.
10345 * $( 'body' ).append( popupButton.$element );
10346 *
10347 * @class
10348 * @extends OO.ui.ButtonWidget
10349 * @mixins OO.ui.PopupElement
10350 *
10351 * @constructor
10352 * @param {Object} [config] Configuration options
10353 */
10354 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10355 // Parent constructor
10356 OO.ui.PopupButtonWidget.super.call( this, config );
10357
10358 // Mixin constructors
10359 OO.ui.PopupElement.call( this, config );
10360
10361 // Events
10362 this.connect( this, { click: 'onAction' } );
10363
10364 // Initialization
10365 this.$element
10366 .addClass( 'oo-ui-popupButtonWidget' )
10367 .attr( 'aria-haspopup', 'true' )
10368 .append( this.popup.$element );
10369 };
10370
10371 /* Setup */
10372
10373 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10374 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10375
10376 /* Methods */
10377
10378 /**
10379 * Handle the button action being triggered.
10380 *
10381 * @private
10382 */
10383 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10384 this.popup.toggle();
10385 };
10386
10387 /**
10388 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10389 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10390 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10391 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10392 * and {@link OO.ui.LabelElement labels}. Please see
10393 * the [OOjs UI documentation][1] on MediaWiki for more information.
10394 *
10395 * @example
10396 * // Toggle buttons in the 'off' and 'on' state.
10397 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10398 * label: 'Toggle Button off'
10399 * } );
10400 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10401 * label: 'Toggle Button on',
10402 * value: true
10403 * } );
10404 * // Append the buttons to the DOM.
10405 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10406 *
10407 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10408 *
10409 * @class
10410 * @extends OO.ui.ButtonWidget
10411 * @mixins OO.ui.ToggleWidget
10412 *
10413 * @constructor
10414 * @param {Object} [config] Configuration options
10415 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10416 * state. By default, the button is in the 'off' state.
10417 */
10418 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10419 // Configuration initialization
10420 config = config || {};
10421
10422 // Parent constructor
10423 OO.ui.ToggleButtonWidget.super.call( this, config );
10424
10425 // Mixin constructors
10426 OO.ui.ToggleWidget.call( this, config );
10427
10428 // Events
10429 this.connect( this, { click: 'onAction' } );
10430
10431 // Initialization
10432 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10433 };
10434
10435 /* Setup */
10436
10437 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10438 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10439
10440 /* Methods */
10441
10442 /**
10443 *
10444 * @private
10445 * Handle the button action being triggered.
10446 */
10447 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10448 this.setValue( !this.value );
10449 };
10450
10451 /**
10452 * @inheritdoc
10453 */
10454 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10455 value = !!value;
10456 if ( value !== this.value ) {
10457 this.$button.attr( 'aria-pressed', value.toString() );
10458 this.setActive( value );
10459 }
10460
10461 // Parent method (from mixin)
10462 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10463
10464 return this;
10465 };
10466
10467 /**
10468 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10469 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10470 * users can interact with it.
10471 *
10472 * @example
10473 * // Example: A DropdownWidget with a menu that contains three options
10474 * var dropDown = new OO.ui.DropdownWidget( {
10475 * label: 'Dropdown menu: Select a menu option',
10476 * menu: {
10477 * items: [
10478 * new OO.ui.MenuOptionWidget( {
10479 * data: 'a',
10480 * label: 'First'
10481 * } ),
10482 * new OO.ui.MenuOptionWidget( {
10483 * data: 'b',
10484 * label: 'Second'
10485 * } ),
10486 * new OO.ui.MenuOptionWidget( {
10487 * data: 'c',
10488 * label: 'Third'
10489 * } )
10490 * ]
10491 * }
10492 * } );
10493 *
10494 * $( 'body' ).append( dropDown.$element );
10495 *
10496 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10497 *
10498 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10499 *
10500 * @class
10501 * @extends OO.ui.Widget
10502 * @mixins OO.ui.IconElement
10503 * @mixins OO.ui.IndicatorElement
10504 * @mixins OO.ui.LabelElement
10505 * @mixins OO.ui.TitledElement
10506 * @mixins OO.ui.TabIndexedElement
10507 *
10508 * @constructor
10509 * @param {Object} [config] Configuration options
10510 * @cfg {Object} [menu] Configuration options to pass to menu widget
10511 */
10512 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10513 // Configuration initialization
10514 config = $.extend( { indicator: 'down' }, config );
10515
10516 // Parent constructor
10517 OO.ui.DropdownWidget.super.call( this, config );
10518
10519 // Properties (must be set before TabIndexedElement constructor call)
10520 this.$handle = this.$( '<span>' );
10521
10522 // Mixin constructors
10523 OO.ui.IconElement.call( this, config );
10524 OO.ui.IndicatorElement.call( this, config );
10525 OO.ui.LabelElement.call( this, config );
10526 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10527 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10528
10529 // Properties
10530 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
10531
10532 // Events
10533 this.$handle.on( {
10534 click: this.onClick.bind( this ),
10535 keypress: this.onKeyPress.bind( this )
10536 } );
10537 this.menu.connect( this, { select: 'onMenuSelect' } );
10538
10539 // Initialization
10540 this.$handle
10541 .addClass( 'oo-ui-dropdownWidget-handle' )
10542 .append( this.$icon, this.$label, this.$indicator );
10543 this.$element
10544 .addClass( 'oo-ui-dropdownWidget' )
10545 .append( this.$handle, this.menu.$element );
10546 };
10547
10548 /* Setup */
10549
10550 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10551 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10552 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10553 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10554 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10555 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
10556
10557 /* Methods */
10558
10559 /**
10560 * Get the menu.
10561 *
10562 * @return {OO.ui.MenuSelectWidget} Menu of widget
10563 */
10564 OO.ui.DropdownWidget.prototype.getMenu = function () {
10565 return this.menu;
10566 };
10567
10568 /**
10569 * Handles menu select events.
10570 *
10571 * @private
10572 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10573 */
10574 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10575 var selectedLabel;
10576
10577 if ( !item ) {
10578 return;
10579 }
10580
10581 selectedLabel = item.getLabel();
10582
10583 // If the label is a DOM element, clone it, because setLabel will append() it
10584 if ( selectedLabel instanceof jQuery ) {
10585 selectedLabel = selectedLabel.clone();
10586 }
10587
10588 this.setLabel( selectedLabel );
10589 };
10590
10591 /**
10592 * Handle mouse click events.
10593 *
10594 * @private
10595 * @param {jQuery.Event} e Mouse click event
10596 */
10597 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10598 if ( !this.isDisabled() && e.which === 1 ) {
10599 this.menu.toggle();
10600 }
10601 return false;
10602 };
10603
10604 /**
10605 * Handle key press events.
10606 *
10607 * @private
10608 * @param {jQuery.Event} e Key press event
10609 */
10610 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
10611 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10612 this.menu.toggle();
10613 return false;
10614 }
10615 };
10616
10617 /**
10618 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10619 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10620 * for a list of icons included in the library.
10621 *
10622 * @example
10623 * // An icon widget with a label
10624 * var myIcon = new OO.ui.IconWidget( {
10625 * icon: 'help',
10626 * iconTitle: 'Help'
10627 * } );
10628 * // Create a label.
10629 * var iconLabel = new OO.ui.LabelWidget( {
10630 * label: 'Help'
10631 * } );
10632 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10633 *
10634 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10635 *
10636 * @class
10637 * @extends OO.ui.Widget
10638 * @mixins OO.ui.IconElement
10639 * @mixins OO.ui.TitledElement
10640 *
10641 * @constructor
10642 * @param {Object} [config] Configuration options
10643 */
10644 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10645 // Configuration initialization
10646 config = config || {};
10647
10648 // Parent constructor
10649 OO.ui.IconWidget.super.call( this, config );
10650
10651 // Mixin constructors
10652 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10653 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10654
10655 // Initialization
10656 this.$element.addClass( 'oo-ui-iconWidget' );
10657 };
10658
10659 /* Setup */
10660
10661 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10662 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10663 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10664
10665 /* Static Properties */
10666
10667 OO.ui.IconWidget.static.tagName = 'span';
10668
10669 /**
10670 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10671 * attention to the status of an item or to clarify the function of a control. For a list of
10672 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10673 *
10674 * @example
10675 * // Example of an indicator widget
10676 * var indicator1 = new OO.ui.IndicatorWidget( {
10677 * indicator: 'alert'
10678 * } );
10679 *
10680 * // Create a fieldset layout to add a label
10681 * var fieldset = new OO.ui.FieldsetLayout();
10682 * fieldset.addItems( [
10683 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10684 * ] );
10685 * $( 'body' ).append( fieldset.$element );
10686 *
10687 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10688 *
10689 * @class
10690 * @extends OO.ui.Widget
10691 * @mixins OO.ui.IndicatorElement
10692 * @mixins OO.ui.TitledElement
10693 *
10694 * @constructor
10695 * @param {Object} [config] Configuration options
10696 */
10697 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
10698 // Configuration initialization
10699 config = config || {};
10700
10701 // Parent constructor
10702 OO.ui.IndicatorWidget.super.call( this, config );
10703
10704 // Mixin constructors
10705 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
10706 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10707
10708 // Initialization
10709 this.$element.addClass( 'oo-ui-indicatorWidget' );
10710 };
10711
10712 /* Setup */
10713
10714 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10715 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10716 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10717
10718 /* Static Properties */
10719
10720 OO.ui.IndicatorWidget.static.tagName = 'span';
10721
10722 /**
10723 * InputWidget is the base class for all input widgets, which
10724 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
10725 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
10726 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10727 *
10728 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10729 *
10730 * @abstract
10731 * @class
10732 * @extends OO.ui.Widget
10733 * @mixins OO.ui.FlaggedElement
10734 * @mixins OO.ui.TabIndexedElement
10735 *
10736 * @constructor
10737 * @param {Object} [config] Configuration options
10738 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
10739 * @cfg {string} [value=''] The value of the input.
10740 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
10741 * before it is accepted.
10742 */
10743 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10744 // Configuration initialization
10745 config = config || {};
10746
10747 // Parent constructor
10748 OO.ui.InputWidget.super.call( this, config );
10749
10750 // Properties
10751 this.$input = this.getInputElement( config );
10752 this.value = '';
10753 this.inputFilter = config.inputFilter;
10754
10755 // Mixin constructors
10756 OO.ui.FlaggedElement.call( this, config );
10757 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
10758
10759 // Events
10760 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10761
10762 // Initialization
10763 this.$input
10764 .attr( 'name', config.name )
10765 .prop( 'disabled', this.isDisabled() );
10766 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10767 this.setValue( config.value );
10768 };
10769
10770 /* Setup */
10771
10772 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10773 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10774 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
10775
10776 /* Events */
10777
10778 /**
10779 * @event change
10780 *
10781 * A change event is emitted when the value of the input changes.
10782 *
10783 * @param {string} value
10784 */
10785
10786 /* Methods */
10787
10788 /**
10789 * Get input element.
10790 *
10791 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10792 * different circumstances. The element must have a `value` property (like form elements).
10793 *
10794 * @private
10795 * @param {Object} config Configuration options
10796 * @return {jQuery} Input element
10797 */
10798 OO.ui.InputWidget.prototype.getInputElement = function () {
10799 return $( '<input>' );
10800 };
10801
10802 /**
10803 * Handle potentially value-changing events.
10804 *
10805 * @private
10806 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10807 */
10808 OO.ui.InputWidget.prototype.onEdit = function () {
10809 var widget = this;
10810 if ( !this.isDisabled() ) {
10811 // Allow the stack to clear so the value will be updated
10812 setTimeout( function () {
10813 widget.setValue( widget.$input.val() );
10814 } );
10815 }
10816 };
10817
10818 /**
10819 * Get the value of the input.
10820 *
10821 * @return {string} Input value
10822 */
10823 OO.ui.InputWidget.prototype.getValue = function () {
10824 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10825 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10826 var value = this.$input.val();
10827 if ( this.value !== value ) {
10828 this.setValue( value );
10829 }
10830 return this.value;
10831 };
10832
10833 /**
10834 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
10835 *
10836 * @param {boolean} isRTL
10837 * Direction is right-to-left
10838 */
10839 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10840 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
10841 };
10842
10843 /**
10844 * Set the value of the input.
10845 *
10846 * @param {string} value New value
10847 * @fires change
10848 * @chainable
10849 */
10850 OO.ui.InputWidget.prototype.setValue = function ( value ) {
10851 value = this.cleanUpValue( value );
10852 // Update the DOM if it has changed. Note that with cleanUpValue, it
10853 // is possible for the DOM value to change without this.value changing.
10854 if ( this.$input.val() !== value ) {
10855 this.$input.val( value );
10856 }
10857 if ( this.value !== value ) {
10858 this.value = value;
10859 this.emit( 'change', this.value );
10860 }
10861 return this;
10862 };
10863
10864 /**
10865 * Clean up incoming value.
10866 *
10867 * Ensures value is a string, and converts undefined and null to empty string.
10868 *
10869 * @private
10870 * @param {string} value Original value
10871 * @return {string} Cleaned up value
10872 */
10873 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
10874 if ( value === undefined || value === null ) {
10875 return '';
10876 } else if ( this.inputFilter ) {
10877 return this.inputFilter( String( value ) );
10878 } else {
10879 return String( value );
10880 }
10881 };
10882
10883 /**
10884 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
10885 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
10886 * called directly.
10887 */
10888 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
10889 if ( !this.isDisabled() ) {
10890 if ( this.$input.is( ':checkbox, :radio' ) ) {
10891 this.$input.click();
10892 }
10893 if ( this.$input.is( ':input' ) ) {
10894 this.$input[ 0 ].focus();
10895 }
10896 }
10897 };
10898
10899 /**
10900 * @inheritdoc
10901 */
10902 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
10903 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
10904 if ( this.$input ) {
10905 this.$input.prop( 'disabled', this.isDisabled() );
10906 }
10907 return this;
10908 };
10909
10910 /**
10911 * Focus the input.
10912 *
10913 * @chainable
10914 */
10915 OO.ui.InputWidget.prototype.focus = function () {
10916 this.$input[ 0 ].focus();
10917 return this;
10918 };
10919
10920 /**
10921 * Blur the input.
10922 *
10923 * @chainable
10924 */
10925 OO.ui.InputWidget.prototype.blur = function () {
10926 this.$input[ 0 ].blur();
10927 return this;
10928 };
10929
10930 /**
10931 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
10932 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
10933 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
10934 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
10935 * [OOjs UI documentation on MediaWiki] [1] for more information.
10936 *
10937 * @example
10938 * // A ButtonInputWidget rendered as an HTML button, the default.
10939 * var button = new OO.ui.ButtonInputWidget( {
10940 * label: 'Input button',
10941 * icon: 'check',
10942 * value: 'check'
10943 * } );
10944 * $( 'body' ).append( button.$element );
10945 *
10946 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
10947 *
10948 * @class
10949 * @extends OO.ui.InputWidget
10950 * @mixins OO.ui.ButtonElement
10951 * @mixins OO.ui.IconElement
10952 * @mixins OO.ui.IndicatorElement
10953 * @mixins OO.ui.LabelElement
10954 * @mixins OO.ui.TitledElement
10955 * @mixins OO.ui.FlaggedElement
10956 *
10957 * @constructor
10958 * @param {Object} [config] Configuration options
10959 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
10960 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
10961 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
10962 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
10963 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
10964 */
10965 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
10966 // Configuration initialization
10967 config = $.extend( { type: 'button', useInputTag: false }, config );
10968
10969 // Properties (must be set before parent constructor, which calls #setValue)
10970 this.useInputTag = config.useInputTag;
10971
10972 // Parent constructor
10973 OO.ui.ButtonInputWidget.super.call( this, config );
10974
10975 // Mixin constructors
10976 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
10977 OO.ui.IconElement.call( this, config );
10978 OO.ui.IndicatorElement.call( this, config );
10979 OO.ui.LabelElement.call( this, config );
10980 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
10981 OO.ui.FlaggedElement.call( this, config );
10982
10983 // Initialization
10984 if ( !config.useInputTag ) {
10985 this.$input.append( this.$icon, this.$label, this.$indicator );
10986 }
10987 this.$element.addClass( 'oo-ui-buttonInputWidget' );
10988 };
10989
10990 /* Setup */
10991
10992 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
10993 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
10994 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
10995 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
10996 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
10997 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
10998 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
10999
11000 /* Methods */
11001
11002 /**
11003 * @inheritdoc
11004 * @private
11005 */
11006 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
11007 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
11008 return $( html );
11009 };
11010
11011 /**
11012 * Set label value.
11013 *
11014 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11015 *
11016 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11017 * text, or `null` for no label
11018 * @chainable
11019 */
11020 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
11021 OO.ui.LabelElement.prototype.setLabel.call( this, label );
11022
11023 if ( this.useInputTag ) {
11024 if ( typeof label === 'function' ) {
11025 label = OO.ui.resolveMsg( label );
11026 }
11027 if ( label instanceof jQuery ) {
11028 label = label.text();
11029 }
11030 if ( !label ) {
11031 label = '';
11032 }
11033 this.$input.val( label );
11034 }
11035
11036 return this;
11037 };
11038
11039 /**
11040 * Set the value of the input.
11041 *
11042 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11043 * they do not support {@link #value values}.
11044 *
11045 * @param {string} value New value
11046 * @chainable
11047 */
11048 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11049 if ( !this.useInputTag ) {
11050 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11051 }
11052 return this;
11053 };
11054
11055 /**
11056 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11057 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11058 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11059 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11060 *
11061 * @example
11062 * // An example of selected, unselected, and disabled checkbox inputs
11063 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11064 * value: 'a',
11065 * selected: true
11066 * } );
11067 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11068 * value: 'b'
11069 * } );
11070 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11071 * value:'c',
11072 * disabled: true
11073 * } );
11074 * // Create a fieldset layout with fields for each checkbox.
11075 * var fieldset = new OO.ui.FieldsetLayout( {
11076 * label: 'Checkboxes'
11077 * } );
11078 * fieldset.addItems( [
11079 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11080 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11081 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11082 * ] );
11083 * $( 'body' ).append( fieldset.$element );
11084 *
11085 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11086 *
11087 * @class
11088 * @extends OO.ui.InputWidget
11089 *
11090 * @constructor
11091 * @param {Object} [config] Configuration options
11092 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11093 */
11094 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11095 // Configuration initialization
11096 config = config || {};
11097
11098 // Parent constructor
11099 OO.ui.CheckboxInputWidget.super.call( this, config );
11100
11101 // Initialization
11102 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11103 this.setSelected( config.selected !== undefined ? config.selected : false );
11104 };
11105
11106 /* Setup */
11107
11108 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11109
11110 /* Methods */
11111
11112 /**
11113 * @inheritdoc
11114 * @private
11115 */
11116 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11117 return $( '<input type="checkbox" />' );
11118 };
11119
11120 /**
11121 * @inheritdoc
11122 */
11123 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11124 var widget = this;
11125 if ( !this.isDisabled() ) {
11126 // Allow the stack to clear so the value will be updated
11127 setTimeout( function () {
11128 widget.setSelected( widget.$input.prop( 'checked' ) );
11129 } );
11130 }
11131 };
11132
11133 /**
11134 * Set selection state of this checkbox.
11135 *
11136 * @param {boolean} state `true` for selected
11137 * @chainable
11138 */
11139 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11140 state = !!state;
11141 if ( this.selected !== state ) {
11142 this.selected = state;
11143 this.$input.prop( 'checked', this.selected );
11144 this.emit( 'change', this.selected );
11145 }
11146 return this;
11147 };
11148
11149 /**
11150 * Check if this checkbox is selected.
11151 *
11152 * @return {boolean} Checkbox is selected
11153 */
11154 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11155 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11156 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11157 var selected = this.$input.prop( 'checked' );
11158 if ( this.selected !== selected ) {
11159 this.setSelected( selected );
11160 }
11161 return this.selected;
11162 };
11163
11164 /**
11165 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11166 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11167 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11168 * more information about input widgets.
11169 *
11170 * @example
11171 * // Example: A DropdownInputWidget with three options
11172 * var dropDown = new OO.ui.DropdownInputWidget( {
11173 * label: 'Dropdown menu: Select a menu option',
11174 * options: [
11175 * { data: 'a', label: 'First' } ,
11176 * { data: 'b', label: 'Second'} ,
11177 * { data: 'c', label: 'Third' }
11178 * ]
11179 * } );
11180 * $( 'body' ).append( dropDown.$element );
11181 *
11182 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11183 *
11184 * @class
11185 * @extends OO.ui.InputWidget
11186 *
11187 * @constructor
11188 * @param {Object} [config] Configuration options
11189 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11190 */
11191 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11192 // Configuration initialization
11193 config = config || {};
11194
11195 // Properties (must be done before parent constructor which calls #setDisabled)
11196 this.dropdownWidget = new OO.ui.DropdownWidget();
11197
11198 // Parent constructor
11199 OO.ui.DropdownInputWidget.super.call( this, config );
11200
11201 // Events
11202 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11203
11204 // Initialization
11205 this.setOptions( config.options || [] );
11206 this.$element
11207 .addClass( 'oo-ui-dropdownInputWidget' )
11208 .append( this.dropdownWidget.$element );
11209 };
11210
11211 /* Setup */
11212
11213 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11214
11215 /* Methods */
11216
11217 /**
11218 * @inheritdoc
11219 * @private
11220 */
11221 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11222 return $( '<input type="hidden">' );
11223 };
11224
11225 /**
11226 * Handles menu select events.
11227 *
11228 * @private
11229 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11230 */
11231 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11232 this.setValue( item.getData() );
11233 };
11234
11235 /**
11236 * @inheritdoc
11237 */
11238 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11239 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11240 if ( item ) {
11241 this.dropdownWidget.getMenu().selectItem( item );
11242 }
11243 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11244 return this;
11245 };
11246
11247 /**
11248 * @inheritdoc
11249 */
11250 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11251 this.dropdownWidget.setDisabled( state );
11252 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11253 return this;
11254 };
11255
11256 /**
11257 * Set the options available for this input.
11258 *
11259 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11260 * @chainable
11261 */
11262 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11263 var value = this.getValue();
11264
11265 // Rebuild the dropdown menu
11266 this.dropdownWidget.getMenu()
11267 .clearItems()
11268 .addItems( options.map( function ( opt ) {
11269 return new OO.ui.MenuOptionWidget( {
11270 data: opt.data,
11271 label: opt.label !== undefined ? opt.label : opt.data
11272 } );
11273 } ) );
11274
11275 // Restore the previous value, or reset to something sensible
11276 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11277 // Previous value is still available, ensure consistency with the dropdown
11278 this.setValue( value );
11279 } else {
11280 // No longer valid, reset
11281 if ( options.length ) {
11282 this.setValue( options[ 0 ].data );
11283 }
11284 }
11285
11286 return this;
11287 };
11288
11289 /**
11290 * @inheritdoc
11291 */
11292 OO.ui.DropdownInputWidget.prototype.focus = function () {
11293 this.dropdownWidget.getMenu().toggle( true );
11294 return this;
11295 };
11296
11297 /**
11298 * @inheritdoc
11299 */
11300 OO.ui.DropdownInputWidget.prototype.blur = function () {
11301 this.dropdownWidget.getMenu().toggle( false );
11302 return this;
11303 };
11304
11305 /**
11306 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11307 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11308 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11309 * please see the [OOjs UI documentation on MediaWiki][1].
11310 *
11311 * @example
11312 * // An example of selected, unselected, and disabled radio inputs
11313 * var radio1 = new OO.ui.RadioInputWidget( {
11314 * value: 'a',
11315 * selected: true
11316 * } );
11317 * var radio2 = new OO.ui.RadioInputWidget( {
11318 * value: 'b'
11319 * } );
11320 * var radio3 = new OO.ui.RadioInputWidget( {
11321 * value: 'c',
11322 * disabled: true
11323 * } );
11324 * // Create a fieldset layout with fields for each radio button.
11325 * var fieldset = new OO.ui.FieldsetLayout( {
11326 * label: 'Radio inputs'
11327 * } );
11328 * fieldset.addItems( [
11329 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11330 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11331 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11332 * ] );
11333 * $( 'body' ).append( fieldset.$element );
11334 *
11335 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11336 *
11337 * @class
11338 * @extends OO.ui.InputWidget
11339 *
11340 * @constructor
11341 * @param {Object} [config] Configuration options
11342 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11343 */
11344 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11345 // Configuration initialization
11346 config = config || {};
11347
11348 // Parent constructor
11349 OO.ui.RadioInputWidget.super.call( this, config );
11350
11351 // Initialization
11352 this.$element.addClass( 'oo-ui-radioInputWidget' );
11353 this.setSelected( config.selected !== undefined ? config.selected : false );
11354 };
11355
11356 /* Setup */
11357
11358 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11359
11360 /* Methods */
11361
11362 /**
11363 * @inheritdoc
11364 * @private
11365 */
11366 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11367 return $( '<input type="radio" />' );
11368 };
11369
11370 /**
11371 * @inheritdoc
11372 */
11373 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11374 // RadioInputWidget doesn't track its state.
11375 };
11376
11377 /**
11378 * Set selection state of this radio button.
11379 *
11380 * @param {boolean} state `true` for selected
11381 * @chainable
11382 */
11383 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11384 // RadioInputWidget doesn't track its state.
11385 this.$input.prop( 'checked', state );
11386 return this;
11387 };
11388
11389 /**
11390 * Check if this radio button is selected.
11391 *
11392 * @return {boolean} Radio is selected
11393 */
11394 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11395 return this.$input.prop( 'checked' );
11396 };
11397
11398 /**
11399 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11400 * size of the field as well as its presentation. In addition, these widgets can be configured
11401 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11402 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11403 * which modifies incoming values rather than validating them.
11404 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11405 *
11406 * @example
11407 * // Example of a text input widget
11408 * var textInput = new OO.ui.TextInputWidget( {
11409 * value: 'Text input'
11410 * } )
11411 * $( 'body' ).append( textInput.$element );
11412 *
11413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11414 *
11415 * @class
11416 * @extends OO.ui.InputWidget
11417 * @mixins OO.ui.IconElement
11418 * @mixins OO.ui.IndicatorElement
11419 * @mixins OO.ui.PendingElement
11420 * @mixins OO.ui.LabelElement
11421 *
11422 * @constructor
11423 * @param {Object} [config] Configuration options
11424 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11425 * @cfg {string} [placeholder] Placeholder text
11426 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11427 * instruct the browser to focus this widget.
11428 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11429 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11430 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11431 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11432 * Use the #maxRows config to specify a maximum number of displayed rows.
11433 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11434 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11435 * the value or placeholder text: `'before'` or `'after'`
11436 * @cfg {boolean} [required=false] Mark the field as required
11437 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11438 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11439 * or 'integer' (the value must contain only numbers).
11440 */
11441 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
11442 // Configuration initialization
11443 config = $.extend( {
11444 type: 'text',
11445 labelPosition: 'after',
11446 maxRows: 10
11447 }, config );
11448
11449 // Parent constructor
11450 OO.ui.TextInputWidget.super.call( this, config );
11451
11452 // Mixin constructors
11453 OO.ui.IconElement.call( this, config );
11454 OO.ui.IndicatorElement.call( this, config );
11455 OO.ui.PendingElement.call( this, config );
11456 OO.ui.LabelElement.call( this, config );
11457
11458 // Properties
11459 this.readOnly = false;
11460 this.multiline = !!config.multiline;
11461 this.autosize = !!config.autosize;
11462 this.maxRows = config.maxRows;
11463 this.validate = null;
11464
11465 // Clone for resizing
11466 if ( this.autosize ) {
11467 this.$clone = this.$input
11468 .clone()
11469 .insertAfter( this.$input )
11470 .attr( 'aria-hidden', 'true' )
11471 .addClass( 'oo-ui-element-hidden' );
11472 }
11473
11474 this.setValidation( config.validate );
11475 this.setLabelPosition( config.labelPosition );
11476
11477 // Events
11478 this.$input.on( {
11479 keypress: this.onKeyPress.bind( this ),
11480 blur: this.setValidityFlag.bind( this )
11481 } );
11482 this.$input.one( {
11483 focus: this.onElementAttach.bind( this )
11484 } );
11485 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11486 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11487 this.on( 'labelChange', this.updatePosition.bind( this ) );
11488
11489 // Initialization
11490 this.$element
11491 .addClass( 'oo-ui-textInputWidget' )
11492 .append( this.$icon, this.$indicator );
11493 this.setReadOnly( !!config.readOnly );
11494 if ( config.placeholder ) {
11495 this.$input.attr( 'placeholder', config.placeholder );
11496 }
11497 if ( config.maxLength !== undefined ) {
11498 this.$input.attr( 'maxlength', config.maxLength );
11499 }
11500 if ( config.autofocus ) {
11501 this.$input.attr( 'autofocus', 'autofocus' );
11502 }
11503 if ( config.required ) {
11504 this.$input.attr( 'required', 'true' );
11505 }
11506 if ( this.label || config.autosize ) {
11507 this.installParentChangeDetector();
11508 }
11509 };
11510
11511 /* Setup */
11512
11513 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11514 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11515 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11516 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11517 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11518
11519 /* Static properties */
11520
11521 OO.ui.TextInputWidget.static.validationPatterns = {
11522 'non-empty': /.+/,
11523 integer: /^\d+$/
11524 };
11525
11526 /* Events */
11527
11528 /**
11529 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11530 *
11531 * Not emitted if the input is multiline.
11532 *
11533 * @event enter
11534 */
11535
11536 /* Methods */
11537
11538 /**
11539 * Handle icon mouse down events.
11540 *
11541 * @private
11542 * @param {jQuery.Event} e Mouse down event
11543 * @fires icon
11544 */
11545 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11546 if ( e.which === 1 ) {
11547 this.$input[ 0 ].focus();
11548 return false;
11549 }
11550 };
11551
11552 /**
11553 * Handle indicator mouse down events.
11554 *
11555 * @private
11556 * @param {jQuery.Event} e Mouse down event
11557 * @fires indicator
11558 */
11559 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11560 if ( e.which === 1 ) {
11561 this.$input[ 0 ].focus();
11562 return false;
11563 }
11564 };
11565
11566 /**
11567 * Handle key press events.
11568 *
11569 * @private
11570 * @param {jQuery.Event} e Key press event
11571 * @fires enter If enter key is pressed and input is not multiline
11572 */
11573 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11574 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11575 this.emit( 'enter', e );
11576 }
11577 };
11578
11579 /**
11580 * Handle element attach events.
11581 *
11582 * @private
11583 * @param {jQuery.Event} e Element attach event
11584 */
11585 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11586 // Any previously calculated size is now probably invalid if we reattached elsewhere
11587 this.valCache = null;
11588 this.adjustSize();
11589 this.positionLabel();
11590 };
11591
11592 /**
11593 * @inheritdoc
11594 */
11595 OO.ui.TextInputWidget.prototype.onEdit = function () {
11596 this.adjustSize();
11597
11598 // Parent method
11599 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11600 };
11601
11602 /**
11603 * @inheritdoc
11604 */
11605 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11606 // Parent method
11607 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11608
11609 this.setValidityFlag();
11610 this.adjustSize();
11611 return this;
11612 };
11613
11614 /**
11615 * Check if the input is {@link #readOnly read-only}.
11616 *
11617 * @return {boolean}
11618 */
11619 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11620 return this.readOnly;
11621 };
11622
11623 /**
11624 * Set the {@link #readOnly read-only} state of the input.
11625 *
11626 * @param {boolean} state Make input read-only
11627 * @chainable
11628 */
11629 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11630 this.readOnly = !!state;
11631 this.$input.prop( 'readOnly', this.readOnly );
11632 return this;
11633 };
11634
11635 /**
11636 * Support function for making #onElementAttach work across browsers.
11637 *
11638 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11639 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11640 *
11641 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11642 * first time that the element gets attached to the documented.
11643 */
11644 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
11645 var mutationObserver, onRemove, topmostNode, fakeParentNode,
11646 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
11647 widget = this;
11648
11649 if ( MutationObserver ) {
11650 // The new way. If only it wasn't so ugly.
11651
11652 if ( this.$element.closest( 'html' ).length ) {
11653 // Widget is attached already, do nothing. This breaks the functionality of this function when
11654 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11655 // would require observation of the whole document, which would hurt performance of other,
11656 // more important code.
11657 return;
11658 }
11659
11660 // Find topmost node in the tree
11661 topmostNode = this.$element[0];
11662 while ( topmostNode.parentNode ) {
11663 topmostNode = topmostNode.parentNode;
11664 }
11665
11666 // We have no way to detect the $element being attached somewhere without observing the entire
11667 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11668 // parent node of $element, and instead detect when $element is removed from it (and thus
11669 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11670 // doesn't get attached, we end up back here and create the parent.
11671
11672 mutationObserver = new MutationObserver( function ( mutations ) {
11673 var i, j, removedNodes;
11674 for ( i = 0; i < mutations.length; i++ ) {
11675 removedNodes = mutations[ i ].removedNodes;
11676 for ( j = 0; j < removedNodes.length; j++ ) {
11677 if ( removedNodes[ j ] === topmostNode ) {
11678 setTimeout( onRemove, 0 );
11679 return;
11680 }
11681 }
11682 }
11683 } );
11684
11685 onRemove = function () {
11686 // If the node was attached somewhere else, report it
11687 if ( widget.$element.closest( 'html' ).length ) {
11688 widget.onElementAttach();
11689 }
11690 mutationObserver.disconnect();
11691 widget.installParentChangeDetector();
11692 };
11693
11694 // Create a fake parent and observe it
11695 fakeParentNode = $( '<div>' ).append( this.$element )[0];
11696 mutationObserver.observe( fakeParentNode, { childList: true } );
11697 } else {
11698 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
11699 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
11700 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
11701 }
11702 };
11703
11704 /**
11705 * Automatically adjust the size of the text input.
11706 *
11707 * This only affects #multiline inputs that are {@link #autosize autosized}.
11708 *
11709 * @chainable
11710 */
11711 OO.ui.TextInputWidget.prototype.adjustSize = function () {
11712 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
11713
11714 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
11715 this.$clone
11716 .val( this.$input.val() )
11717 .attr( 'rows', '' )
11718 // Set inline height property to 0 to measure scroll height
11719 .css( 'height', 0 );
11720
11721 this.$clone.removeClass( 'oo-ui-element-hidden' );
11722
11723 this.valCache = this.$input.val();
11724
11725 scrollHeight = this.$clone[ 0 ].scrollHeight;
11726
11727 // Remove inline height property to measure natural heights
11728 this.$clone.css( 'height', '' );
11729 innerHeight = this.$clone.innerHeight();
11730 outerHeight = this.$clone.outerHeight();
11731
11732 // Measure max rows height
11733 this.$clone
11734 .attr( 'rows', this.maxRows )
11735 .css( 'height', 'auto' )
11736 .val( '' );
11737 maxInnerHeight = this.$clone.innerHeight();
11738
11739 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11740 // Equals 1 on Blink-based browsers and 0 everywhere else
11741 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11742 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11743
11744 this.$clone.addClass( 'oo-ui-element-hidden' );
11745
11746 // Only apply inline height when expansion beyond natural height is needed
11747 if ( idealHeight > innerHeight ) {
11748 // Use the difference between the inner and outer height as a buffer
11749 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
11750 } else {
11751 this.$input.css( 'height', '' );
11752 }
11753 }
11754 return this;
11755 };
11756
11757 /**
11758 * @inheritdoc
11759 * @private
11760 */
11761 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
11762 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
11763 };
11764
11765 /**
11766 * Check if the input supports multiple lines.
11767 *
11768 * @return {boolean}
11769 */
11770 OO.ui.TextInputWidget.prototype.isMultiline = function () {
11771 return !!this.multiline;
11772 };
11773
11774 /**
11775 * Check if the input automatically adjusts its size.
11776 *
11777 * @return {boolean}
11778 */
11779 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
11780 return !!this.autosize;
11781 };
11782
11783 /**
11784 * Select the entire text of the input.
11785 *
11786 * @chainable
11787 */
11788 OO.ui.TextInputWidget.prototype.select = function () {
11789 this.$input.select();
11790 return this;
11791 };
11792
11793 /**
11794 * Set the validation pattern.
11795 *
11796 * The validation pattern is either a regular expression or the symbolic name of a pattern
11797 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11798 * value must contain only numbers).
11799 *
11800 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
11801 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11802 */
11803 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11804 if ( validate instanceof RegExp ) {
11805 this.validate = validate;
11806 } else {
11807 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11808 }
11809 };
11810
11811 /**
11812 * Sets the 'invalid' flag appropriately.
11813 */
11814 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
11815 var widget = this;
11816 this.isValid().done( function ( valid ) {
11817 widget.setFlags( { invalid: !valid } );
11818 } );
11819 };
11820
11821 /**
11822 * Check if a value is valid.
11823 *
11824 * This method returns a promise that resolves with a boolean `true` if the current value is
11825 * considered valid according to the supplied {@link #validate validation pattern}.
11826 *
11827 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
11828 */
11829 OO.ui.TextInputWidget.prototype.isValid = function () {
11830 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
11831 };
11832
11833 /**
11834 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11835 *
11836 * @param {string} labelPosition Label position, 'before' or 'after'
11837 * @chainable
11838 */
11839 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11840 this.labelPosition = labelPosition;
11841 this.updatePosition();
11842 return this;
11843 };
11844
11845 /**
11846 * Deprecated alias of #setLabelPosition
11847 *
11848 * @deprecated Use setLabelPosition instead.
11849 */
11850 OO.ui.TextInputWidget.prototype.setPosition =
11851 OO.ui.TextInputWidget.prototype.setLabelPosition;
11852
11853 /**
11854 * Update the position of the inline label.
11855 *
11856 * This method is called by #setLabelPosition, and can also be called on its own if
11857 * something causes the label to be mispositioned.
11858 *
11859 *
11860 * @chainable
11861 */
11862 OO.ui.TextInputWidget.prototype.updatePosition = function () {
11863 var after = this.labelPosition === 'after';
11864
11865 this.$element
11866 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
11867 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
11868
11869 if ( this.label ) {
11870 this.positionLabel();
11871 }
11872
11873 return this;
11874 };
11875
11876 /**
11877 * Position the label by setting the correct padding on the input.
11878 *
11879 * @private
11880 * @chainable
11881 */
11882 OO.ui.TextInputWidget.prototype.positionLabel = function () {
11883 // Clear old values
11884 this.$input
11885 // Clear old values if present
11886 .css( {
11887 'padding-right': '',
11888 'padding-left': ''
11889 } );
11890
11891 if ( this.label ) {
11892 this.$element.append( this.$label );
11893 } else {
11894 this.$label.detach();
11895 return;
11896 }
11897
11898 var after = this.labelPosition === 'after',
11899 rtl = this.$element.css( 'direction' ) === 'rtl',
11900 property = after === rtl ? 'padding-left' : 'padding-right';
11901
11902 this.$input.css( property, this.$label.outerWidth( true ) );
11903
11904 return this;
11905 };
11906
11907 /**
11908 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
11909 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
11910 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
11911 *
11912 * - by typing a value in the text input field. If the value exactly matches the value of a menu
11913 * option, that option will appear to be selected.
11914 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
11915 * input field.
11916 *
11917 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
11918 *
11919 * @example
11920 * // Example: A ComboBoxWidget.
11921 * var comboBox = new OO.ui.ComboBoxWidget( {
11922 * label: 'ComboBoxWidget',
11923 * input: { value: 'Option One' },
11924 * menu: {
11925 * items: [
11926 * new OO.ui.MenuOptionWidget( {
11927 * data: 'Option 1',
11928 * label: 'Option One'
11929 * } ),
11930 * new OO.ui.MenuOptionWidget( {
11931 * data: 'Option 2',
11932 * label: 'Option Two'
11933 * } ),
11934 * new OO.ui.MenuOptionWidget( {
11935 * data: 'Option 3',
11936 * label: 'Option Three'
11937 * } ),
11938 * new OO.ui.MenuOptionWidget( {
11939 * data: 'Option 4',
11940 * label: 'Option Four'
11941 * } ),
11942 * new OO.ui.MenuOptionWidget( {
11943 * data: 'Option 5',
11944 * label: 'Option Five'
11945 * } )
11946 * ]
11947 * }
11948 * } );
11949 * $( 'body' ).append( comboBox.$element );
11950 *
11951 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
11952 *
11953 * @class
11954 * @extends OO.ui.Widget
11955 * @mixins OO.ui.TabIndexedElement
11956 *
11957 * @constructor
11958 * @param {Object} [config] Configuration options
11959 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
11960 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
11961 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
11962 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
11963 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
11964 */
11965 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
11966 // Configuration initialization
11967 config = config || {};
11968
11969 // Parent constructor
11970 OO.ui.ComboBoxWidget.super.call( this, config );
11971
11972 // Properties (must be set before TabIndexedElement constructor call)
11973 this.$indicator = this.$( '<span>' );
11974
11975 // Mixin constructors
11976 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
11977
11978 // Properties
11979 this.$overlay = config.$overlay || this.$element;
11980 this.input = new OO.ui.TextInputWidget( $.extend(
11981 {
11982 indicator: 'down',
11983 $indicator: this.$indicator,
11984 disabled: this.isDisabled()
11985 },
11986 config.input
11987 ) );
11988 this.input.$input.eq( 0 ).attr( {
11989 role: 'combobox',
11990 'aria-autocomplete': 'list'
11991 } );
11992 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
11993 {
11994 widget: this,
11995 input: this.input,
11996 disabled: this.isDisabled()
11997 },
11998 config.menu
11999 ) );
12000
12001 // Events
12002 this.$indicator.on( {
12003 click: this.onClick.bind( this ),
12004 keypress: this.onKeyPress.bind( this )
12005 } );
12006 this.input.connect( this, {
12007 change: 'onInputChange',
12008 enter: 'onInputEnter'
12009 } );
12010 this.menu.connect( this, {
12011 choose: 'onMenuChoose',
12012 add: 'onMenuItemsChange',
12013 remove: 'onMenuItemsChange'
12014 } );
12015
12016 // Initialization
12017 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
12018 this.$overlay.append( this.menu.$element );
12019 this.onMenuItemsChange();
12020 };
12021
12022 /* Setup */
12023
12024 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
12025 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
12026
12027 /* Methods */
12028
12029 /**
12030 * Get the combobox's menu.
12031 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12032 */
12033 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
12034 return this.menu;
12035 };
12036
12037 /**
12038 * Handle input change events.
12039 *
12040 * @private
12041 * @param {string} value New value
12042 */
12043 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
12044 var match = this.menu.getItemFromData( value );
12045
12046 this.menu.selectItem( match );
12047 if ( this.menu.getHighlightedItem() ) {
12048 this.menu.highlightItem( match );
12049 }
12050
12051 if ( !this.isDisabled() ) {
12052 this.menu.toggle( true );
12053 }
12054 };
12055
12056 /**
12057 * Handle mouse click events.
12058 *
12059 *
12060 * @private
12061 * @param {jQuery.Event} e Mouse click event
12062 */
12063 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
12064 if ( !this.isDisabled() && e.which === 1 ) {
12065 this.menu.toggle();
12066 this.input.$input[ 0 ].focus();
12067 }
12068 return false;
12069 };
12070
12071 /**
12072 * Handle key press events.
12073 *
12074 *
12075 * @private
12076 * @param {jQuery.Event} e Key press event
12077 */
12078 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
12079 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
12080 this.menu.toggle();
12081 this.input.$input[ 0 ].focus();
12082 return false;
12083 }
12084 };
12085
12086 /**
12087 * Handle input enter events.
12088 *
12089 * @private
12090 */
12091 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
12092 if ( !this.isDisabled() ) {
12093 this.menu.toggle( false );
12094 }
12095 };
12096
12097 /**
12098 * Handle menu choose events.
12099 *
12100 * @private
12101 * @param {OO.ui.OptionWidget} item Chosen item
12102 */
12103 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
12104 if ( item ) {
12105 this.input.setValue( item.getData() );
12106 }
12107 };
12108
12109 /**
12110 * Handle menu item change events.
12111 *
12112 * @private
12113 */
12114 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
12115 var match = this.menu.getItemFromData( this.input.getValue() );
12116 this.menu.selectItem( match );
12117 if ( this.menu.getHighlightedItem() ) {
12118 this.menu.highlightItem( match );
12119 }
12120 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
12121 };
12122
12123 /**
12124 * @inheritdoc
12125 */
12126 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
12127 // Parent method
12128 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
12129
12130 if ( this.input ) {
12131 this.input.setDisabled( this.isDisabled() );
12132 }
12133 if ( this.menu ) {
12134 this.menu.setDisabled( this.isDisabled() );
12135 }
12136
12137 return this;
12138 };
12139
12140 /**
12141 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12142 * be configured with a `label` option that is set to a string, a label node, or a function:
12143 *
12144 * - String: a plaintext string
12145 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12146 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12147 * - Function: a function that will produce a string in the future. Functions are used
12148 * in cases where the value of the label is not currently defined.
12149 *
12150 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12151 * will come into focus when the label is clicked.
12152 *
12153 * @example
12154 * // Examples of LabelWidgets
12155 * var label1 = new OO.ui.LabelWidget( {
12156 * label: 'plaintext label'
12157 * } );
12158 * var label2 = new OO.ui.LabelWidget( {
12159 * label: $( '<a href="default.html">jQuery label</a>' )
12160 * } );
12161 * // Create a fieldset layout with fields for each example
12162 * var fieldset = new OO.ui.FieldsetLayout();
12163 * fieldset.addItems( [
12164 * new OO.ui.FieldLayout( label1 ),
12165 * new OO.ui.FieldLayout( label2 )
12166 * ] );
12167 * $( 'body' ).append( fieldset.$element );
12168 *
12169 *
12170 * @class
12171 * @extends OO.ui.Widget
12172 * @mixins OO.ui.LabelElement
12173 *
12174 * @constructor
12175 * @param {Object} [config] Configuration options
12176 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12177 * Clicking the label will focus the specified input field.
12178 */
12179 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
12180 // Configuration initialization
12181 config = config || {};
12182
12183 // Parent constructor
12184 OO.ui.LabelWidget.super.call( this, config );
12185
12186 // Mixin constructors
12187 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
12188 OO.ui.TitledElement.call( this, config );
12189
12190 // Properties
12191 this.input = config.input;
12192
12193 // Events
12194 if ( this.input instanceof OO.ui.InputWidget ) {
12195 this.$element.on( 'click', this.onClick.bind( this ) );
12196 }
12197
12198 // Initialization
12199 this.$element.addClass( 'oo-ui-labelWidget' );
12200 };
12201
12202 /* Setup */
12203
12204 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
12205 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
12206 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
12207
12208 /* Static Properties */
12209
12210 OO.ui.LabelWidget.static.tagName = 'span';
12211
12212 /* Methods */
12213
12214 /**
12215 * Handles label mouse click events.
12216 *
12217 * @private
12218 * @param {jQuery.Event} e Mouse click event
12219 */
12220 OO.ui.LabelWidget.prototype.onClick = function () {
12221 this.input.simulateLabelClick();
12222 return false;
12223 };
12224
12225 /**
12226 * OptionWidgets are special elements that can be selected and configured with data. The
12227 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12228 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12229 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12230 *
12231 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12232 *
12233 * @class
12234 * @extends OO.ui.Widget
12235 * @mixins OO.ui.LabelElement
12236 * @mixins OO.ui.FlaggedElement
12237 *
12238 * @constructor
12239 * @param {Object} [config] Configuration options
12240 */
12241 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
12242 // Configuration initialization
12243 config = config || {};
12244
12245 // Parent constructor
12246 OO.ui.OptionWidget.super.call( this, config );
12247
12248 // Mixin constructors
12249 OO.ui.ItemWidget.call( this );
12250 OO.ui.LabelElement.call( this, config );
12251 OO.ui.FlaggedElement.call( this, config );
12252
12253 // Properties
12254 this.selected = false;
12255 this.highlighted = false;
12256 this.pressed = false;
12257
12258 // Initialization
12259 this.$element
12260 .data( 'oo-ui-optionWidget', this )
12261 .attr( 'role', 'option' )
12262 .addClass( 'oo-ui-optionWidget' )
12263 .append( this.$label );
12264 };
12265
12266 /* Setup */
12267
12268 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12269 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12270 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12271 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12272
12273 /* Static Properties */
12274
12275 OO.ui.OptionWidget.static.selectable = true;
12276
12277 OO.ui.OptionWidget.static.highlightable = true;
12278
12279 OO.ui.OptionWidget.static.pressable = true;
12280
12281 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12282
12283 /* Methods */
12284
12285 /**
12286 * Check if the option can be selected.
12287 *
12288 * @return {boolean} Item is selectable
12289 */
12290 OO.ui.OptionWidget.prototype.isSelectable = function () {
12291 return this.constructor.static.selectable && !this.isDisabled();
12292 };
12293
12294 /**
12295 * Check if the option can be highlighted. A highlight indicates that the option
12296 * may be selected when a user presses enter or clicks. Disabled items cannot
12297 * be highlighted.
12298 *
12299 * @return {boolean} Item is highlightable
12300 */
12301 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12302 return this.constructor.static.highlightable && !this.isDisabled();
12303 };
12304
12305 /**
12306 * Check if the option can be pressed. The pressed state occurs when a user mouses
12307 * down on an item, but has not yet let go of the mouse.
12308 *
12309 * @return {boolean} Item is pressable
12310 */
12311 OO.ui.OptionWidget.prototype.isPressable = function () {
12312 return this.constructor.static.pressable && !this.isDisabled();
12313 };
12314
12315 /**
12316 * Check if the option is selected.
12317 *
12318 * @return {boolean} Item is selected
12319 */
12320 OO.ui.OptionWidget.prototype.isSelected = function () {
12321 return this.selected;
12322 };
12323
12324 /**
12325 * Check if the option is highlighted. A highlight indicates that the
12326 * item may be selected when a user presses enter or clicks.
12327 *
12328 * @return {boolean} Item is highlighted
12329 */
12330 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12331 return this.highlighted;
12332 };
12333
12334 /**
12335 * Check if the option is pressed. The pressed state occurs when a user mouses
12336 * down on an item, but has not yet let go of the mouse. The item may appear
12337 * selected, but it will not be selected until the user releases the mouse.
12338 *
12339 * @return {boolean} Item is pressed
12340 */
12341 OO.ui.OptionWidget.prototype.isPressed = function () {
12342 return this.pressed;
12343 };
12344
12345 /**
12346 * Set the option’s selected state. In general, all modifications to the selection
12347 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12348 * method instead of this method.
12349 *
12350 * @param {boolean} [state=false] Select option
12351 * @chainable
12352 */
12353 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12354 if ( this.constructor.static.selectable ) {
12355 this.selected = !!state;
12356 this.$element
12357 .toggleClass( 'oo-ui-optionWidget-selected', state )
12358 .attr( 'aria-selected', state.toString() );
12359 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12360 this.scrollElementIntoView();
12361 }
12362 this.updateThemeClasses();
12363 }
12364 return this;
12365 };
12366
12367 /**
12368 * Set the option’s highlighted state. In general, all programmatic
12369 * modifications to the highlight should be handled by the
12370 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12371 * method instead of this method.
12372 *
12373 * @param {boolean} [state=false] Highlight option
12374 * @chainable
12375 */
12376 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12377 if ( this.constructor.static.highlightable ) {
12378 this.highlighted = !!state;
12379 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12380 this.updateThemeClasses();
12381 }
12382 return this;
12383 };
12384
12385 /**
12386 * Set the option’s pressed state. In general, all
12387 * programmatic modifications to the pressed state should be handled by the
12388 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12389 * method instead of this method.
12390 *
12391 * @param {boolean} [state=false] Press option
12392 * @chainable
12393 */
12394 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12395 if ( this.constructor.static.pressable ) {
12396 this.pressed = !!state;
12397 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12398 this.updateThemeClasses();
12399 }
12400 return this;
12401 };
12402
12403 /**
12404 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12405 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12406 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12407 * options. For more information about options and selects, please see the
12408 * [OOjs UI documentation on MediaWiki][1].
12409 *
12410 * @example
12411 * // Decorated options in a select widget
12412 * var select = new OO.ui.SelectWidget( {
12413 * items: [
12414 * new OO.ui.DecoratedOptionWidget( {
12415 * data: 'a',
12416 * label: 'Option with icon',
12417 * icon: 'help'
12418 * } ),
12419 * new OO.ui.DecoratedOptionWidget( {
12420 * data: 'b',
12421 * label: 'Option with indicator',
12422 * indicator: 'next'
12423 * } )
12424 * ]
12425 * } );
12426 * $( 'body' ).append( select.$element );
12427 *
12428 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12429 *
12430 * @class
12431 * @extends OO.ui.OptionWidget
12432 * @mixins OO.ui.IconElement
12433 * @mixins OO.ui.IndicatorElement
12434 *
12435 * @constructor
12436 * @param {Object} [config] Configuration options
12437 */
12438 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
12439 // Parent constructor
12440 OO.ui.DecoratedOptionWidget.super.call( this, config );
12441
12442 // Mixin constructors
12443 OO.ui.IconElement.call( this, config );
12444 OO.ui.IndicatorElement.call( this, config );
12445
12446 // Initialization
12447 this.$element
12448 .addClass( 'oo-ui-decoratedOptionWidget' )
12449 .prepend( this.$icon )
12450 .append( this.$indicator );
12451 };
12452
12453 /* Setup */
12454
12455 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
12456 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
12457 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
12458
12459 /**
12460 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12461 * can be selected and configured with data. The class is
12462 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12463 * [OOjs UI documentation on MediaWiki] [1] for more information.
12464 *
12465 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12466 *
12467 * @class
12468 * @extends OO.ui.DecoratedOptionWidget
12469 * @mixins OO.ui.ButtonElement
12470 * @mixins OO.ui.TabIndexedElement
12471 *
12472 * @constructor
12473 * @param {Object} [config] Configuration options
12474 */
12475 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
12476 // Configuration initialization
12477 config = $.extend( { tabIndex: -1 }, config );
12478
12479 // Parent constructor
12480 OO.ui.ButtonOptionWidget.super.call( this, config );
12481
12482 // Mixin constructors
12483 OO.ui.ButtonElement.call( this, config );
12484 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12485
12486 // Initialization
12487 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
12488 this.$button.append( this.$element.contents() );
12489 this.$element.append( this.$button );
12490 };
12491
12492 /* Setup */
12493
12494 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
12495 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
12496 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
12497
12498 /* Static Properties */
12499
12500 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12501 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
12502
12503 OO.ui.ButtonOptionWidget.static.highlightable = false;
12504
12505 /* Methods */
12506
12507 /**
12508 * @inheritdoc
12509 */
12510 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
12511 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
12512
12513 if ( this.constructor.static.selectable ) {
12514 this.setActive( state );
12515 }
12516
12517 return this;
12518 };
12519
12520 /**
12521 * RadioOptionWidget is an option widget that looks like a radio button.
12522 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12523 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12524 *
12525 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12526 *
12527 * @class
12528 * @extends OO.ui.OptionWidget
12529 *
12530 * @constructor
12531 * @param {Object} [config] Configuration options
12532 */
12533 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
12534 // Configuration initialization
12535 config = config || {};
12536
12537 // Properties (must be done before parent constructor which calls #setDisabled)
12538 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
12539
12540 // Parent constructor
12541 OO.ui.RadioOptionWidget.super.call( this, config );
12542
12543 // Initialization
12544 this.$element
12545 .addClass( 'oo-ui-radioOptionWidget' )
12546 .prepend( this.radio.$element );
12547 };
12548
12549 /* Setup */
12550
12551 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
12552
12553 /* Static Properties */
12554
12555 OO.ui.RadioOptionWidget.static.highlightable = false;
12556
12557 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
12558
12559 OO.ui.RadioOptionWidget.static.pressable = false;
12560
12561 OO.ui.RadioOptionWidget.static.tagName = 'label';
12562
12563 /* Methods */
12564
12565 /**
12566 * @inheritdoc
12567 */
12568 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
12569 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
12570
12571 this.radio.setSelected( state );
12572
12573 return this;
12574 };
12575
12576 /**
12577 * @inheritdoc
12578 */
12579 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
12580 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
12581
12582 this.radio.setDisabled( this.isDisabled() );
12583
12584 return this;
12585 };
12586
12587 /**
12588 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12589 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12590 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12591 *
12592 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12593 *
12594 * @class
12595 * @extends OO.ui.DecoratedOptionWidget
12596 *
12597 * @constructor
12598 * @param {Object} [config] Configuration options
12599 */
12600 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
12601 // Configuration initialization
12602 config = $.extend( { icon: 'check' }, config );
12603
12604 // Parent constructor
12605 OO.ui.MenuOptionWidget.super.call( this, config );
12606
12607 // Initialization
12608 this.$element
12609 .attr( 'role', 'menuitem' )
12610 .addClass( 'oo-ui-menuOptionWidget' );
12611 };
12612
12613 /* Setup */
12614
12615 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
12616
12617 /* Static Properties */
12618
12619 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
12620
12621 /**
12622 * Section to group one or more items in a OO.ui.MenuSelectWidget.
12623 *
12624 * @class
12625 * @extends OO.ui.DecoratedOptionWidget
12626 *
12627 * @constructor
12628 * @param {Object} [config] Configuration options
12629 */
12630 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
12631 // Parent constructor
12632 OO.ui.MenuSectionOptionWidget.super.call( this, config );
12633
12634 // Initialization
12635 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
12636 };
12637
12638 /* Setup */
12639
12640 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
12641
12642 /* Static Properties */
12643
12644 OO.ui.MenuSectionOptionWidget.static.selectable = false;
12645
12646 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
12647
12648 /**
12649 * Items for an OO.ui.OutlineSelectWidget.
12650 *
12651 * @class
12652 * @extends OO.ui.DecoratedOptionWidget
12653 *
12654 * @constructor
12655 * @param {Object} [config] Configuration options
12656 * @cfg {number} [level] Indentation level
12657 * @cfg {boolean} [movable] Allow modification from outline controls
12658 */
12659 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
12660 // Configuration initialization
12661 config = config || {};
12662
12663 // Parent constructor
12664 OO.ui.OutlineOptionWidget.super.call( this, config );
12665
12666 // Properties
12667 this.level = 0;
12668 this.movable = !!config.movable;
12669 this.removable = !!config.removable;
12670
12671 // Initialization
12672 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
12673 this.setLevel( config.level );
12674 };
12675
12676 /* Setup */
12677
12678 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
12679
12680 /* Static Properties */
12681
12682 OO.ui.OutlineOptionWidget.static.highlightable = false;
12683
12684 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
12685
12686 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
12687
12688 OO.ui.OutlineOptionWidget.static.levels = 3;
12689
12690 /* Methods */
12691
12692 /**
12693 * Check if item is movable.
12694 *
12695 * Movability is used by outline controls.
12696 *
12697 * @return {boolean} Item is movable
12698 */
12699 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
12700 return this.movable;
12701 };
12702
12703 /**
12704 * Check if item is removable.
12705 *
12706 * Removability is used by outline controls.
12707 *
12708 * @return {boolean} Item is removable
12709 */
12710 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
12711 return this.removable;
12712 };
12713
12714 /**
12715 * Get indentation level.
12716 *
12717 * @return {number} Indentation level
12718 */
12719 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
12720 return this.level;
12721 };
12722
12723 /**
12724 * Set movability.
12725 *
12726 * Movability is used by outline controls.
12727 *
12728 * @param {boolean} movable Item is movable
12729 * @chainable
12730 */
12731 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
12732 this.movable = !!movable;
12733 this.updateThemeClasses();
12734 return this;
12735 };
12736
12737 /**
12738 * Set removability.
12739 *
12740 * Removability is used by outline controls.
12741 *
12742 * @param {boolean} movable Item is removable
12743 * @chainable
12744 */
12745 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
12746 this.removable = !!removable;
12747 this.updateThemeClasses();
12748 return this;
12749 };
12750
12751 /**
12752 * Set indentation level.
12753 *
12754 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12755 * @chainable
12756 */
12757 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
12758 var levels = this.constructor.static.levels,
12759 levelClass = this.constructor.static.levelClass,
12760 i = levels;
12761
12762 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
12763 while ( i-- ) {
12764 if ( this.level === i ) {
12765 this.$element.addClass( levelClass + i );
12766 } else {
12767 this.$element.removeClass( levelClass + i );
12768 }
12769 }
12770 this.updateThemeClasses();
12771
12772 return this;
12773 };
12774
12775 /**
12776 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
12777 * By default, each popup has an anchor that points toward its origin.
12778 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
12779 *
12780 * @example
12781 * // A popup widget.
12782 * var popup = new OO.ui.PopupWidget( {
12783 * $content: $( '<p>Hi there!</p>' ),
12784 * padded: true,
12785 * width: 300
12786 * } );
12787 *
12788 * $( 'body' ).append( popup.$element );
12789 * // To display the popup, toggle the visibility to 'true'.
12790 * popup.toggle( true );
12791 *
12792 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
12793 *
12794 * @class
12795 * @extends OO.ui.Widget
12796 * @mixins OO.ui.LabelElement
12797 *
12798 * @constructor
12799 * @param {Object} [config] Configuration options
12800 * @cfg {number} [width=320] Width of popup in pixels
12801 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
12802 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12803 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
12804 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
12805 * For left-aligned popups, the left edge is aligned to the anchor.
12806 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
12807 * See the [OOjs UI docs on MediaWiki][3] for an example.
12808 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
12809 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
12810 * @cfg {jQuery} [$content] Content to append to the popup's body
12811 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
12812 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
12813 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
12814 * for an example.
12815 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
12816 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
12817 * button.
12818 * @cfg {boolean} [padded] Add padding to the popup's body
12819 */
12820 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
12821 // Configuration initialization
12822 config = config || {};
12823
12824 // Parent constructor
12825 OO.ui.PopupWidget.super.call( this, config );
12826
12827 // Properties (must be set before ClippableElement constructor call)
12828 this.$body = $( '<div>' );
12829
12830 // Mixin constructors
12831 OO.ui.LabelElement.call( this, config );
12832 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
12833
12834 // Properties
12835 this.$popup = $( '<div>' );
12836 this.$head = $( '<div>' );
12837 this.$anchor = $( '<div>' );
12838 // If undefined, will be computed lazily in updateDimensions()
12839 this.$container = config.$container;
12840 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
12841 this.autoClose = !!config.autoClose;
12842 this.$autoCloseIgnore = config.$autoCloseIgnore;
12843 this.transitionTimeout = null;
12844 this.anchor = null;
12845 this.width = config.width !== undefined ? config.width : 320;
12846 this.height = config.height !== undefined ? config.height : null;
12847 this.align = config.align || 'center';
12848 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
12849 this.onMouseDownHandler = this.onMouseDown.bind( this );
12850 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
12851
12852 // Events
12853 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
12854
12855 // Initialization
12856 this.toggleAnchor( config.anchor === undefined || config.anchor );
12857 this.$body.addClass( 'oo-ui-popupWidget-body' );
12858 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
12859 this.$head
12860 .addClass( 'oo-ui-popupWidget-head' )
12861 .append( this.$label, this.closeButton.$element );
12862 if ( !config.head ) {
12863 this.$head.addClass( 'oo-ui-element-hidden' );
12864 }
12865 this.$popup
12866 .addClass( 'oo-ui-popupWidget-popup' )
12867 .append( this.$head, this.$body );
12868 this.$element
12869 .addClass( 'oo-ui-popupWidget' )
12870 .append( this.$popup, this.$anchor );
12871 // Move content, which was added to #$element by OO.ui.Widget, to the body
12872 if ( config.$content instanceof jQuery ) {
12873 this.$body.append( config.$content );
12874 }
12875 if ( config.padded ) {
12876 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
12877 }
12878
12879 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
12880 // that reference properties not initialized at that time of parent class construction
12881 // TODO: Find a better way to handle post-constructor setup
12882 this.visible = false;
12883 this.$element.addClass( 'oo-ui-element-hidden' );
12884 };
12885
12886 /* Setup */
12887
12888 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
12889 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
12890 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
12891
12892 /* Methods */
12893
12894 /**
12895 * Handles mouse down events.
12896 *
12897 * @private
12898 * @param {MouseEvent} e Mouse down event
12899 */
12900 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
12901 if (
12902 this.isVisible() &&
12903 !$.contains( this.$element[ 0 ], e.target ) &&
12904 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
12905 ) {
12906 this.toggle( false );
12907 }
12908 };
12909
12910 /**
12911 * Bind mouse down listener.
12912 *
12913 * @private
12914 */
12915 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
12916 // Capture clicks outside popup
12917 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
12918 };
12919
12920 /**
12921 * Handles close button click events.
12922 *
12923 * @private
12924 */
12925 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
12926 if ( this.isVisible() ) {
12927 this.toggle( false );
12928 }
12929 };
12930
12931 /**
12932 * Unbind mouse down listener.
12933 *
12934 * @private
12935 */
12936 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
12937 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
12938 };
12939
12940 /**
12941 * Handles key down events.
12942 *
12943 * @private
12944 * @param {KeyboardEvent} e Key down event
12945 */
12946 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
12947 if (
12948 e.which === OO.ui.Keys.ESCAPE &&
12949 this.isVisible()
12950 ) {
12951 this.toggle( false );
12952 e.preventDefault();
12953 e.stopPropagation();
12954 }
12955 };
12956
12957 /**
12958 * Bind key down listener.
12959 *
12960 * @private
12961 */
12962 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
12963 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
12964 };
12965
12966 /**
12967 * Unbind key down listener.
12968 *
12969 * @private
12970 */
12971 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
12972 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
12973 };
12974
12975 /**
12976 * Show, hide, or toggle the visibility of the anchor.
12977 *
12978 * @param {boolean} [show] Show anchor, omit to toggle
12979 */
12980 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
12981 show = show === undefined ? !this.anchored : !!show;
12982
12983 if ( this.anchored !== show ) {
12984 if ( show ) {
12985 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
12986 } else {
12987 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
12988 }
12989 this.anchored = show;
12990 }
12991 };
12992
12993 /**
12994 * Check if the anchor is visible.
12995 *
12996 * @return {boolean} Anchor is visible
12997 */
12998 OO.ui.PopupWidget.prototype.hasAnchor = function () {
12999 return this.anchor;
13000 };
13001
13002 /**
13003 * @inheritdoc
13004 */
13005 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
13006 show = show === undefined ? !this.isVisible() : !!show;
13007
13008 var change = show !== this.isVisible();
13009
13010 // Parent method
13011 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
13012
13013 if ( change ) {
13014 if ( show ) {
13015 if ( this.autoClose ) {
13016 this.bindMouseDownListener();
13017 this.bindKeyDownListener();
13018 }
13019 this.updateDimensions();
13020 this.toggleClipping( true );
13021 } else {
13022 this.toggleClipping( false );
13023 if ( this.autoClose ) {
13024 this.unbindMouseDownListener();
13025 this.unbindKeyDownListener();
13026 }
13027 }
13028 }
13029
13030 return this;
13031 };
13032
13033 /**
13034 * Set the size of the popup.
13035 *
13036 * Changing the size may also change the popup's position depending on the alignment.
13037 *
13038 * @param {number} width Width in pixels
13039 * @param {number} height Height in pixels
13040 * @param {boolean} [transition=false] Use a smooth transition
13041 * @chainable
13042 */
13043 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
13044 this.width = width;
13045 this.height = height !== undefined ? height : null;
13046 if ( this.isVisible() ) {
13047 this.updateDimensions( transition );
13048 }
13049 };
13050
13051 /**
13052 * Update the size and position.
13053 *
13054 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13055 * be called automatically.
13056 *
13057 * @param {boolean} [transition=false] Use a smooth transition
13058 * @chainable
13059 */
13060 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
13061 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
13062 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
13063 widget = this;
13064
13065 if ( !this.$container ) {
13066 // Lazy-initialize $container if not specified in constructor
13067 this.$container = $( this.getClosestScrollableElementContainer() );
13068 }
13069
13070 // Set height and width before measuring things, since it might cause our measurements
13071 // to change (e.g. due to scrollbars appearing or disappearing)
13072 this.$popup.css( {
13073 width: this.width,
13074 height: this.height !== null ? this.height : 'auto'
13075 } );
13076
13077 // Compute initial popupOffset based on alignment
13078 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
13079
13080 // Figure out if this will cause the popup to go beyond the edge of the container
13081 originOffset = this.$element.offset().left;
13082 containerLeft = this.$container.offset().left;
13083 containerWidth = this.$container.innerWidth();
13084 containerRight = containerLeft + containerWidth;
13085 popupLeft = popupOffset - this.containerPadding;
13086 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
13087 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
13088 overlapRight = containerRight - ( originOffset + popupRight );
13089
13090 // Adjust offset to make the popup not go beyond the edge, if needed
13091 if ( overlapRight < 0 ) {
13092 popupOffset += overlapRight;
13093 } else if ( overlapLeft < 0 ) {
13094 popupOffset -= overlapLeft;
13095 }
13096
13097 // Adjust offset to avoid anchor being rendered too close to the edge
13098 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13099 // TODO: Find a measurement that works for CSS anchors and image anchors
13100 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
13101 if ( popupOffset + this.width < anchorWidth ) {
13102 popupOffset = anchorWidth - this.width;
13103 } else if ( -popupOffset < anchorWidth ) {
13104 popupOffset = -anchorWidth;
13105 }
13106
13107 // Prevent transition from being interrupted
13108 clearTimeout( this.transitionTimeout );
13109 if ( transition ) {
13110 // Enable transition
13111 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
13112 }
13113
13114 // Position body relative to anchor
13115 this.$popup.css( 'margin-left', popupOffset );
13116
13117 if ( transition ) {
13118 // Prevent transitioning after transition is complete
13119 this.transitionTimeout = setTimeout( function () {
13120 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13121 }, 200 );
13122 } else {
13123 // Prevent transitioning immediately
13124 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13125 }
13126
13127 // Reevaluate clipping state since we've relocated and resized the popup
13128 this.clip();
13129
13130 return this;
13131 };
13132
13133 /**
13134 * Progress bars visually display the status of an operation, such as a download,
13135 * and can be either determinate or indeterminate:
13136 *
13137 * - **determinate** process bars show the percent of an operation that is complete.
13138 *
13139 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13140 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13141 * not use percentages.
13142 *
13143 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13144 *
13145 * @example
13146 * // Examples of determinate and indeterminate progress bars.
13147 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13148 * progress: 33
13149 * } );
13150 * var progressBar2 = new OO.ui.ProgressBarWidget();
13151 *
13152 * // Create a FieldsetLayout to layout progress bars
13153 * var fieldset = new OO.ui.FieldsetLayout;
13154 * fieldset.addItems( [
13155 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13156 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13157 * ] );
13158 * $( 'body' ).append( fieldset.$element );
13159 *
13160 * @class
13161 * @extends OO.ui.Widget
13162 *
13163 * @constructor
13164 * @param {Object} [config] Configuration options
13165 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13166 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13167 * By default, the progress bar is indeterminate.
13168 */
13169 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
13170 // Configuration initialization
13171 config = config || {};
13172
13173 // Parent constructor
13174 OO.ui.ProgressBarWidget.super.call( this, config );
13175
13176 // Properties
13177 this.$bar = $( '<div>' );
13178 this.progress = null;
13179
13180 // Initialization
13181 this.setProgress( config.progress !== undefined ? config.progress : false );
13182 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
13183 this.$element
13184 .attr( {
13185 role: 'progressbar',
13186 'aria-valuemin': 0,
13187 'aria-valuemax': 100
13188 } )
13189 .addClass( 'oo-ui-progressBarWidget' )
13190 .append( this.$bar );
13191 };
13192
13193 /* Setup */
13194
13195 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
13196
13197 /* Static Properties */
13198
13199 OO.ui.ProgressBarWidget.static.tagName = 'div';
13200
13201 /* Methods */
13202
13203 /**
13204 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13205 *
13206 * @return {number|boolean} Progress percent
13207 */
13208 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
13209 return this.progress;
13210 };
13211
13212 /**
13213 * Set the percent of the process completed or `false` for an indeterminate process.
13214 *
13215 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13216 */
13217 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
13218 this.progress = progress;
13219
13220 if ( progress !== false ) {
13221 this.$bar.css( 'width', this.progress + '%' );
13222 this.$element.attr( 'aria-valuenow', this.progress );
13223 } else {
13224 this.$bar.css( 'width', '' );
13225 this.$element.removeAttr( 'aria-valuenow' );
13226 }
13227 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
13228 };
13229
13230 /**
13231 * Search widget.
13232 *
13233 * Search widgets combine a query input, placed above, and a results selection widget, placed below.
13234 * Results are cleared and populated each time the query is changed.
13235 *
13236 * @class
13237 * @extends OO.ui.Widget
13238 *
13239 * @constructor
13240 * @param {Object} [config] Configuration options
13241 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13242 * @cfg {string} [value] Initial query value
13243 */
13244 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
13245 // Configuration initialization
13246 config = config || {};
13247
13248 // Parent constructor
13249 OO.ui.SearchWidget.super.call( this, config );
13250
13251 // Properties
13252 this.query = new OO.ui.TextInputWidget( {
13253 icon: 'search',
13254 placeholder: config.placeholder,
13255 value: config.value
13256 } );
13257 this.results = new OO.ui.SelectWidget();
13258 this.$query = $( '<div>' );
13259 this.$results = $( '<div>' );
13260
13261 // Events
13262 this.query.connect( this, {
13263 change: 'onQueryChange',
13264 enter: 'onQueryEnter'
13265 } );
13266 this.results.connect( this, {
13267 highlight: 'onResultsHighlight',
13268 select: 'onResultsSelect'
13269 } );
13270 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
13271
13272 // Initialization
13273 this.$query
13274 .addClass( 'oo-ui-searchWidget-query' )
13275 .append( this.query.$element );
13276 this.$results
13277 .addClass( 'oo-ui-searchWidget-results' )
13278 .append( this.results.$element );
13279 this.$element
13280 .addClass( 'oo-ui-searchWidget' )
13281 .append( this.$results, this.$query );
13282 };
13283
13284 /* Setup */
13285
13286 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
13287
13288 /* Events */
13289
13290 /**
13291 * @event highlight
13292 * @param {Object|null} item Item data or null if no item is highlighted
13293 */
13294
13295 /**
13296 * @event select
13297 * @param {Object|null} item Item data or null if no item is selected
13298 */
13299
13300 /* Methods */
13301
13302 /**
13303 * Handle query key down events.
13304 *
13305 * @param {jQuery.Event} e Key down event
13306 */
13307 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
13308 var highlightedItem, nextItem,
13309 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
13310
13311 if ( dir ) {
13312 highlightedItem = this.results.getHighlightedItem();
13313 if ( !highlightedItem ) {
13314 highlightedItem = this.results.getSelectedItem();
13315 }
13316 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
13317 this.results.highlightItem( nextItem );
13318 nextItem.scrollElementIntoView();
13319 }
13320 };
13321
13322 /**
13323 * Handle select widget select events.
13324 *
13325 * Clears existing results. Subclasses should repopulate items according to new query.
13326 *
13327 * @param {string} value New value
13328 */
13329 OO.ui.SearchWidget.prototype.onQueryChange = function () {
13330 // Reset
13331 this.results.clearItems();
13332 };
13333
13334 /**
13335 * Handle select widget enter key events.
13336 *
13337 * Selects highlighted item.
13338 *
13339 * @param {string} value New value
13340 */
13341 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
13342 // Reset
13343 this.results.selectItem( this.results.getHighlightedItem() );
13344 };
13345
13346 /**
13347 * Handle select widget highlight events.
13348 *
13349 * @param {OO.ui.OptionWidget} item Highlighted item
13350 * @fires highlight
13351 */
13352 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
13353 this.emit( 'highlight', item ? item.getData() : null );
13354 };
13355
13356 /**
13357 * Handle select widget select events.
13358 *
13359 * @param {OO.ui.OptionWidget} item Selected item
13360 * @fires select
13361 */
13362 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
13363 this.emit( 'select', item ? item.getData() : null );
13364 };
13365
13366 /**
13367 * Get the query input.
13368 *
13369 * @return {OO.ui.TextInputWidget} Query input
13370 */
13371 OO.ui.SearchWidget.prototype.getQuery = function () {
13372 return this.query;
13373 };
13374
13375 /**
13376 * Get the results list.
13377 *
13378 * @return {OO.ui.SelectWidget} Select list
13379 */
13380 OO.ui.SearchWidget.prototype.getResults = function () {
13381 return this.results;
13382 };
13383
13384 /**
13385 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13386 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13387 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13388 * menu selects}.
13389 *
13390 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13391 * information, please see the [OOjs UI documentation on MediaWiki][1].
13392 *
13393 * @example
13394 * // Example of a select widget with three options
13395 * var select = new OO.ui.SelectWidget( {
13396 * items: [
13397 * new OO.ui.OptionWidget( {
13398 * data: 'a',
13399 * label: 'Option One',
13400 * } ),
13401 * new OO.ui.OptionWidget( {
13402 * data: 'b',
13403 * label: 'Option Two',
13404 * } ),
13405 * new OO.ui.OptionWidget( {
13406 * data: 'c',
13407 * label: 'Option Three',
13408 * } )
13409 * ]
13410 * } );
13411 * $( 'body' ).append( select.$element );
13412 *
13413 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13414 *
13415 * @class
13416 * @extends OO.ui.Widget
13417 * @mixins OO.ui.GroupElement
13418 *
13419 * @constructor
13420 * @param {Object} [config] Configuration options
13421 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13422 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13423 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13424 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13425 */
13426 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
13427 // Configuration initialization
13428 config = config || {};
13429
13430 // Parent constructor
13431 OO.ui.SelectWidget.super.call( this, config );
13432
13433 // Mixin constructors
13434 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
13435
13436 // Properties
13437 this.pressed = false;
13438 this.selecting = null;
13439 this.onMouseUpHandler = this.onMouseUp.bind( this );
13440 this.onMouseMoveHandler = this.onMouseMove.bind( this );
13441 this.onKeyDownHandler = this.onKeyDown.bind( this );
13442
13443 // Events
13444 this.$element.on( {
13445 mousedown: this.onMouseDown.bind( this ),
13446 mouseover: this.onMouseOver.bind( this ),
13447 mouseleave: this.onMouseLeave.bind( this )
13448 } );
13449
13450 // Initialization
13451 this.$element
13452 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13453 .attr( 'role', 'listbox' );
13454 if ( Array.isArray( config.items ) ) {
13455 this.addItems( config.items );
13456 }
13457 };
13458
13459 /* Setup */
13460
13461 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
13462
13463 // Need to mixin base class as well
13464 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
13465 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
13466
13467 /* Events */
13468
13469 /**
13470 * @event highlight
13471 *
13472 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13473 *
13474 * @param {OO.ui.OptionWidget|null} item Highlighted item
13475 */
13476
13477 /**
13478 * @event press
13479 *
13480 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13481 * pressed state of an option.
13482 *
13483 * @param {OO.ui.OptionWidget|null} item Pressed item
13484 */
13485
13486 /**
13487 * @event select
13488 *
13489 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13490 *
13491 * @param {OO.ui.OptionWidget|null} item Selected item
13492 */
13493
13494 /**
13495 * @event choose
13496 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13497 * @param {OO.ui.OptionWidget|null} item Chosen item
13498 */
13499
13500 /**
13501 * @event add
13502 *
13503 * An `add` event is emitted when options are added to the select with the #addItems method.
13504 *
13505 * @param {OO.ui.OptionWidget[]} items Added items
13506 * @param {number} index Index of insertion point
13507 */
13508
13509 /**
13510 * @event remove
13511 *
13512 * A `remove` event is emitted when options are removed from the select with the #clearItems
13513 * or #removeItems methods.
13514 *
13515 * @param {OO.ui.OptionWidget[]} items Removed items
13516 */
13517
13518 /* Methods */
13519
13520 /**
13521 * Handle mouse down events.
13522 *
13523 * @private
13524 * @param {jQuery.Event} e Mouse down event
13525 */
13526 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
13527 var item;
13528
13529 if ( !this.isDisabled() && e.which === 1 ) {
13530 this.togglePressed( true );
13531 item = this.getTargetItem( e );
13532 if ( item && item.isSelectable() ) {
13533 this.pressItem( item );
13534 this.selecting = item;
13535 this.getElementDocument().addEventListener(
13536 'mouseup',
13537 this.onMouseUpHandler,
13538 true
13539 );
13540 this.getElementDocument().addEventListener(
13541 'mousemove',
13542 this.onMouseMoveHandler,
13543 true
13544 );
13545 }
13546 }
13547 return false;
13548 };
13549
13550 /**
13551 * Handle mouse up events.
13552 *
13553 * @private
13554 * @param {jQuery.Event} e Mouse up event
13555 */
13556 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
13557 var item;
13558
13559 this.togglePressed( false );
13560 if ( !this.selecting ) {
13561 item = this.getTargetItem( e );
13562 if ( item && item.isSelectable() ) {
13563 this.selecting = item;
13564 }
13565 }
13566 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
13567 this.pressItem( null );
13568 this.chooseItem( this.selecting );
13569 this.selecting = null;
13570 }
13571
13572 this.getElementDocument().removeEventListener(
13573 'mouseup',
13574 this.onMouseUpHandler,
13575 true
13576 );
13577 this.getElementDocument().removeEventListener(
13578 'mousemove',
13579 this.onMouseMoveHandler,
13580 true
13581 );
13582
13583 return false;
13584 };
13585
13586 /**
13587 * Handle mouse move events.
13588 *
13589 * @private
13590 * @param {jQuery.Event} e Mouse move event
13591 */
13592 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
13593 var item;
13594
13595 if ( !this.isDisabled() && this.pressed ) {
13596 item = this.getTargetItem( e );
13597 if ( item && item !== this.selecting && item.isSelectable() ) {
13598 this.pressItem( item );
13599 this.selecting = item;
13600 }
13601 }
13602 return false;
13603 };
13604
13605 /**
13606 * Handle mouse over events.
13607 *
13608 * @private
13609 * @param {jQuery.Event} e Mouse over event
13610 */
13611 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
13612 var item;
13613
13614 if ( !this.isDisabled() ) {
13615 item = this.getTargetItem( e );
13616 this.highlightItem( item && item.isHighlightable() ? item : null );
13617 }
13618 return false;
13619 };
13620
13621 /**
13622 * Handle mouse leave events.
13623 *
13624 * @private
13625 * @param {jQuery.Event} e Mouse over event
13626 */
13627 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
13628 if ( !this.isDisabled() ) {
13629 this.highlightItem( null );
13630 }
13631 return false;
13632 };
13633
13634 /**
13635 * Handle key down events.
13636 *
13637 * @protected
13638 * @param {jQuery.Event} e Key down event
13639 */
13640 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
13641 var nextItem,
13642 handled = false,
13643 currentItem = this.getHighlightedItem() || this.getSelectedItem();
13644
13645 if ( !this.isDisabled() && this.isVisible() ) {
13646 switch ( e.keyCode ) {
13647 case OO.ui.Keys.ENTER:
13648 if ( currentItem && currentItem.constructor.static.highlightable ) {
13649 // Was only highlighted, now let's select it. No-op if already selected.
13650 this.chooseItem( currentItem );
13651 handled = true;
13652 }
13653 break;
13654 case OO.ui.Keys.UP:
13655 case OO.ui.Keys.LEFT:
13656 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
13657 handled = true;
13658 break;
13659 case OO.ui.Keys.DOWN:
13660 case OO.ui.Keys.RIGHT:
13661 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
13662 handled = true;
13663 break;
13664 case OO.ui.Keys.ESCAPE:
13665 case OO.ui.Keys.TAB:
13666 if ( currentItem && currentItem.constructor.static.highlightable ) {
13667 currentItem.setHighlighted( false );
13668 }
13669 this.unbindKeyDownListener();
13670 // Don't prevent tabbing away / defocusing
13671 handled = false;
13672 break;
13673 }
13674
13675 if ( nextItem ) {
13676 if ( nextItem.constructor.static.highlightable ) {
13677 this.highlightItem( nextItem );
13678 } else {
13679 this.chooseItem( nextItem );
13680 }
13681 nextItem.scrollElementIntoView();
13682 }
13683
13684 if ( handled ) {
13685 // Can't just return false, because e is not always a jQuery event
13686 e.preventDefault();
13687 e.stopPropagation();
13688 }
13689 }
13690 };
13691
13692 /**
13693 * Bind key down listener.
13694 *
13695 * @protected
13696 */
13697 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
13698 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
13699 };
13700
13701 /**
13702 * Unbind key down listener.
13703 *
13704 * @protected
13705 */
13706 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
13707 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
13708 };
13709
13710 /**
13711 * Get the closest item to a jQuery.Event.
13712 *
13713 * @private
13714 * @param {jQuery.Event} e
13715 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
13716 */
13717 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
13718 var $item = $( e.target ).closest( '.oo-ui-optionWidget' );
13719 if ( $item.length ) {
13720 return $item.data( 'oo-ui-optionWidget' );
13721 }
13722 return null;
13723 };
13724
13725 /**
13726 * Get selected item.
13727 *
13728 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
13729 */
13730 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
13731 var i, len;
13732
13733 for ( i = 0, len = this.items.length; i < len; i++ ) {
13734 if ( this.items[ i ].isSelected() ) {
13735 return this.items[ i ];
13736 }
13737 }
13738 return null;
13739 };
13740
13741 /**
13742 * Get highlighted item.
13743 *
13744 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
13745 */
13746 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
13747 var i, len;
13748
13749 for ( i = 0, len = this.items.length; i < len; i++ ) {
13750 if ( this.items[ i ].isHighlighted() ) {
13751 return this.items[ i ];
13752 }
13753 }
13754 return null;
13755 };
13756
13757 /**
13758 * Toggle pressed state.
13759 *
13760 * Press is a state that occurs when a user mouses down on an item, but
13761 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
13762 * until the user releases the mouse.
13763 *
13764 * @param {boolean} pressed An option is being pressed
13765 */
13766 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
13767 if ( pressed === undefined ) {
13768 pressed = !this.pressed;
13769 }
13770 if ( pressed !== this.pressed ) {
13771 this.$element
13772 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
13773 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
13774 this.pressed = pressed;
13775 }
13776 };
13777
13778 /**
13779 * Highlight an option. If the `item` param is omitted, no options will be highlighted
13780 * and any existing highlight will be removed. The highlight is mutually exclusive.
13781 *
13782 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
13783 * @fires highlight
13784 * @chainable
13785 */
13786 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
13787 var i, len, highlighted,
13788 changed = false;
13789
13790 for ( i = 0, len = this.items.length; i < len; i++ ) {
13791 highlighted = this.items[ i ] === item;
13792 if ( this.items[ i ].isHighlighted() !== highlighted ) {
13793 this.items[ i ].setHighlighted( highlighted );
13794 changed = true;
13795 }
13796 }
13797 if ( changed ) {
13798 this.emit( 'highlight', item );
13799 }
13800
13801 return this;
13802 };
13803
13804 /**
13805 * Programmatically select an option by its reference. If the `item` parameter is omitted,
13806 * all options will be deselected.
13807 *
13808 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
13809 * @fires select
13810 * @chainable
13811 */
13812 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
13813 var i, len, selected,
13814 changed = false;
13815
13816 for ( i = 0, len = this.items.length; i < len; i++ ) {
13817 selected = this.items[ i ] === item;
13818 if ( this.items[ i ].isSelected() !== selected ) {
13819 this.items[ i ].setSelected( selected );
13820 changed = true;
13821 }
13822 }
13823 if ( changed ) {
13824 this.emit( 'select', item );
13825 }
13826
13827 return this;
13828 };
13829
13830 /**
13831 * Press an item.
13832 *
13833 * Press is a state that occurs when a user mouses down on an item, but has not
13834 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
13835 * releases the mouse.
13836 *
13837 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
13838 * @fires press
13839 * @chainable
13840 */
13841 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
13842 var i, len, pressed,
13843 changed = false;
13844
13845 for ( i = 0, len = this.items.length; i < len; i++ ) {
13846 pressed = this.items[ i ] === item;
13847 if ( this.items[ i ].isPressed() !== pressed ) {
13848 this.items[ i ].setPressed( pressed );
13849 changed = true;
13850 }
13851 }
13852 if ( changed ) {
13853 this.emit( 'press', item );
13854 }
13855
13856 return this;
13857 };
13858
13859 /**
13860 * Choose an item.
13861 *
13862 * Note that ‘choose’ should never be modified programmatically. A user can choose
13863 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
13864 * use the #selectItem method.
13865 *
13866 * This method is identical to #selectItem, but may vary in subclasses that take additional action
13867 * when users choose an item with the keyboard or mouse.
13868 *
13869 * @param {OO.ui.OptionWidget} item Item to choose
13870 * @fires choose
13871 * @chainable
13872 */
13873 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
13874 this.selectItem( item );
13875 this.emit( 'choose', item );
13876
13877 return this;
13878 };
13879
13880 /**
13881 * Get an option by its position relative to the specified item (or to the start of the option array,
13882 * if item is `null`). The direction in which to search through the option array is specified with a
13883 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
13884 * `null` if there are no options in the array.
13885 *
13886 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
13887 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
13888 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
13889 */
13890 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
13891 var currentIndex, nextIndex, i,
13892 increase = direction > 0 ? 1 : -1,
13893 len = this.items.length;
13894
13895 if ( item instanceof OO.ui.OptionWidget ) {
13896 currentIndex = $.inArray( item, this.items );
13897 nextIndex = ( currentIndex + increase + len ) % len;
13898 } else {
13899 // If no item is selected and moving forward, start at the beginning.
13900 // If moving backward, start at the end.
13901 nextIndex = direction > 0 ? 0 : len - 1;
13902 }
13903
13904 for ( i = 0; i < len; i++ ) {
13905 item = this.items[ nextIndex ];
13906 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
13907 return item;
13908 }
13909 nextIndex = ( nextIndex + increase + len ) % len;
13910 }
13911 return null;
13912 };
13913
13914 /**
13915 * Get the next selectable item or `null` if there are no selectable items.
13916 * Disabled options and menu-section markers and breaks are not selectable.
13917 *
13918 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
13919 */
13920 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
13921 var i, len, item;
13922
13923 for ( i = 0, len = this.items.length; i < len; i++ ) {
13924 item = this.items[ i ];
13925 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
13926 return item;
13927 }
13928 }
13929
13930 return null;
13931 };
13932
13933 /**
13934 * Add an array of options to the select. Optionally, an index number can be used to
13935 * specify an insertion point.
13936 *
13937 * @param {OO.ui.OptionWidget[]} items Items to add
13938 * @param {number} [index] Index to insert items after
13939 * @fires add
13940 * @chainable
13941 */
13942 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
13943 // Mixin method
13944 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
13945
13946 // Always provide an index, even if it was omitted
13947 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
13948
13949 return this;
13950 };
13951
13952 /**
13953 * Remove the specified array of options from the select. Options will be detached
13954 * from the DOM, not removed, so they can be reused later. To remove all options from
13955 * the select, you may wish to use the #clearItems method instead.
13956 *
13957 * @param {OO.ui.OptionWidget[]} items Items to remove
13958 * @fires remove
13959 * @chainable
13960 */
13961 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
13962 var i, len, item;
13963
13964 // Deselect items being removed
13965 for ( i = 0, len = items.length; i < len; i++ ) {
13966 item = items[ i ];
13967 if ( item.isSelected() ) {
13968 this.selectItem( null );
13969 }
13970 }
13971
13972 // Mixin method
13973 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
13974
13975 this.emit( 'remove', items );
13976
13977 return this;
13978 };
13979
13980 /**
13981 * Clear all options from the select. Options will be detached from the DOM, not removed,
13982 * so that they can be reused later. To remove a subset of options from the select, use
13983 * the #removeItems method.
13984 *
13985 * @fires remove
13986 * @chainable
13987 */
13988 OO.ui.SelectWidget.prototype.clearItems = function () {
13989 var items = this.items.slice();
13990
13991 // Mixin method
13992 OO.ui.GroupWidget.prototype.clearItems.call( this );
13993
13994 // Clear selection
13995 this.selectItem( null );
13996
13997 this.emit( 'remove', items );
13998
13999 return this;
14000 };
14001
14002 /**
14003 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14004 * button options and is used together with
14005 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14006 * highlighting, choosing, and selecting mutually exclusive options. Please see
14007 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14008 *
14009 * @example
14010 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14011 * var option1 = new OO.ui.ButtonOptionWidget( {
14012 * data: 1,
14013 * label: 'Option 1',
14014 * title: 'Button option 1'
14015 * } );
14016 *
14017 * var option2 = new OO.ui.ButtonOptionWidget( {
14018 * data: 2,
14019 * label: 'Option 2',
14020 * title: 'Button option 2'
14021 * } );
14022 *
14023 * var option3 = new OO.ui.ButtonOptionWidget( {
14024 * data: 3,
14025 * label: 'Option 3',
14026 * title: 'Button option 3'
14027 * } );
14028 *
14029 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14030 * items: [ option1, option2, option3 ]
14031 * } );
14032 * $( 'body' ).append( buttonSelect.$element );
14033 *
14034 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14035 *
14036 * @class
14037 * @extends OO.ui.SelectWidget
14038 * @mixins OO.ui.TabIndexedElement
14039 *
14040 * @constructor
14041 * @param {Object} [config] Configuration options
14042 */
14043 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
14044 // Parent constructor
14045 OO.ui.ButtonSelectWidget.super.call( this, config );
14046
14047 // Mixin constructors
14048 OO.ui.TabIndexedElement.call( this, config );
14049
14050 // Events
14051 this.$element.on( {
14052 focus: this.bindKeyDownListener.bind( this ),
14053 blur: this.unbindKeyDownListener.bind( this )
14054 } );
14055
14056 // Initialization
14057 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
14058 };
14059
14060 /* Setup */
14061
14062 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
14063 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
14064
14065 /**
14066 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14067 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14068 * an interface for adding, removing and selecting options.
14069 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14070 *
14071 * @example
14072 * // A RadioSelectWidget with RadioOptions.
14073 * var option1 = new OO.ui.RadioOptionWidget( {
14074 * data: 'a',
14075 * label: 'Selected radio option'
14076 * } );
14077 *
14078 * var option2 = new OO.ui.RadioOptionWidget( {
14079 * data: 'b',
14080 * label: 'Unselected radio option'
14081 * } );
14082 *
14083 * var radioSelect=new OO.ui.RadioSelectWidget( {
14084 * items: [ option1, option2 ]
14085 * } );
14086 *
14087 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14088 * radioSelect.selectItem( option1 );
14089 *
14090 * $( 'body' ).append( radioSelect.$element );
14091 *
14092 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14093
14094 *
14095 * @class
14096 * @extends OO.ui.SelectWidget
14097 * @mixins OO.ui.TabIndexedElement
14098 *
14099 * @constructor
14100 * @param {Object} [config] Configuration options
14101 */
14102 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
14103 // Parent constructor
14104 OO.ui.RadioSelectWidget.super.call( this, config );
14105
14106 // Mixin constructors
14107 OO.ui.TabIndexedElement.call( this, config );
14108
14109 // Events
14110 this.$element.on( {
14111 focus: this.bindKeyDownListener.bind( this ),
14112 blur: this.unbindKeyDownListener.bind( this )
14113 } );
14114
14115 // Initialization
14116 this.$element.addClass( 'oo-ui-radioSelectWidget' );
14117 };
14118
14119 /* Setup */
14120
14121 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
14122 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
14123
14124 /**
14125 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14126 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14127 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14128 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14129 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14130 * and customized to be opened, closed, and displayed as needed.
14131 *
14132 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14133 * mouse outside the menu.
14134 *
14135 * Menus also have support for keyboard interaction:
14136 *
14137 * - Enter/Return key: choose and select a menu option
14138 * - Up-arrow key: highlight the previous menu option
14139 * - Down-arrow key: highlight the next menu option
14140 * - Esc key: hide the menu
14141 *
14142 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14143 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14144 *
14145 * @class
14146 * @extends OO.ui.SelectWidget
14147 * @mixins OO.ui.ClippableElement
14148 *
14149 * @constructor
14150 * @param {Object} [config] Configuration options
14151 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14152 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14153 * and {@link OO.ui.LookupElement LookupElement}
14154 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14155 * anywhere on the page outside of this widget, the menu is hidden.
14156 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14157 */
14158 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
14159 // Configuration initialization
14160 config = config || {};
14161
14162 // Parent constructor
14163 OO.ui.MenuSelectWidget.super.call( this, config );
14164
14165 // Mixin constructors
14166 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
14167
14168 // Properties
14169 this.newItems = null;
14170 this.autoHide = config.autoHide === undefined || !!config.autoHide;
14171 this.$input = config.input ? config.input.$input : null;
14172 this.$widget = config.widget ? config.widget.$element : null;
14173 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
14174
14175 // Initialization
14176 this.$element
14177 .addClass( 'oo-ui-menuSelectWidget' )
14178 .attr( 'role', 'menu' );
14179
14180 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14181 // that reference properties not initialized at that time of parent class construction
14182 // TODO: Find a better way to handle post-constructor setup
14183 this.visible = false;
14184 this.$element.addClass( 'oo-ui-element-hidden' );
14185 };
14186
14187 /* Setup */
14188
14189 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
14190 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
14191
14192 /* Methods */
14193
14194 /**
14195 * Handles document mouse down events.
14196 *
14197 * @protected
14198 * @param {jQuery.Event} e Key down event
14199 */
14200 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
14201 if (
14202 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
14203 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
14204 ) {
14205 this.toggle( false );
14206 }
14207 };
14208
14209 /**
14210 * @inheritdoc
14211 */
14212 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
14213 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
14214
14215 if ( !this.isDisabled() && this.isVisible() ) {
14216 switch ( e.keyCode ) {
14217 case OO.ui.Keys.LEFT:
14218 case OO.ui.Keys.RIGHT:
14219 // Do nothing if a text field is associated, arrow keys will be handled natively
14220 if ( !this.$input ) {
14221 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14222 }
14223 break;
14224 case OO.ui.Keys.ESCAPE:
14225 case OO.ui.Keys.TAB:
14226 if ( currentItem ) {
14227 currentItem.setHighlighted( false );
14228 }
14229 this.toggle( false );
14230 // Don't prevent tabbing away, prevent defocusing
14231 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
14232 e.preventDefault();
14233 e.stopPropagation();
14234 }
14235 break;
14236 default:
14237 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14238 return;
14239 }
14240 }
14241 };
14242
14243 /**
14244 * @inheritdoc
14245 */
14246 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
14247 if ( this.$input ) {
14248 this.$input.on( 'keydown', this.onKeyDownHandler );
14249 } else {
14250 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
14251 }
14252 };
14253
14254 /**
14255 * @inheritdoc
14256 */
14257 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
14258 if ( this.$input ) {
14259 this.$input.off( 'keydown', this.onKeyDownHandler );
14260 } else {
14261 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
14262 }
14263 };
14264
14265 /**
14266 * Choose an item.
14267 *
14268 * When a user chooses an item, the menu is closed.
14269 *
14270 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14271 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14272 * @param {OO.ui.OptionWidget} item Item to choose
14273 * @chainable
14274 */
14275 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
14276 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
14277 this.toggle( false );
14278 return this;
14279 };
14280
14281 /**
14282 * @inheritdoc
14283 */
14284 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
14285 var i, len, item;
14286
14287 // Parent method
14288 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
14289
14290 // Auto-initialize
14291 if ( !this.newItems ) {
14292 this.newItems = [];
14293 }
14294
14295 for ( i = 0, len = items.length; i < len; i++ ) {
14296 item = items[ i ];
14297 if ( this.isVisible() ) {
14298 // Defer fitting label until item has been attached
14299 item.fitLabel();
14300 } else {
14301 this.newItems.push( item );
14302 }
14303 }
14304
14305 // Reevaluate clipping
14306 this.clip();
14307
14308 return this;
14309 };
14310
14311 /**
14312 * @inheritdoc
14313 */
14314 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
14315 // Parent method
14316 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
14317
14318 // Reevaluate clipping
14319 this.clip();
14320
14321 return this;
14322 };
14323
14324 /**
14325 * @inheritdoc
14326 */
14327 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
14328 // Parent method
14329 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
14330
14331 // Reevaluate clipping
14332 this.clip();
14333
14334 return this;
14335 };
14336
14337 /**
14338 * @inheritdoc
14339 */
14340 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
14341 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
14342
14343 var i, len,
14344 change = visible !== this.isVisible();
14345
14346 // Parent method
14347 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
14348
14349 if ( change ) {
14350 if ( visible ) {
14351 this.bindKeyDownListener();
14352
14353 if ( this.newItems && this.newItems.length ) {
14354 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
14355 this.newItems[ i ].fitLabel();
14356 }
14357 this.newItems = null;
14358 }
14359 this.toggleClipping( true );
14360
14361 // Auto-hide
14362 if ( this.autoHide ) {
14363 this.getElementDocument().addEventListener(
14364 'mousedown', this.onDocumentMouseDownHandler, true
14365 );
14366 }
14367 } else {
14368 this.unbindKeyDownListener();
14369 this.getElementDocument().removeEventListener(
14370 'mousedown', this.onDocumentMouseDownHandler, true
14371 );
14372 this.toggleClipping( false );
14373 }
14374 }
14375
14376 return this;
14377 };
14378
14379 /**
14380 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14381 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14382 * calculated and maintained when the menu is toggled or the window is resized.
14383 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14384 *
14385 * @class
14386 * @extends OO.ui.MenuSelectWidget
14387 *
14388 * @constructor
14389 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14390 * @param {Object} [config] Configuration options
14391 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14392 */
14393 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
14394 // Allow passing positional parameters inside the config object
14395 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
14396 config = inputWidget;
14397 inputWidget = config.inputWidget;
14398 }
14399
14400 // Configuration initialization
14401 config = config || {};
14402
14403 // Parent constructor
14404 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
14405
14406 // Properties
14407 this.inputWidget = inputWidget;
14408 this.$container = config.$container || this.inputWidget.$element;
14409 this.onWindowResizeHandler = this.onWindowResize.bind( this );
14410
14411 // Initialization
14412 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
14413 };
14414
14415 /* Setup */
14416
14417 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
14418
14419 /* Methods */
14420
14421 /**
14422 * Handle window resize event.
14423 *
14424 * @private
14425 * @param {jQuery.Event} e Window resize event
14426 */
14427 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
14428 this.position();
14429 };
14430
14431 /**
14432 * @inheritdoc
14433 */
14434 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
14435 visible = visible === undefined ? !this.isVisible() : !!visible;
14436
14437 var change = visible !== this.isVisible();
14438
14439 if ( change && visible ) {
14440 // Make sure the width is set before the parent method runs.
14441 // After this we have to call this.position(); again to actually
14442 // position ourselves correctly.
14443 this.position();
14444 }
14445
14446 // Parent method
14447 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
14448
14449 if ( change ) {
14450 if ( this.isVisible() ) {
14451 this.position();
14452 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
14453 } else {
14454 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
14455 }
14456 }
14457
14458 return this;
14459 };
14460
14461 /**
14462 * Position the menu.
14463 *
14464 * @private
14465 * @chainable
14466 */
14467 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
14468 var $container = this.$container,
14469 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
14470
14471 // Position under input
14472 pos.top += $container.height();
14473 this.$element.css( pos );
14474
14475 // Set width
14476 this.setIdealSize( $container.width() );
14477 // We updated the position, so re-evaluate the clipping state
14478 this.clip();
14479
14480 return this;
14481 };
14482
14483 /**
14484 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14485 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14486 *
14487 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14488 *
14489 * @class
14490 * @extends OO.ui.SelectWidget
14491 * @mixins OO.ui.TabIndexedElement
14492 *
14493 * @constructor
14494 * @param {Object} [config] Configuration options
14495 */
14496 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
14497 // Parent constructor
14498 OO.ui.OutlineSelectWidget.super.call( this, config );
14499
14500 // Mixin constructors
14501 OO.ui.TabIndexedElement.call( this, config );
14502
14503 // Events
14504 this.$element.on( {
14505 focus: this.bindKeyDownListener.bind( this ),
14506 blur: this.unbindKeyDownListener.bind( this )
14507 } );
14508
14509 // Initialization
14510 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
14511 };
14512
14513 /* Setup */
14514
14515 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
14516 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
14517
14518 /**
14519 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14520 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14521 * visually by a slider in the leftmost position.
14522 *
14523 * @example
14524 * // Toggle switches in the 'off' and 'on' position.
14525 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14526 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14527 * value: true
14528 * } );
14529 *
14530 * // Create a FieldsetLayout to layout and label switches
14531 * var fieldset = new OO.ui.FieldsetLayout( {
14532 * label: 'Toggle switches'
14533 * } );
14534 * fieldset.addItems( [
14535 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14536 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14537 * ] );
14538 * $( 'body' ).append( fieldset.$element );
14539 *
14540 * @class
14541 * @extends OO.ui.Widget
14542 * @mixins OO.ui.ToggleWidget
14543 * @mixins OO.ui.TabIndexedElement
14544 *
14545 * @constructor
14546 * @param {Object} [config] Configuration options
14547 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14548 * By default, the toggle switch is in the 'off' position.
14549 */
14550 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
14551 // Parent constructor
14552 OO.ui.ToggleSwitchWidget.super.call( this, config );
14553
14554 // Mixin constructors
14555 OO.ui.ToggleWidget.call( this, config );
14556 OO.ui.TabIndexedElement.call( this, config );
14557
14558 // Properties
14559 this.dragging = false;
14560 this.dragStart = null;
14561 this.sliding = false;
14562 this.$glow = $( '<span>' );
14563 this.$grip = $( '<span>' );
14564
14565 // Events
14566 this.$element.on( {
14567 click: this.onClick.bind( this ),
14568 keypress: this.onKeyPress.bind( this )
14569 } );
14570
14571 // Initialization
14572 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14573 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14574 this.$element
14575 .addClass( 'oo-ui-toggleSwitchWidget' )
14576 .attr( 'role', 'checkbox' )
14577 .append( this.$glow, this.$grip );
14578 };
14579
14580 /* Setup */
14581
14582 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
14583 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
14584 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
14585
14586 /* Methods */
14587
14588 /**
14589 * Handle mouse click events.
14590 *
14591 * @private
14592 * @param {jQuery.Event} e Mouse click event
14593 */
14594 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
14595 if ( !this.isDisabled() && e.which === 1 ) {
14596 this.setValue( !this.value );
14597 }
14598 return false;
14599 };
14600
14601 /**
14602 * Handle key press events.
14603 *
14604 * @private
14605 * @param {jQuery.Event} e Key press event
14606 */
14607 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
14608 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
14609 this.setValue( !this.value );
14610 return false;
14611 }
14612 };
14613
14614 }( OO ) );