MessagePoster followup: Dependency and docs
[lhc/web/wiklou.git] / resources / lib / oojs-ui / oojs-ui.js
1 /*!
2 * OOjs UI v0.9.4
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-25T22:24:05Z
10 */
11 ( function ( OO ) {
12
13 'use strict';
14
15 /**
16 * Namespace for all classes, static methods and static properties.
17 *
18 * @class
19 * @singleton
20 */
21 OO.ui = {};
22
23 OO.ui.bind = $.proxy;
24
25 /**
26 * @property {Object}
27 */
28 OO.ui.Keys = {
29 UNDEFINED: 0,
30 BACKSPACE: 8,
31 DELETE: 46,
32 LEFT: 37,
33 RIGHT: 39,
34 UP: 38,
35 DOWN: 40,
36 ENTER: 13,
37 END: 35,
38 HOME: 36,
39 TAB: 9,
40 PAGEUP: 33,
41 PAGEDOWN: 34,
42 ESCAPE: 27,
43 SHIFT: 16,
44 SPACE: 32
45 };
46
47 /**
48 * Get the user's language and any fallback languages.
49 *
50 * These language codes are used to localize user interface elements in the user's language.
51 *
52 * In environments that provide a localization system, this function should be overridden to
53 * return the user's language(s). The default implementation returns English (en) only.
54 *
55 * @return {string[]} Language codes, in descending order of priority
56 */
57 OO.ui.getUserLanguages = function () {
58 return [ 'en' ];
59 };
60
61 /**
62 * Get a value in an object keyed by language code.
63 *
64 * @param {Object.<string,Mixed>} obj Object keyed by language code
65 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
66 * @param {string} [fallback] Fallback code, used if no matching language can be found
67 * @return {Mixed} Local value
68 */
69 OO.ui.getLocalValue = function ( obj, lang, fallback ) {
70 var i, len, langs;
71
72 // Requested language
73 if ( obj[ lang ] ) {
74 return obj[ lang ];
75 }
76 // Known user language
77 langs = OO.ui.getUserLanguages();
78 for ( i = 0, len = langs.length; i < len; i++ ) {
79 lang = langs[ i ];
80 if ( obj[ lang ] ) {
81 return obj[ lang ];
82 }
83 }
84 // Fallback language
85 if ( obj[ fallback ] ) {
86 return obj[ fallback ];
87 }
88 // First existing language
89 for ( lang in obj ) {
90 return obj[ lang ];
91 }
92
93 return undefined;
94 };
95
96 /**
97 * Check if a node is contained within another node
98 *
99 * Similar to jQuery#contains except a list of containers can be supplied
100 * and a boolean argument allows you to include the container in the match list
101 *
102 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
103 * @param {HTMLElement} contained Node to find
104 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
105 * @return {boolean} The node is in the list of target nodes
106 */
107 OO.ui.contains = function ( containers, contained, matchContainers ) {
108 var i;
109 if ( !Array.isArray( containers ) ) {
110 containers = [ containers ];
111 }
112 for ( i = containers.length - 1; i >= 0; i-- ) {
113 if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) {
114 return true;
115 }
116 }
117 return false;
118 };
119
120 /**
121 * Reconstitute a JavaScript object corresponding to a widget created by
122 * the PHP implementation.
123 *
124 * This is an alias for `OO.ui.Element.static.infuse()`.
125 *
126 * @param {string|HTMLElement|jQuery} idOrNode
127 * A DOM id (if a string) or node for the widget to infuse.
128 * @return {OO.ui.Element}
129 * The `OO.ui.Element` corresponding to this (infusable) document node.
130 */
131 OO.ui.infuse = function ( idOrNode ) {
132 return OO.ui.Element.static.infuse( idOrNode );
133 };
134
135 ( function () {
136 /**
137 * Message store for the default implementation of OO.ui.msg
138 *
139 * Environments that provide a localization system should not use this, but should override
140 * OO.ui.msg altogether.
141 *
142 * @private
143 */
144 var messages = {
145 // Tool tip for a button that moves items in a list down one place
146 'ooui-outline-control-move-down': 'Move item down',
147 // Tool tip for a button that moves items in a list up one place
148 'ooui-outline-control-move-up': 'Move item up',
149 // Tool tip for a button that removes items from a list
150 'ooui-outline-control-remove': 'Remove item',
151 // Label for the toolbar group that contains a list of all other available tools
152 'ooui-toolbar-more': 'More',
153 // Label for the fake tool that expands the full list of tools in a toolbar group
154 'ooui-toolgroup-expand': 'More',
155 // Label for the fake tool that collapses the full list of tools in a toolbar group
156 'ooui-toolgroup-collapse': 'Fewer',
157 // Default label for the accept button of a confirmation dialog
158 'ooui-dialog-message-accept': 'OK',
159 // Default label for the reject button of a confirmation dialog
160 'ooui-dialog-message-reject': 'Cancel',
161 // Title for process dialog error description
162 'ooui-dialog-process-error': 'Something went wrong',
163 // Label for process dialog dismiss error button, visible when describing errors
164 'ooui-dialog-process-dismiss': 'Dismiss',
165 // Label for process dialog retry action button, visible when describing only recoverable errors
166 'ooui-dialog-process-retry': 'Try again',
167 // Label for process dialog retry action button, visible when describing only warnings
168 'ooui-dialog-process-continue': 'Continue'
169 };
170
171 /**
172 * Get a localized message.
173 *
174 * In environments that provide a localization system, this function should be overridden to
175 * return the message translated in the user's language. The default implementation always returns
176 * English messages.
177 *
178 * After the message key, message parameters may optionally be passed. In the default implementation,
179 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
180 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
181 * they support unnamed, ordered message parameters.
182 *
183 * @abstract
184 * @param {string} key Message key
185 * @param {Mixed...} [params] Message parameters
186 * @return {string} Translated message with parameters substituted
187 */
188 OO.ui.msg = function ( key ) {
189 var message = messages[ key ],
190 params = Array.prototype.slice.call( arguments, 1 );
191 if ( typeof message === 'string' ) {
192 // Perform $1 substitution
193 message = message.replace( /\$(\d+)/g, function ( unused, n ) {
194 var i = parseInt( n, 10 );
195 return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n;
196 } );
197 } else {
198 // Return placeholder if message not found
199 message = '[' + key + ']';
200 }
201 return message;
202 };
203
204 /**
205 * Package a message and arguments for deferred resolution.
206 *
207 * Use this when you are statically specifying a message and the message may not yet be present.
208 *
209 * @param {string} key Message key
210 * @param {Mixed...} [params] Message parameters
211 * @return {Function} Function that returns the resolved message when executed
212 */
213 OO.ui.deferMsg = function () {
214 var args = arguments;
215 return function () {
216 return OO.ui.msg.apply( OO.ui, args );
217 };
218 };
219
220 /**
221 * Resolve a message.
222 *
223 * If the message is a function it will be executed, otherwise it will pass through directly.
224 *
225 * @param {Function|string} msg Deferred message, or message text
226 * @return {string} Resolved message
227 */
228 OO.ui.resolveMsg = function ( msg ) {
229 if ( $.isFunction( msg ) ) {
230 return msg();
231 }
232 return msg;
233 };
234
235 } )();
236
237 /**
238 * Element that can be marked as pending.
239 *
240 * @abstract
241 * @class
242 *
243 * @constructor
244 * @param {Object} [config] Configuration options
245 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
246 */
247 OO.ui.PendingElement = function OoUiPendingElement( config ) {
248 // Configuration initialization
249 config = config || {};
250
251 // Properties
252 this.pending = 0;
253 this.$pending = null;
254
255 // Initialisation
256 this.setPendingElement( config.$pending || this.$element );
257 };
258
259 /* Setup */
260
261 OO.initClass( OO.ui.PendingElement );
262
263 /* Methods */
264
265 /**
266 * Set the pending element (and clean up any existing one).
267 *
268 * @param {jQuery} $pending The element to set to pending.
269 */
270 OO.ui.PendingElement.prototype.setPendingElement = function ( $pending ) {
271 if ( this.$pending ) {
272 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
273 }
274
275 this.$pending = $pending;
276 if ( this.pending > 0 ) {
277 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
278 }
279 };
280
281 /**
282 * Check if input is pending.
283 *
284 * @return {boolean}
285 */
286 OO.ui.PendingElement.prototype.isPending = function () {
287 return !!this.pending;
288 };
289
290 /**
291 * Increase the pending stack.
292 *
293 * @chainable
294 */
295 OO.ui.PendingElement.prototype.pushPending = function () {
296 if ( this.pending === 0 ) {
297 this.$pending.addClass( 'oo-ui-pendingElement-pending' );
298 this.updateThemeClasses();
299 }
300 this.pending++;
301
302 return this;
303 };
304
305 /**
306 * Reduce the pending stack.
307 *
308 * Clamped at zero.
309 *
310 * @chainable
311 */
312 OO.ui.PendingElement.prototype.popPending = function () {
313 if ( this.pending === 1 ) {
314 this.$pending.removeClass( 'oo-ui-pendingElement-pending' );
315 this.updateThemeClasses();
316 }
317 this.pending = Math.max( 0, this.pending - 1 );
318
319 return this;
320 };
321
322 /**
323 * ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
324 * Actions can be made available for specific contexts (modes) and circumstances
325 * (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
326 *
327 * ActionSets contain two types of actions:
328 *
329 * - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
330 * - Other: Other actions include all non-special visible actions.
331 *
332 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
333 *
334 * @example
335 * // Example: An action set used in a process dialog
336 * function MyProcessDialog( config ) {
337 * MyProcessDialog.super.call( this, config );
338 * }
339 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
340 * MyProcessDialog.static.title = 'An action set in a process dialog';
341 * // An action set that uses modes ('edit' and 'help' mode, in this example).
342 * MyProcessDialog.static.actions = [
343 * { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
344 * { action: 'help', modes: 'edit', label: 'Help' },
345 * { modes: 'edit', label: 'Cancel', flags: 'safe' },
346 * { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
347 * ];
348 *
349 * MyProcessDialog.prototype.initialize = function () {
350 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
351 * this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
352 * this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
353 * this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
354 * this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
355 * this.stackLayout = new OO.ui.StackLayout( {
356 * items: [ this.panel1, this.panel2 ]
357 * } );
358 * this.$body.append( this.stackLayout.$element );
359 * };
360 * MyProcessDialog.prototype.getSetupProcess = function ( data ) {
361 * return MyProcessDialog.super.prototype.getSetupProcess.call( this, data )
362 * .next( function () {
363 * this.actions.setMode( 'edit' );
364 * }, this );
365 * };
366 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
367 * if ( action === 'help' ) {
368 * this.actions.setMode( 'help' );
369 * this.stackLayout.setItem( this.panel2 );
370 * } else if ( action === 'back' ) {
371 * this.actions.setMode( 'edit' );
372 * this.stackLayout.setItem( this.panel1 );
373 * } else if ( action === 'continue' ) {
374 * var dialog = this;
375 * return new OO.ui.Process( function () {
376 * dialog.close();
377 * } );
378 * }
379 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
380 * };
381 * MyProcessDialog.prototype.getBodyHeight = function () {
382 * return this.panel1.$element.outerHeight( true );
383 * };
384 * var windowManager = new OO.ui.WindowManager();
385 * $( 'body' ).append( windowManager.$element );
386 * var dialog = new MyProcessDialog( {
387 * size: 'medium'
388 * } );
389 * windowManager.addWindows( [ dialog ] );
390 * windowManager.openWindow( dialog );
391 *
392 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
393 *
394 * @abstract
395 * @class
396 * @mixins OO.EventEmitter
397 *
398 * @constructor
399 * @param {Object} [config] Configuration options
400 */
401 OO.ui.ActionSet = function OoUiActionSet( config ) {
402 // Configuration initialization
403 config = config || {};
404
405 // Mixin constructors
406 OO.EventEmitter.call( this );
407
408 // Properties
409 this.list = [];
410 this.categories = {
411 actions: 'getAction',
412 flags: 'getFlags',
413 modes: 'getModes'
414 };
415 this.categorized = {};
416 this.special = {};
417 this.others = [];
418 this.organized = false;
419 this.changing = false;
420 this.changed = false;
421 };
422
423 /* Setup */
424
425 OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
426
427 /* Static Properties */
428
429 /**
430 * Symbolic name of the flags used to identify special actions. Special actions are displayed in the
431 * header of a {@link OO.ui.ProcessDialog process dialog}.
432 * See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
433 *
434 * [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
435 *
436 * @abstract
437 * @static
438 * @inheritable
439 * @property {string}
440 */
441 OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
442
443 /* Events */
444
445 /**
446 * @event click
447 *
448 * A 'click' event is emitted when an action is clicked.
449 *
450 * @param {OO.ui.ActionWidget} action Action that was clicked
451 */
452
453 /**
454 * @event resize
455 *
456 * A 'resize' event is emitted when an action widget is resized.
457 *
458 * @param {OO.ui.ActionWidget} action Action that was resized
459 */
460
461 /**
462 * @event add
463 *
464 * An 'add' event is emitted when actions are {@link #method-add added} to the action set.
465 *
466 * @param {OO.ui.ActionWidget[]} added Actions added
467 */
468
469 /**
470 * @event remove
471 *
472 * A 'remove' event is emitted when actions are {@link #method-remove removed}
473 * or {@link #clear cleared}.
474 *
475 * @param {OO.ui.ActionWidget[]} added Actions removed
476 */
477
478 /**
479 * @event change
480 *
481 * A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
482 * or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
483 *
484 */
485
486 /* Methods */
487
488 /**
489 * Handle action change events.
490 *
491 * @private
492 * @fires change
493 */
494 OO.ui.ActionSet.prototype.onActionChange = function () {
495 this.organized = false;
496 if ( this.changing ) {
497 this.changed = true;
498 } else {
499 this.emit( 'change' );
500 }
501 };
502
503 /**
504 * Check if an action is one of the special actions.
505 *
506 * @param {OO.ui.ActionWidget} action Action to check
507 * @return {boolean} Action is special
508 */
509 OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
510 var flag;
511
512 for ( flag in this.special ) {
513 if ( action === this.special[ flag ] ) {
514 return true;
515 }
516 }
517
518 return false;
519 };
520
521 /**
522 * Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
523 * or ‘disabled’.
524 *
525 * @param {Object} [filters] Filters to use, omit to get all actions
526 * @param {string|string[]} [filters.actions] Actions that action widgets must have
527 * @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
528 * @param {string|string[]} [filters.modes] Modes that action widgets must have
529 * @param {boolean} [filters.visible] Action widgets must be visible
530 * @param {boolean} [filters.disabled] Action widgets must be disabled
531 * @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
532 */
533 OO.ui.ActionSet.prototype.get = function ( filters ) {
534 var i, len, list, category, actions, index, match, matches;
535
536 if ( filters ) {
537 this.organize();
538
539 // Collect category candidates
540 matches = [];
541 for ( category in this.categorized ) {
542 list = filters[ category ];
543 if ( list ) {
544 if ( !Array.isArray( list ) ) {
545 list = [ list ];
546 }
547 for ( i = 0, len = list.length; i < len; i++ ) {
548 actions = this.categorized[ category ][ list[ i ] ];
549 if ( Array.isArray( actions ) ) {
550 matches.push.apply( matches, actions );
551 }
552 }
553 }
554 }
555 // Remove by boolean filters
556 for ( i = 0, len = matches.length; i < len; i++ ) {
557 match = matches[ i ];
558 if (
559 ( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
560 ( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
561 ) {
562 matches.splice( i, 1 );
563 len--;
564 i--;
565 }
566 }
567 // Remove duplicates
568 for ( i = 0, len = matches.length; i < len; i++ ) {
569 match = matches[ i ];
570 index = matches.lastIndexOf( match );
571 while ( index !== i ) {
572 matches.splice( index, 1 );
573 len--;
574 index = matches.lastIndexOf( match );
575 }
576 }
577 return matches;
578 }
579 return this.list.slice();
580 };
581
582 /**
583 * Get 'special' actions.
584 *
585 * Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
586 * Special flags can be configured in subclasses by changing the static #specialFlags property.
587 *
588 * @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
589 */
590 OO.ui.ActionSet.prototype.getSpecial = function () {
591 this.organize();
592 return $.extend( {}, this.special );
593 };
594
595 /**
596 * Get 'other' actions.
597 *
598 * Other actions include all non-special visible action widgets.
599 *
600 * @return {OO.ui.ActionWidget[]} 'Other' action widgets
601 */
602 OO.ui.ActionSet.prototype.getOthers = function () {
603 this.organize();
604 return this.others.slice();
605 };
606
607 /**
608 * Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
609 * to be available in the specified mode will be made visible. All other actions will be hidden.
610 *
611 * @param {string} mode The mode. Only actions configured to be available in the specified
612 * mode will be made visible.
613 * @chainable
614 * @fires toggle
615 * @fires change
616 */
617 OO.ui.ActionSet.prototype.setMode = function ( mode ) {
618 var i, len, action;
619
620 this.changing = true;
621 for ( i = 0, len = this.list.length; i < len; i++ ) {
622 action = this.list[ i ];
623 action.toggle( action.hasMode( mode ) );
624 }
625
626 this.organized = false;
627 this.changing = false;
628 this.emit( 'change' );
629
630 return this;
631 };
632
633 /**
634 * Set the abilities of the specified actions.
635 *
636 * Action widgets that are configured with the specified actions will be enabled
637 * or disabled based on the boolean values specified in the `actions`
638 * parameter.
639 *
640 * @param {Object.<string,boolean>} actions A list keyed by action name with boolean
641 * values that indicate whether or not the action should be enabled.
642 * @chainable
643 */
644 OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
645 var i, len, action, item;
646
647 for ( i = 0, len = this.list.length; i < len; i++ ) {
648 item = this.list[ i ];
649 action = item.getAction();
650 if ( actions[ action ] !== undefined ) {
651 item.setDisabled( !actions[ action ] );
652 }
653 }
654
655 return this;
656 };
657
658 /**
659 * Executes a function once per action.
660 *
661 * When making changes to multiple actions, use this method instead of iterating over the actions
662 * manually to defer emitting a #change event until after all actions have been changed.
663 *
664 * @param {Object|null} actions Filters to use to determine which actions to iterate over; see #get
665 * @param {Function} callback Callback to run for each action; callback is invoked with three
666 * arguments: the action, the action's index, the list of actions being iterated over
667 * @chainable
668 */
669 OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
670 this.changed = false;
671 this.changing = true;
672 this.get( filter ).forEach( callback );
673 this.changing = false;
674 if ( this.changed ) {
675 this.emit( 'change' );
676 }
677
678 return this;
679 };
680
681 /**
682 * Add action widgets to the action set.
683 *
684 * @param {OO.ui.ActionWidget[]} actions Action widgets to add
685 * @chainable
686 * @fires add
687 * @fires change
688 */
689 OO.ui.ActionSet.prototype.add = function ( actions ) {
690 var i, len, action;
691
692 this.changing = true;
693 for ( i = 0, len = actions.length; i < len; i++ ) {
694 action = actions[ i ];
695 action.connect( this, {
696 click: [ 'emit', 'click', action ],
697 resize: [ 'emit', 'resize', action ],
698 toggle: [ 'onActionChange' ]
699 } );
700 this.list.push( action );
701 }
702 this.organized = false;
703 this.emit( 'add', actions );
704 this.changing = false;
705 this.emit( 'change' );
706
707 return this;
708 };
709
710 /**
711 * Remove action widgets from the set.
712 *
713 * To remove all actions, you may wish to use the #clear method instead.
714 *
715 * @param {OO.ui.ActionWidget[]} actions Action widgets to remove
716 * @chainable
717 * @fires remove
718 * @fires change
719 */
720 OO.ui.ActionSet.prototype.remove = function ( actions ) {
721 var i, len, index, action;
722
723 this.changing = true;
724 for ( i = 0, len = actions.length; i < len; i++ ) {
725 action = actions[ i ];
726 index = this.list.indexOf( action );
727 if ( index !== -1 ) {
728 action.disconnect( this );
729 this.list.splice( index, 1 );
730 }
731 }
732 this.organized = false;
733 this.emit( 'remove', actions );
734 this.changing = false;
735 this.emit( 'change' );
736
737 return this;
738 };
739
740 /**
741 * Remove all action widets from the set.
742 *
743 * To remove only specified actions, use the {@link #method-remove remove} method instead.
744 *
745 * @chainable
746 * @fires remove
747 * @fires change
748 */
749 OO.ui.ActionSet.prototype.clear = function () {
750 var i, len, action,
751 removed = this.list.slice();
752
753 this.changing = true;
754 for ( i = 0, len = this.list.length; i < len; i++ ) {
755 action = this.list[ i ];
756 action.disconnect( this );
757 }
758
759 this.list = [];
760
761 this.organized = false;
762 this.emit( 'remove', removed );
763 this.changing = false;
764 this.emit( 'change' );
765
766 return this;
767 };
768
769 /**
770 * Organize actions.
771 *
772 * This is called whenever organized information is requested. It will only reorganize the actions
773 * if something has changed since the last time it ran.
774 *
775 * @private
776 * @chainable
777 */
778 OO.ui.ActionSet.prototype.organize = function () {
779 var i, iLen, j, jLen, flag, action, category, list, item, special,
780 specialFlags = this.constructor.static.specialFlags;
781
782 if ( !this.organized ) {
783 this.categorized = {};
784 this.special = {};
785 this.others = [];
786 for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
787 action = this.list[ i ];
788 if ( action.isVisible() ) {
789 // Populate categories
790 for ( category in this.categories ) {
791 if ( !this.categorized[ category ] ) {
792 this.categorized[ category ] = {};
793 }
794 list = action[ this.categories[ category ] ]();
795 if ( !Array.isArray( list ) ) {
796 list = [ list ];
797 }
798 for ( j = 0, jLen = list.length; j < jLen; j++ ) {
799 item = list[ j ];
800 if ( !this.categorized[ category ][ item ] ) {
801 this.categorized[ category ][ item ] = [];
802 }
803 this.categorized[ category ][ item ].push( action );
804 }
805 }
806 // Populate special/others
807 special = false;
808 for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
809 flag = specialFlags[ j ];
810 if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
811 this.special[ flag ] = action;
812 special = true;
813 break;
814 }
815 }
816 if ( !special ) {
817 this.others.push( action );
818 }
819 }
820 }
821 this.organized = true;
822 }
823
824 return this;
825 };
826
827 /**
828 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
829 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
830 * connected to them and can't be interacted with.
831 *
832 * @abstract
833 * @class
834 *
835 * @constructor
836 * @param {Object} [config] Configuration options
837 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
838 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
839 * for an example.
840 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
841 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
842 * @cfg {string} [text] Text to insert
843 * @cfg {Array} [content] An array of content elements to append (after #text).
844 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
845 * Instances of OO.ui.Element will have their $element appended.
846 * @cfg {jQuery} [$content] Content elements to append (after #text)
847 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
848 * Data can also be specified with the #setData method.
849 */
850 OO.ui.Element = function OoUiElement( config ) {
851 // Configuration initialization
852 config = config || {};
853
854 // Properties
855 this.$ = $;
856 this.visible = true;
857 this.data = config.data;
858 this.$element = config.$element ||
859 $( document.createElement( this.getTagName() ) );
860 this.elementGroup = null;
861 this.debouncedUpdateThemeClassesHandler = this.debouncedUpdateThemeClasses.bind( this );
862 this.updateThemeClassesPending = false;
863
864 // Initialization
865 if ( Array.isArray( config.classes ) ) {
866 this.$element.addClass( config.classes.join( ' ' ) );
867 }
868 if ( config.id ) {
869 this.$element.attr( 'id', config.id );
870 }
871 if ( config.text ) {
872 this.$element.text( config.text );
873 }
874 if ( config.content ) {
875 // The `content` property treats plain strings as text; use an
876 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
877 // appropriate $element appended.
878 this.$element.append( config.content.map( function ( v ) {
879 if ( typeof v === 'string' ) {
880 // Escape string so it is properly represented in HTML.
881 return document.createTextNode( v );
882 } else if ( v instanceof OO.ui.HtmlSnippet ) {
883 // Bypass escaping.
884 return v.toString();
885 } else if ( v instanceof OO.ui.Element ) {
886 return v.$element;
887 }
888 return v;
889 } ) );
890 }
891 if ( config.$content ) {
892 // The `$content` property treats plain strings as HTML.
893 this.$element.append( config.$content );
894 }
895 };
896
897 /* Setup */
898
899 OO.initClass( OO.ui.Element );
900
901 /* Static Properties */
902
903 /**
904 * The name of the HTML tag used by the element.
905 *
906 * The static value may be ignored if the #getTagName method is overridden.
907 *
908 * @static
909 * @inheritable
910 * @property {string}
911 */
912 OO.ui.Element.static.tagName = 'div';
913
914 /* Static Methods */
915
916 /**
917 * Reconstitute a JavaScript object corresponding to a widget created
918 * by the PHP implementation.
919 *
920 * @param {string|HTMLElement|jQuery} idOrNode
921 * A DOM id (if a string) or node for the widget to infuse.
922 * @return {OO.ui.Element}
923 * The `OO.ui.Element` corresponding to this (infusable) document node.
924 * For `Tag` objects emitted on the HTML side (used occasionally for content)
925 * the value returned is a newly-created Element wrapping around the existing
926 * DOM node.
927 */
928 OO.ui.Element.static.infuse = function ( idOrNode ) {
929 var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, true );
930 // Verify that the type matches up.
931 // FIXME: uncomment after T89721 is fixed (see T90929)
932 /*
933 if ( !( obj instanceof this['class'] ) ) {
934 throw new Error( 'Infusion type mismatch!' );
935 }
936 */
937 return obj;
938 };
939
940 /**
941 * Implementation helper for `infuse`; skips the type check and has an
942 * extra property so that only the top-level invocation touches the DOM.
943 * @private
944 * @param {string|HTMLElement|jQuery} idOrNode
945 * @param {boolean} top True only for top-level invocation.
946 * @return {OO.ui.Element}
947 */
948 OO.ui.Element.static.unsafeInfuse = function ( idOrNode, top ) {
949 // look for a cached result of a previous infusion.
950 var id, $elem, data, cls, obj;
951 if ( typeof idOrNode === 'string' ) {
952 id = idOrNode;
953 $elem = $( document.getElementById( id ) );
954 } else {
955 $elem = $( idOrNode );
956 id = $elem.attr( 'id' );
957 }
958 data = $elem.data( 'ooui-infused' );
959 if ( data ) {
960 // cached!
961 if ( data === true ) {
962 throw new Error( 'Circular dependency! ' + id );
963 }
964 return data;
965 }
966 if ( !$elem.length ) {
967 throw new Error( 'Widget not found: ' + id );
968 }
969 data = $elem.attr( 'data-ooui' );
970 if ( !data ) {
971 throw new Error( 'No infusion data found: ' + id );
972 }
973 try {
974 data = $.parseJSON( data );
975 } catch ( _ ) {
976 data = null;
977 }
978 if ( !( data && data._ ) ) {
979 throw new Error( 'No valid infusion data found: ' + id );
980 }
981 if ( data._ === 'Tag' ) {
982 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
983 return new OO.ui.Element( { $element: $elem } );
984 }
985 cls = OO.ui[data._];
986 if ( !cls ) {
987 throw new Error( 'Unknown widget type: ' + id );
988 }
989 $elem.data( 'ooui-infused', true ); // prevent loops
990 data.id = id; // implicit
991 data = OO.copy( data, null, function deserialize( value ) {
992 if ( OO.isPlainObject( value ) ) {
993 if ( value.tag ) {
994 return OO.ui.Element.static.unsafeInfuse( value.tag, false );
995 }
996 if ( value.html ) {
997 return new OO.ui.HtmlSnippet( value.html );
998 }
999 }
1000 } );
1001 // jscs:disable requireCapitalizedConstructors
1002 obj = new cls( data ); // rebuild widget
1003 // now replace old DOM with this new DOM.
1004 if ( top ) {
1005 $elem.replaceWith( obj.$element );
1006 }
1007 obj.$element.data( 'ooui-infused', obj );
1008 // set the 'data-ooui' attribute so we can identify infused widgets
1009 obj.$element.attr( 'data-ooui', '' );
1010 return obj;
1011 };
1012
1013 /**
1014 * Get a jQuery function within a specific document.
1015 *
1016 * @static
1017 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
1018 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
1019 * not in an iframe
1020 * @return {Function} Bound jQuery function
1021 */
1022 OO.ui.Element.static.getJQuery = function ( context, $iframe ) {
1023 function wrapper( selector ) {
1024 return $( selector, wrapper.context );
1025 }
1026
1027 wrapper.context = this.getDocument( context );
1028
1029 if ( $iframe ) {
1030 wrapper.$iframe = $iframe;
1031 }
1032
1033 return wrapper;
1034 };
1035
1036 /**
1037 * Get the document of an element.
1038 *
1039 * @static
1040 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
1041 * @return {HTMLDocument|null} Document object
1042 */
1043 OO.ui.Element.static.getDocument = function ( obj ) {
1044 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
1045 return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) ||
1046 // Empty jQuery selections might have a context
1047 obj.context ||
1048 // HTMLElement
1049 obj.ownerDocument ||
1050 // Window
1051 obj.document ||
1052 // HTMLDocument
1053 ( obj.nodeType === 9 && obj ) ||
1054 null;
1055 };
1056
1057 /**
1058 * Get the window of an element or document.
1059 *
1060 * @static
1061 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
1062 * @return {Window} Window object
1063 */
1064 OO.ui.Element.static.getWindow = function ( obj ) {
1065 var doc = this.getDocument( obj );
1066 return doc.parentWindow || doc.defaultView;
1067 };
1068
1069 /**
1070 * Get the direction of an element or document.
1071 *
1072 * @static
1073 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
1074 * @return {string} Text direction, either 'ltr' or 'rtl'
1075 */
1076 OO.ui.Element.static.getDir = function ( obj ) {
1077 var isDoc, isWin;
1078
1079 if ( obj instanceof jQuery ) {
1080 obj = obj[ 0 ];
1081 }
1082 isDoc = obj.nodeType === 9;
1083 isWin = obj.document !== undefined;
1084 if ( isDoc || isWin ) {
1085 if ( isWin ) {
1086 obj = obj.document;
1087 }
1088 obj = obj.body;
1089 }
1090 return $( obj ).css( 'direction' );
1091 };
1092
1093 /**
1094 * Get the offset between two frames.
1095 *
1096 * TODO: Make this function not use recursion.
1097 *
1098 * @static
1099 * @param {Window} from Window of the child frame
1100 * @param {Window} [to=window] Window of the parent frame
1101 * @param {Object} [offset] Offset to start with, used internally
1102 * @return {Object} Offset object, containing left and top properties
1103 */
1104 OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) {
1105 var i, len, frames, frame, rect;
1106
1107 if ( !to ) {
1108 to = window;
1109 }
1110 if ( !offset ) {
1111 offset = { top: 0, left: 0 };
1112 }
1113 if ( from.parent === from ) {
1114 return offset;
1115 }
1116
1117 // Get iframe element
1118 frames = from.parent.document.getElementsByTagName( 'iframe' );
1119 for ( i = 0, len = frames.length; i < len; i++ ) {
1120 if ( frames[ i ].contentWindow === from ) {
1121 frame = frames[ i ];
1122 break;
1123 }
1124 }
1125
1126 // Recursively accumulate offset values
1127 if ( frame ) {
1128 rect = frame.getBoundingClientRect();
1129 offset.left += rect.left;
1130 offset.top += rect.top;
1131 if ( from !== to ) {
1132 this.getFrameOffset( from.parent, offset );
1133 }
1134 }
1135 return offset;
1136 };
1137
1138 /**
1139 * Get the offset between two elements.
1140 *
1141 * The two elements may be in a different frame, but in that case the frame $element is in must
1142 * be contained in the frame $anchor is in.
1143 *
1144 * @static
1145 * @param {jQuery} $element Element whose position to get
1146 * @param {jQuery} $anchor Element to get $element's position relative to
1147 * @return {Object} Translated position coordinates, containing top and left properties
1148 */
1149 OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) {
1150 var iframe, iframePos,
1151 pos = $element.offset(),
1152 anchorPos = $anchor.offset(),
1153 elementDocument = this.getDocument( $element ),
1154 anchorDocument = this.getDocument( $anchor );
1155
1156 // If $element isn't in the same document as $anchor, traverse up
1157 while ( elementDocument !== anchorDocument ) {
1158 iframe = elementDocument.defaultView.frameElement;
1159 if ( !iframe ) {
1160 throw new Error( '$element frame is not contained in $anchor frame' );
1161 }
1162 iframePos = $( iframe ).offset();
1163 pos.left += iframePos.left;
1164 pos.top += iframePos.top;
1165 elementDocument = iframe.ownerDocument;
1166 }
1167 pos.left -= anchorPos.left;
1168 pos.top -= anchorPos.top;
1169 return pos;
1170 };
1171
1172 /**
1173 * Get element border sizes.
1174 *
1175 * @static
1176 * @param {HTMLElement} el Element to measure
1177 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1178 */
1179 OO.ui.Element.static.getBorders = function ( el ) {
1180 var doc = el.ownerDocument,
1181 win = doc.parentWindow || doc.defaultView,
1182 style = win && win.getComputedStyle ?
1183 win.getComputedStyle( el, null ) :
1184 el.currentStyle,
1185 $el = $( el ),
1186 top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0,
1187 left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0,
1188 bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0,
1189 right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0;
1190
1191 return {
1192 top: top,
1193 left: left,
1194 bottom: bottom,
1195 right: right
1196 };
1197 };
1198
1199 /**
1200 * Get dimensions of an element or window.
1201 *
1202 * @static
1203 * @param {HTMLElement|Window} el Element to measure
1204 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1205 */
1206 OO.ui.Element.static.getDimensions = function ( el ) {
1207 var $el, $win,
1208 doc = el.ownerDocument || el.document,
1209 win = doc.parentWindow || doc.defaultView;
1210
1211 if ( win === el || el === doc.documentElement ) {
1212 $win = $( win );
1213 return {
1214 borders: { top: 0, left: 0, bottom: 0, right: 0 },
1215 scroll: {
1216 top: $win.scrollTop(),
1217 left: $win.scrollLeft()
1218 },
1219 scrollbar: { right: 0, bottom: 0 },
1220 rect: {
1221 top: 0,
1222 left: 0,
1223 bottom: $win.innerHeight(),
1224 right: $win.innerWidth()
1225 }
1226 };
1227 } else {
1228 $el = $( el );
1229 return {
1230 borders: this.getBorders( el ),
1231 scroll: {
1232 top: $el.scrollTop(),
1233 left: $el.scrollLeft()
1234 },
1235 scrollbar: {
1236 right: $el.innerWidth() - el.clientWidth,
1237 bottom: $el.innerHeight() - el.clientHeight
1238 },
1239 rect: el.getBoundingClientRect()
1240 };
1241 }
1242 };
1243
1244 /**
1245 * Get scrollable object parent
1246 *
1247 * documentElement can't be used to get or set the scrollTop
1248 * property on Blink. Changing and testing its value lets us
1249 * use 'body' or 'documentElement' based on what is working.
1250 *
1251 * https://code.google.com/p/chromium/issues/detail?id=303131
1252 *
1253 * @static
1254 * @param {HTMLElement} el Element to find scrollable parent for
1255 * @return {HTMLElement} Scrollable parent
1256 */
1257 OO.ui.Element.static.getRootScrollableElement = function ( el ) {
1258 var scrollTop, body;
1259
1260 if ( OO.ui.scrollableElement === undefined ) {
1261 body = el.ownerDocument.body;
1262 scrollTop = body.scrollTop;
1263 body.scrollTop = 1;
1264
1265 if ( body.scrollTop === 1 ) {
1266 body.scrollTop = scrollTop;
1267 OO.ui.scrollableElement = 'body';
1268 } else {
1269 OO.ui.scrollableElement = 'documentElement';
1270 }
1271 }
1272
1273 return el.ownerDocument[ OO.ui.scrollableElement ];
1274 };
1275
1276 /**
1277 * Get closest scrollable container.
1278 *
1279 * Traverses up until either a scrollable element or the root is reached, in which case the window
1280 * will be returned.
1281 *
1282 * @static
1283 * @param {HTMLElement} el Element to find scrollable container for
1284 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1285 * @return {HTMLElement} Closest scrollable container
1286 */
1287 OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) {
1288 var i, val,
1289 props = [ 'overflow' ],
1290 $parent = $( el ).parent();
1291
1292 if ( dimension === 'x' || dimension === 'y' ) {
1293 props.push( 'overflow-' + dimension );
1294 }
1295
1296 while ( $parent.length ) {
1297 if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) {
1298 return $parent[ 0 ];
1299 }
1300 i = props.length;
1301 while ( i-- ) {
1302 val = $parent.css( props[ i ] );
1303 if ( val === 'auto' || val === 'scroll' ) {
1304 return $parent[ 0 ];
1305 }
1306 }
1307 $parent = $parent.parent();
1308 }
1309 return this.getDocument( el ).body;
1310 };
1311
1312 /**
1313 * Scroll element into view.
1314 *
1315 * @static
1316 * @param {HTMLElement} el Element to scroll into view
1317 * @param {Object} [config] Configuration options
1318 * @param {string} [config.duration] jQuery animation duration value
1319 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1320 * to scroll in both directions
1321 * @param {Function} [config.complete] Function to call when scrolling completes
1322 */
1323 OO.ui.Element.static.scrollIntoView = function ( el, config ) {
1324 // Configuration initialization
1325 config = config || {};
1326
1327 var rel, anim = {},
1328 callback = typeof config.complete === 'function' && config.complete,
1329 sc = this.getClosestScrollableContainer( el, config.direction ),
1330 $sc = $( sc ),
1331 eld = this.getDimensions( el ),
1332 scd = this.getDimensions( sc ),
1333 $win = $( this.getWindow( el ) );
1334
1335 // Compute the distances between the edges of el and the edges of the scroll viewport
1336 if ( $sc.is( 'html, body' ) ) {
1337 // If the scrollable container is the root, this is easy
1338 rel = {
1339 top: eld.rect.top,
1340 bottom: $win.innerHeight() - eld.rect.bottom,
1341 left: eld.rect.left,
1342 right: $win.innerWidth() - eld.rect.right
1343 };
1344 } else {
1345 // Otherwise, we have to subtract el's coordinates from sc's coordinates
1346 rel = {
1347 top: eld.rect.top - ( scd.rect.top + scd.borders.top ),
1348 bottom: scd.rect.bottom - scd.borders.bottom - scd.scrollbar.bottom - eld.rect.bottom,
1349 left: eld.rect.left - ( scd.rect.left + scd.borders.left ),
1350 right: scd.rect.right - scd.borders.right - scd.scrollbar.right - eld.rect.right
1351 };
1352 }
1353
1354 if ( !config.direction || config.direction === 'y' ) {
1355 if ( rel.top < 0 ) {
1356 anim.scrollTop = scd.scroll.top + rel.top;
1357 } else if ( rel.top > 0 && rel.bottom < 0 ) {
1358 anim.scrollTop = scd.scroll.top + Math.min( rel.top, -rel.bottom );
1359 }
1360 }
1361 if ( !config.direction || config.direction === 'x' ) {
1362 if ( rel.left < 0 ) {
1363 anim.scrollLeft = scd.scroll.left + rel.left;
1364 } else if ( rel.left > 0 && rel.right < 0 ) {
1365 anim.scrollLeft = scd.scroll.left + Math.min( rel.left, -rel.right );
1366 }
1367 }
1368 if ( !$.isEmptyObject( anim ) ) {
1369 $sc.stop( true ).animate( anim, config.duration || 'fast' );
1370 if ( callback ) {
1371 $sc.queue( function ( next ) {
1372 callback();
1373 next();
1374 } );
1375 }
1376 } else {
1377 if ( callback ) {
1378 callback();
1379 }
1380 }
1381 };
1382
1383 /**
1384 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1385 * and reserve space for them, because it probably doesn't.
1386 *
1387 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1388 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1389 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1390 * and then reattach (or show) them back.
1391 *
1392 * @static
1393 * @param {HTMLElement} el Element to reconsider the scrollbars on
1394 */
1395 OO.ui.Element.static.reconsiderScrollbars = function ( el ) {
1396 var i, len, nodes = [];
1397 // Detach all children
1398 while ( el.firstChild ) {
1399 nodes.push( el.firstChild );
1400 el.removeChild( el.firstChild );
1401 }
1402 // Force reflow
1403 void el.offsetHeight;
1404 // Reattach all children
1405 for ( i = 0, len = nodes.length; i < len; i++ ) {
1406 el.appendChild( nodes[ i ] );
1407 }
1408 };
1409
1410 /* Methods */
1411
1412 /**
1413 * Toggle visibility of an element.
1414 *
1415 * @param {boolean} [show] Make element visible, omit to toggle visibility
1416 * @fires visible
1417 * @chainable
1418 */
1419 OO.ui.Element.prototype.toggle = function ( show ) {
1420 show = show === undefined ? !this.visible : !!show;
1421
1422 if ( show !== this.isVisible() ) {
1423 this.visible = show;
1424 this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible );
1425 this.emit( 'toggle', show );
1426 }
1427
1428 return this;
1429 };
1430
1431 /**
1432 * Check if element is visible.
1433 *
1434 * @return {boolean} element is visible
1435 */
1436 OO.ui.Element.prototype.isVisible = function () {
1437 return this.visible;
1438 };
1439
1440 /**
1441 * Get element data.
1442 *
1443 * @return {Mixed} Element data
1444 */
1445 OO.ui.Element.prototype.getData = function () {
1446 return this.data;
1447 };
1448
1449 /**
1450 * Set element data.
1451 *
1452 * @param {Mixed} Element data
1453 * @chainable
1454 */
1455 OO.ui.Element.prototype.setData = function ( data ) {
1456 this.data = data;
1457 return this;
1458 };
1459
1460 /**
1461 * Check if element supports one or more methods.
1462 *
1463 * @param {string|string[]} methods Method or list of methods to check
1464 * @return {boolean} All methods are supported
1465 */
1466 OO.ui.Element.prototype.supports = function ( methods ) {
1467 var i, len,
1468 support = 0;
1469
1470 methods = Array.isArray( methods ) ? methods : [ methods ];
1471 for ( i = 0, len = methods.length; i < len; i++ ) {
1472 if ( $.isFunction( this[ methods[ i ] ] ) ) {
1473 support++;
1474 }
1475 }
1476
1477 return methods.length === support;
1478 };
1479
1480 /**
1481 * Update the theme-provided classes.
1482 *
1483 * @localdoc This is called in element mixins and widget classes any time state changes.
1484 * Updating is debounced, minimizing overhead of changing multiple attributes and
1485 * guaranteeing that theme updates do not occur within an element's constructor
1486 */
1487 OO.ui.Element.prototype.updateThemeClasses = function () {
1488 if ( !this.updateThemeClassesPending ) {
1489 this.updateThemeClassesPending = true;
1490 setTimeout( this.debouncedUpdateThemeClassesHandler );
1491 }
1492 };
1493
1494 /**
1495 * @private
1496 */
1497 OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () {
1498 OO.ui.theme.updateElementClasses( this );
1499 this.updateThemeClassesPending = false;
1500 };
1501
1502 /**
1503 * Get the HTML tag name.
1504 *
1505 * Override this method to base the result on instance information.
1506 *
1507 * @return {string} HTML tag name
1508 */
1509 OO.ui.Element.prototype.getTagName = function () {
1510 return this.constructor.static.tagName;
1511 };
1512
1513 /**
1514 * Check if the element is attached to the DOM
1515 * @return {boolean} The element is attached to the DOM
1516 */
1517 OO.ui.Element.prototype.isElementAttached = function () {
1518 return $.contains( this.getElementDocument(), this.$element[ 0 ] );
1519 };
1520
1521 /**
1522 * Get the DOM document.
1523 *
1524 * @return {HTMLDocument} Document object
1525 */
1526 OO.ui.Element.prototype.getElementDocument = function () {
1527 // Don't cache this in other ways either because subclasses could can change this.$element
1528 return OO.ui.Element.static.getDocument( this.$element );
1529 };
1530
1531 /**
1532 * Get the DOM window.
1533 *
1534 * @return {Window} Window object
1535 */
1536 OO.ui.Element.prototype.getElementWindow = function () {
1537 return OO.ui.Element.static.getWindow( this.$element );
1538 };
1539
1540 /**
1541 * Get closest scrollable container.
1542 */
1543 OO.ui.Element.prototype.getClosestScrollableElementContainer = function () {
1544 return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] );
1545 };
1546
1547 /**
1548 * Get group element is in.
1549 *
1550 * @return {OO.ui.GroupElement|null} Group element, null if none
1551 */
1552 OO.ui.Element.prototype.getElementGroup = function () {
1553 return this.elementGroup;
1554 };
1555
1556 /**
1557 * Set group element is in.
1558 *
1559 * @param {OO.ui.GroupElement|null} group Group element, null if none
1560 * @chainable
1561 */
1562 OO.ui.Element.prototype.setElementGroup = function ( group ) {
1563 this.elementGroup = group;
1564 return this;
1565 };
1566
1567 /**
1568 * Scroll element into view.
1569 *
1570 * @param {Object} [config] Configuration options
1571 */
1572 OO.ui.Element.prototype.scrollElementIntoView = function ( config ) {
1573 return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config );
1574 };
1575
1576 /**
1577 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1578 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1579 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1580 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1581 * and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1582 *
1583 * @abstract
1584 * @class
1585 * @extends OO.ui.Element
1586 * @mixins OO.EventEmitter
1587 *
1588 * @constructor
1589 * @param {Object} [config] Configuration options
1590 */
1591 OO.ui.Layout = function OoUiLayout( config ) {
1592 // Configuration initialization
1593 config = config || {};
1594
1595 // Parent constructor
1596 OO.ui.Layout.super.call( this, config );
1597
1598 // Mixin constructors
1599 OO.EventEmitter.call( this );
1600
1601 // Initialization
1602 this.$element.addClass( 'oo-ui-layout' );
1603 };
1604
1605 /* Setup */
1606
1607 OO.inheritClass( OO.ui.Layout, OO.ui.Element );
1608 OO.mixinClass( OO.ui.Layout, OO.EventEmitter );
1609
1610 /**
1611 * Widgets are compositions of one or more OOjs UI elements that users can both view
1612 * and interact with. All widgets can be configured and modified via a standard API,
1613 * and their state can change dynamically according to a model.
1614 *
1615 * @abstract
1616 * @class
1617 * @extends OO.ui.Element
1618 * @mixins OO.EventEmitter
1619 *
1620 * @constructor
1621 * @param {Object} [config] Configuration options
1622 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1623 * appearance reflects this state.
1624 */
1625 OO.ui.Widget = function OoUiWidget( config ) {
1626 // Initialize config
1627 config = $.extend( { disabled: false }, config );
1628
1629 // Parent constructor
1630 OO.ui.Widget.super.call( this, config );
1631
1632 // Mixin constructors
1633 OO.EventEmitter.call( this );
1634
1635 // Properties
1636 this.disabled = null;
1637 this.wasDisabled = null;
1638
1639 // Initialization
1640 this.$element.addClass( 'oo-ui-widget' );
1641 this.setDisabled( !!config.disabled );
1642 };
1643
1644 /* Setup */
1645
1646 OO.inheritClass( OO.ui.Widget, OO.ui.Element );
1647 OO.mixinClass( OO.ui.Widget, OO.EventEmitter );
1648
1649 /* Events */
1650
1651 /**
1652 * @event disable
1653 *
1654 * A 'disable' event is emitted when a widget is disabled.
1655 *
1656 * @param {boolean} disabled Widget is disabled
1657 */
1658
1659 /**
1660 * @event toggle
1661 *
1662 * A 'toggle' event is emitted when the visibility of the widget changes.
1663 *
1664 * @param {boolean} visible Widget is visible
1665 */
1666
1667 /* Methods */
1668
1669 /**
1670 * Check if the widget is disabled.
1671 *
1672 * @return {boolean} Widget is disabled
1673 */
1674 OO.ui.Widget.prototype.isDisabled = function () {
1675 return this.disabled;
1676 };
1677
1678 /**
1679 * Set the 'disabled' state of the widget.
1680 *
1681 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1682 *
1683 * @param {boolean} disabled Disable widget
1684 * @chainable
1685 */
1686 OO.ui.Widget.prototype.setDisabled = function ( disabled ) {
1687 var isDisabled;
1688
1689 this.disabled = !!disabled;
1690 isDisabled = this.isDisabled();
1691 if ( isDisabled !== this.wasDisabled ) {
1692 this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled );
1693 this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled );
1694 this.$element.attr( 'aria-disabled', isDisabled.toString() );
1695 this.emit( 'disable', isDisabled );
1696 this.updateThemeClasses();
1697 }
1698 this.wasDisabled = isDisabled;
1699
1700 return this;
1701 };
1702
1703 /**
1704 * Update the disabled state, in case of changes in parent widget.
1705 *
1706 * @chainable
1707 */
1708 OO.ui.Widget.prototype.updateDisabled = function () {
1709 this.setDisabled( this.disabled );
1710 return this;
1711 };
1712
1713 /**
1714 * A window is a container for elements that are in a child frame. They are used with
1715 * a window manager (OO.ui.WindowManager), which is used to open and close the window and control
1716 * its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
1717 * ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
1718 * the window manager will choose a sensible fallback.
1719 *
1720 * The lifecycle of a window has three primary stages (opening, opened, and closing) in which
1721 * different processes are executed:
1722 *
1723 * **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
1724 * openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
1725 * the window.
1726 *
1727 * - {@link #getSetupProcess} method is called and its result executed
1728 * - {@link #getReadyProcess} method is called and its result executed
1729 *
1730 * **opened**: The window is now open
1731 *
1732 * **closing**: The closing stage begins when the window manager's
1733 * {@link OO.ui.WindowManager#closeWindow closeWindow}
1734 * or the window's {@link #close} methods are used, and the window manager begins to close the window.
1735 *
1736 * - {@link #getHoldProcess} method is called and its result executed
1737 * - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
1738 *
1739 * Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
1740 * by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
1741 * methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
1742 * processing can complete. Always assume window processes are executed asynchronously.
1743 *
1744 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
1745 *
1746 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
1747 *
1748 * @abstract
1749 * @class
1750 * @extends OO.ui.Element
1751 * @mixins OO.EventEmitter
1752 *
1753 * @constructor
1754 * @param {Object} [config] Configuration options
1755 * @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
1756 * `full`. If omitted, the value of the {@link #static-size static size} property will be used.
1757 */
1758 OO.ui.Window = function OoUiWindow( config ) {
1759 // Configuration initialization
1760 config = config || {};
1761
1762 // Parent constructor
1763 OO.ui.Window.super.call( this, config );
1764
1765 // Mixin constructors
1766 OO.EventEmitter.call( this );
1767
1768 // Properties
1769 this.manager = null;
1770 this.size = config.size || this.constructor.static.size;
1771 this.$frame = $( '<div>' );
1772 this.$overlay = $( '<div>' );
1773 this.$content = $( '<div>' );
1774
1775 // Initialization
1776 this.$overlay.addClass( 'oo-ui-window-overlay' );
1777 this.$content
1778 .addClass( 'oo-ui-window-content' )
1779 .attr( 'tabIndex', 0 );
1780 this.$frame
1781 .addClass( 'oo-ui-window-frame' )
1782 .append( this.$content );
1783
1784 this.$element
1785 .addClass( 'oo-ui-window' )
1786 .append( this.$frame, this.$overlay );
1787
1788 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
1789 // that reference properties not initialized at that time of parent class construction
1790 // TODO: Find a better way to handle post-constructor setup
1791 this.visible = false;
1792 this.$element.addClass( 'oo-ui-element-hidden' );
1793 };
1794
1795 /* Setup */
1796
1797 OO.inheritClass( OO.ui.Window, OO.ui.Element );
1798 OO.mixinClass( OO.ui.Window, OO.EventEmitter );
1799
1800 /* Static Properties */
1801
1802 /**
1803 * Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
1804 *
1805 * The static size is used if no #size is configured during construction.
1806 *
1807 * @static
1808 * @inheritable
1809 * @property {string}
1810 */
1811 OO.ui.Window.static.size = 'medium';
1812
1813 /* Methods */
1814
1815 /**
1816 * Handle mouse down events.
1817 *
1818 * @private
1819 * @param {jQuery.Event} e Mouse down event
1820 */
1821 OO.ui.Window.prototype.onMouseDown = function ( e ) {
1822 // Prevent clicking on the click-block from stealing focus
1823 if ( e.target === this.$element[ 0 ] ) {
1824 return false;
1825 }
1826 };
1827
1828 /**
1829 * Check if the window has been initialized.
1830 *
1831 * Initialization occurs when a window is added to a manager.
1832 *
1833 * @return {boolean} Window has been initialized
1834 */
1835 OO.ui.Window.prototype.isInitialized = function () {
1836 return !!this.manager;
1837 };
1838
1839 /**
1840 * Check if the window is visible.
1841 *
1842 * @return {boolean} Window is visible
1843 */
1844 OO.ui.Window.prototype.isVisible = function () {
1845 return this.visible;
1846 };
1847
1848 /**
1849 * Check if the window is opening.
1850 *
1851 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
1852 * method.
1853 *
1854 * @return {boolean} Window is opening
1855 */
1856 OO.ui.Window.prototype.isOpening = function () {
1857 return this.manager.isOpening( this );
1858 };
1859
1860 /**
1861 * Check if the window is closing.
1862 *
1863 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
1864 *
1865 * @return {boolean} Window is closing
1866 */
1867 OO.ui.Window.prototype.isClosing = function () {
1868 return this.manager.isClosing( this );
1869 };
1870
1871 /**
1872 * Check if the window is opened.
1873 *
1874 * This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
1875 *
1876 * @return {boolean} Window is opened
1877 */
1878 OO.ui.Window.prototype.isOpened = function () {
1879 return this.manager.isOpened( this );
1880 };
1881
1882 /**
1883 * Get the window manager.
1884 *
1885 * All windows must be attached to a window manager, which is used to open
1886 * and close the window and control its presentation.
1887 *
1888 * @return {OO.ui.WindowManager} Manager of window
1889 */
1890 OO.ui.Window.prototype.getManager = function () {
1891 return this.manager;
1892 };
1893
1894 /**
1895 * Get the symbolic name of the window size (e.g., `small` or `medium`).
1896 *
1897 * @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
1898 */
1899 OO.ui.Window.prototype.getSize = function () {
1900 return this.size;
1901 };
1902
1903 /**
1904 * Disable transitions on window's frame for the duration of the callback function, then enable them
1905 * back.
1906 *
1907 * @private
1908 * @param {Function} callback Function to call while transitions are disabled
1909 */
1910 OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
1911 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1912 // Disable transitions first, otherwise we'll get values from when the window was animating.
1913 var oldTransition,
1914 styleObj = this.$frame[ 0 ].style;
1915 oldTransition = styleObj.transition || styleObj.OTransition || styleObj.MsTransition ||
1916 styleObj.MozTransition || styleObj.WebkitTransition;
1917 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1918 styleObj.MozTransition = styleObj.WebkitTransition = 'none';
1919 callback();
1920 // Force reflow to make sure the style changes done inside callback really are not transitioned
1921 this.$frame.height();
1922 styleObj.transition = styleObj.OTransition = styleObj.MsTransition =
1923 styleObj.MozTransition = styleObj.WebkitTransition = oldTransition;
1924 };
1925
1926 /**
1927 * Get the height of the full window contents (i.e., the window head, body and foot together).
1928 *
1929 * What consistitutes the head, body, and foot varies depending on the window type.
1930 * A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
1931 * and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
1932 * and special actions in the head, and dialog content in the body.
1933 *
1934 * To get just the height of the dialog body, use the #getBodyHeight method.
1935 *
1936 * @return {number} The height of the window contents (the dialog head, body and foot) in pixels
1937 */
1938 OO.ui.Window.prototype.getContentHeight = function () {
1939 var bodyHeight,
1940 win = this,
1941 bodyStyleObj = this.$body[ 0 ].style,
1942 frameStyleObj = this.$frame[ 0 ].style;
1943
1944 // Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
1945 // Disable transitions first, otherwise we'll get values from when the window was animating.
1946 this.withoutSizeTransitions( function () {
1947 var oldHeight = frameStyleObj.height,
1948 oldPosition = bodyStyleObj.position;
1949 frameStyleObj.height = '1px';
1950 // Force body to resize to new width
1951 bodyStyleObj.position = 'relative';
1952 bodyHeight = win.getBodyHeight();
1953 frameStyleObj.height = oldHeight;
1954 bodyStyleObj.position = oldPosition;
1955 } );
1956
1957 return (
1958 // Add buffer for border
1959 ( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
1960 // Use combined heights of children
1961 ( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
1962 );
1963 };
1964
1965 /**
1966 * Get the height of the window body.
1967 *
1968 * To get the height of the full window contents (the window body, head, and foot together),
1969 * use #getContentHeight.
1970 *
1971 * When this function is called, the window will temporarily have been resized
1972 * to height=1px, so .scrollHeight measurements can be taken accurately.
1973 *
1974 * @return {number} Height of the window body in pixels
1975 */
1976 OO.ui.Window.prototype.getBodyHeight = function () {
1977 return this.$body[ 0 ].scrollHeight;
1978 };
1979
1980 /**
1981 * Get the directionality of the frame (right-to-left or left-to-right).
1982 *
1983 * @return {string} Directionality: `'ltr'` or `'rtl'`
1984 */
1985 OO.ui.Window.prototype.getDir = function () {
1986 return this.dir;
1987 };
1988
1989 /**
1990 * Get the 'setup' process.
1991 *
1992 * The setup process is used to set up a window for use in a particular context,
1993 * based on the `data` argument. This method is called during the opening phase of the window’s
1994 * lifecycle.
1995 *
1996 * Override this method to add additional steps to the ‘setup’ process the parent method provides
1997 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
1998 * of OO.ui.Process.
1999 *
2000 * To add window content that persists between openings, you may wish to use the #initialize method
2001 * instead.
2002 *
2003 * @abstract
2004 * @param {Object} [data] Window opening data
2005 * @return {OO.ui.Process} Setup process
2006 */
2007 OO.ui.Window.prototype.getSetupProcess = function () {
2008 return new OO.ui.Process();
2009 };
2010
2011 /**
2012 * Get the ‘ready’ process.
2013 *
2014 * The ready process is used to ready a window for use in a particular
2015 * context, based on the `data` argument. This method is called during the opening phase of
2016 * the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
2017 *
2018 * Override this method to add additional steps to the ‘ready’ process the parent method
2019 * provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
2020 * methods of OO.ui.Process.
2021 *
2022 * @abstract
2023 * @param {Object} [data] Window opening data
2024 * @return {OO.ui.Process} Ready process
2025 */
2026 OO.ui.Window.prototype.getReadyProcess = function () {
2027 return new OO.ui.Process();
2028 };
2029
2030 /**
2031 * Get the 'hold' process.
2032 *
2033 * The hold proccess is used to keep a window from being used in a particular context,
2034 * based on the `data` argument. This method is called during the closing phase of the window’s
2035 * lifecycle.
2036 *
2037 * Override this method to add additional steps to the 'hold' process the parent method provides
2038 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2039 * of OO.ui.Process.
2040 *
2041 * @abstract
2042 * @param {Object} [data] Window closing data
2043 * @return {OO.ui.Process} Hold process
2044 */
2045 OO.ui.Window.prototype.getHoldProcess = function () {
2046 return new OO.ui.Process();
2047 };
2048
2049 /**
2050 * Get the ‘teardown’ process.
2051 *
2052 * The teardown process is used to teardown a window after use. During teardown,
2053 * user interactions within the window are conveyed and the window is closed, based on the `data`
2054 * argument. This method is called during the closing phase of the window’s lifecycle.
2055 *
2056 * Override this method to add additional steps to the ‘teardown’ process the parent method provides
2057 * using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
2058 * of OO.ui.Process.
2059 *
2060 * @abstract
2061 * @param {Object} [data] Window closing data
2062 * @return {OO.ui.Process} Teardown process
2063 */
2064 OO.ui.Window.prototype.getTeardownProcess = function () {
2065 return new OO.ui.Process();
2066 };
2067
2068 /**
2069 * Set the window manager.
2070 *
2071 * This will cause the window to initialize. Calling it more than once will cause an error.
2072 *
2073 * @param {OO.ui.WindowManager} manager Manager for this window
2074 * @throws {Error} An error is thrown if the method is called more than once
2075 * @chainable
2076 */
2077 OO.ui.Window.prototype.setManager = function ( manager ) {
2078 if ( this.manager ) {
2079 throw new Error( 'Cannot set window manager, window already has a manager' );
2080 }
2081
2082 this.manager = manager;
2083 this.initialize();
2084
2085 return this;
2086 };
2087
2088 /**
2089 * Set the window size by symbolic name (e.g., 'small' or 'medium')
2090 *
2091 * @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
2092 * `full`
2093 * @chainable
2094 */
2095 OO.ui.Window.prototype.setSize = function ( size ) {
2096 this.size = size;
2097 this.updateSize();
2098 return this;
2099 };
2100
2101 /**
2102 * Update the window size.
2103 *
2104 * @throws {Error} An error is thrown if the window is not attached to a window manager
2105 * @chainable
2106 */
2107 OO.ui.Window.prototype.updateSize = function () {
2108 if ( !this.manager ) {
2109 throw new Error( 'Cannot update window size, must be attached to a manager' );
2110 }
2111
2112 this.manager.updateWindowSize( this );
2113
2114 return this;
2115 };
2116
2117 /**
2118 * Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
2119 * when the window is opening. In general, setDimensions should not be called directly.
2120 *
2121 * To set the size of the window, use the #setSize method.
2122 *
2123 * @param {Object} dim CSS dimension properties
2124 * @param {string|number} [dim.width] Width
2125 * @param {string|number} [dim.minWidth] Minimum width
2126 * @param {string|number} [dim.maxWidth] Maximum width
2127 * @param {string|number} [dim.width] Height, omit to set based on height of contents
2128 * @param {string|number} [dim.minWidth] Minimum height
2129 * @param {string|number} [dim.maxWidth] Maximum height
2130 * @chainable
2131 */
2132 OO.ui.Window.prototype.setDimensions = function ( dim ) {
2133 var height,
2134 win = this,
2135 styleObj = this.$frame[ 0 ].style;
2136
2137 // Calculate the height we need to set using the correct width
2138 if ( dim.height === undefined ) {
2139 this.withoutSizeTransitions( function () {
2140 var oldWidth = styleObj.width;
2141 win.$frame.css( 'width', dim.width || '' );
2142 height = win.getContentHeight();
2143 styleObj.width = oldWidth;
2144 } );
2145 } else {
2146 height = dim.height;
2147 }
2148
2149 this.$frame.css( {
2150 width: dim.width || '',
2151 minWidth: dim.minWidth || '',
2152 maxWidth: dim.maxWidth || '',
2153 height: height || '',
2154 minHeight: dim.minHeight || '',
2155 maxHeight: dim.maxHeight || ''
2156 } );
2157
2158 return this;
2159 };
2160
2161 /**
2162 * Initialize window contents.
2163 *
2164 * Before the window is opened for the first time, #initialize is called so that content that
2165 * persists between openings can be added to the window.
2166 *
2167 * To set up a window with new content each time the window opens, use #getSetupProcess.
2168 *
2169 * @throws {Error} An error is thrown if the window is not attached to a window manager
2170 * @chainable
2171 */
2172 OO.ui.Window.prototype.initialize = function () {
2173 if ( !this.manager ) {
2174 throw new Error( 'Cannot initialize window, must be attached to a manager' );
2175 }
2176
2177 // Properties
2178 this.$head = $( '<div>' );
2179 this.$body = $( '<div>' );
2180 this.$foot = $( '<div>' );
2181 this.dir = OO.ui.Element.static.getDir( this.$content ) || 'ltr';
2182 this.$document = $( this.getElementDocument() );
2183
2184 // Events
2185 this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
2186
2187 // Initialization
2188 this.$head.addClass( 'oo-ui-window-head' );
2189 this.$body.addClass( 'oo-ui-window-body' );
2190 this.$foot.addClass( 'oo-ui-window-foot' );
2191 this.$content.append( this.$head, this.$body, this.$foot );
2192
2193 return this;
2194 };
2195
2196 /**
2197 * Open the window.
2198 *
2199 * This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
2200 * method, which returns a promise resolved when the window is done opening.
2201 *
2202 * To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
2203 *
2204 * @param {Object} [data] Window opening data
2205 * @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
2206 * if the window fails to open. When the promise is resolved successfully, the first argument of the
2207 * value is a new promise, which is resolved when the window begins closing.
2208 * @throws {Error} An error is thrown if the window is not attached to a window manager
2209 */
2210 OO.ui.Window.prototype.open = function ( data ) {
2211 if ( !this.manager ) {
2212 throw new Error( 'Cannot open window, must be attached to a manager' );
2213 }
2214
2215 return this.manager.openWindow( this, data );
2216 };
2217
2218 /**
2219 * Close the window.
2220 *
2221 * This method is a wrapper around a call to the window
2222 * manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
2223 * which returns a closing promise resolved when the window is done closing.
2224 *
2225 * The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
2226 * phase of the window’s lifecycle and can be used to specify closing behavior each time
2227 * the window closes.
2228 *
2229 * @param {Object} [data] Window closing data
2230 * @return {jQuery.Promise} Promise resolved when window is closed
2231 * @throws {Error} An error is thrown if the window is not attached to a window manager
2232 */
2233 OO.ui.Window.prototype.close = function ( data ) {
2234 if ( !this.manager ) {
2235 throw new Error( 'Cannot close window, must be attached to a manager' );
2236 }
2237
2238 return this.manager.closeWindow( this, data );
2239 };
2240
2241 /**
2242 * Setup window.
2243 *
2244 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2245 * by other systems.
2246 *
2247 * @param {Object} [data] Window opening data
2248 * @return {jQuery.Promise} Promise resolved when window is setup
2249 */
2250 OO.ui.Window.prototype.setup = function ( data ) {
2251 var win = this,
2252 deferred = $.Deferred();
2253
2254 this.toggle( true );
2255
2256 this.getSetupProcess( data ).execute().done( function () {
2257 // Force redraw by asking the browser to measure the elements' widths
2258 win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2259 win.$content.addClass( 'oo-ui-window-content-setup' ).width();
2260 deferred.resolve();
2261 } );
2262
2263 return deferred.promise();
2264 };
2265
2266 /**
2267 * Ready window.
2268 *
2269 * This is called by OO.ui.WindowManager during window opening, and should not be called directly
2270 * by other systems.
2271 *
2272 * @param {Object} [data] Window opening data
2273 * @return {jQuery.Promise} Promise resolved when window is ready
2274 */
2275 OO.ui.Window.prototype.ready = function ( data ) {
2276 var win = this,
2277 deferred = $.Deferred();
2278
2279 this.$content.focus();
2280 this.getReadyProcess( data ).execute().done( function () {
2281 // Force redraw by asking the browser to measure the elements' widths
2282 win.$element.addClass( 'oo-ui-window-ready' ).width();
2283 win.$content.addClass( 'oo-ui-window-content-ready' ).width();
2284 deferred.resolve();
2285 } );
2286
2287 return deferred.promise();
2288 };
2289
2290 /**
2291 * Hold window.
2292 *
2293 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2294 * by other systems.
2295 *
2296 * @param {Object} [data] Window closing data
2297 * @return {jQuery.Promise} Promise resolved when window is held
2298 */
2299 OO.ui.Window.prototype.hold = function ( data ) {
2300 var win = this,
2301 deferred = $.Deferred();
2302
2303 this.getHoldProcess( data ).execute().done( function () {
2304 // Get the focused element within the window's content
2305 var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
2306
2307 // Blur the focused element
2308 if ( $focus.length ) {
2309 $focus[ 0 ].blur();
2310 }
2311
2312 // Force redraw by asking the browser to measure the elements' widths
2313 win.$element.removeClass( 'oo-ui-window-ready' ).width();
2314 win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
2315 deferred.resolve();
2316 } );
2317
2318 return deferred.promise();
2319 };
2320
2321 /**
2322 * Teardown window.
2323 *
2324 * This is called by OO.ui.WindowManager during window closing, and should not be called directly
2325 * by other systems.
2326 *
2327 * @param {Object} [data] Window closing data
2328 * @return {jQuery.Promise} Promise resolved when window is torn down
2329 */
2330 OO.ui.Window.prototype.teardown = function ( data ) {
2331 var win = this;
2332
2333 return this.getTeardownProcess( data ).execute()
2334 .done( function () {
2335 // Force redraw by asking the browser to measure the elements' widths
2336 win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
2337 win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
2338 win.toggle( false );
2339 } );
2340 };
2341
2342 /**
2343 * The Dialog class serves as the base class for the other types of dialogs.
2344 * Unless extended to include controls, the rendered dialog box is a simple window
2345 * that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
2346 * which opens, closes, and controls the presentation of the window. See the
2347 * [OOjs UI documentation on MediaWiki] [1] for more information.
2348 *
2349 * @example
2350 * // A simple dialog window.
2351 * function MyDialog( config ) {
2352 * MyDialog.super.call( this, config );
2353 * }
2354 * OO.inheritClass( MyDialog, OO.ui.Dialog );
2355 * MyDialog.prototype.initialize = function () {
2356 * MyDialog.super.prototype.initialize.call( this );
2357 * this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
2358 * this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
2359 * this.$body.append( this.content.$element );
2360 * };
2361 * MyDialog.prototype.getBodyHeight = function () {
2362 * return this.content.$element.outerHeight( true );
2363 * };
2364 * var myDialog = new MyDialog( {
2365 * size: 'medium'
2366 * } );
2367 * // Create and append a window manager, which opens and closes the window.
2368 * var windowManager = new OO.ui.WindowManager();
2369 * $( 'body' ).append( windowManager.$element );
2370 * windowManager.addWindows( [ myDialog ] );
2371 * // Open the window!
2372 * windowManager.openWindow( myDialog );
2373 *
2374 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
2375 *
2376 * @abstract
2377 * @class
2378 * @extends OO.ui.Window
2379 * @mixins OO.ui.PendingElement
2380 *
2381 * @constructor
2382 * @param {Object} [config] Configuration options
2383 */
2384 OO.ui.Dialog = function OoUiDialog( config ) {
2385 // Parent constructor
2386 OO.ui.Dialog.super.call( this, config );
2387
2388 // Mixin constructors
2389 OO.ui.PendingElement.call( this );
2390
2391 // Properties
2392 this.actions = new OO.ui.ActionSet();
2393 this.attachedActions = [];
2394 this.currentAction = null;
2395 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
2396
2397 // Events
2398 this.actions.connect( this, {
2399 click: 'onActionClick',
2400 resize: 'onActionResize',
2401 change: 'onActionsChange'
2402 } );
2403
2404 // Initialization
2405 this.$element
2406 .addClass( 'oo-ui-dialog' )
2407 .attr( 'role', 'dialog' );
2408 };
2409
2410 /* Setup */
2411
2412 OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
2413 OO.mixinClass( OO.ui.Dialog, OO.ui.PendingElement );
2414
2415 /* Static Properties */
2416
2417 /**
2418 * Symbolic name of dialog.
2419 *
2420 * The dialog class must have a symbolic name in order to be registered with OO.Factory.
2421 * Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
2422 *
2423 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2424 *
2425 * @abstract
2426 * @static
2427 * @inheritable
2428 * @property {string}
2429 */
2430 OO.ui.Dialog.static.name = '';
2431
2432 /**
2433 * The dialog title.
2434 *
2435 * The title can be specified as a plaintext string, a {@link OO.ui.LabelElement Label} node, or a function
2436 * that will produce a Label node or string. The title can also be specified with data passed to the
2437 * constructor (see #getSetupProcess). In this case, the static value will be overriden.
2438 *
2439 * @abstract
2440 * @static
2441 * @inheritable
2442 * @property {jQuery|string|Function}
2443 */
2444 OO.ui.Dialog.static.title = '';
2445
2446 /**
2447 * An array of configured {@link OO.ui.ActionWidget action widgets}.
2448 *
2449 * Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
2450 * value will be overriden.
2451 *
2452 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
2453 *
2454 * @static
2455 * @inheritable
2456 * @property {Object[]}
2457 */
2458 OO.ui.Dialog.static.actions = [];
2459
2460 /**
2461 * Close the dialog when the 'Esc' key is pressed.
2462 *
2463 * @static
2464 * @abstract
2465 * @inheritable
2466 * @property {boolean}
2467 */
2468 OO.ui.Dialog.static.escapable = true;
2469
2470 /* Methods */
2471
2472 /**
2473 * Handle frame document key down events.
2474 *
2475 * @private
2476 * @param {jQuery.Event} e Key down event
2477 */
2478 OO.ui.Dialog.prototype.onDocumentKeyDown = function ( e ) {
2479 if ( e.which === OO.ui.Keys.ESCAPE ) {
2480 this.close();
2481 e.preventDefault();
2482 e.stopPropagation();
2483 }
2484 };
2485
2486 /**
2487 * Handle action resized events.
2488 *
2489 * @private
2490 * @param {OO.ui.ActionWidget} action Action that was resized
2491 */
2492 OO.ui.Dialog.prototype.onActionResize = function () {
2493 // Override in subclass
2494 };
2495
2496 /**
2497 * Handle action click events.
2498 *
2499 * @private
2500 * @param {OO.ui.ActionWidget} action Action that was clicked
2501 */
2502 OO.ui.Dialog.prototype.onActionClick = function ( action ) {
2503 if ( !this.isPending() ) {
2504 this.executeAction( action.getAction() );
2505 }
2506 };
2507
2508 /**
2509 * Handle actions change event.
2510 *
2511 * @private
2512 */
2513 OO.ui.Dialog.prototype.onActionsChange = function () {
2514 this.detachActions();
2515 if ( !this.isClosing() ) {
2516 this.attachActions();
2517 }
2518 };
2519
2520 /**
2521 * Get the set of actions used by the dialog.
2522 *
2523 * @return {OO.ui.ActionSet}
2524 */
2525 OO.ui.Dialog.prototype.getActions = function () {
2526 return this.actions;
2527 };
2528
2529 /**
2530 * Get a process for taking action.
2531 *
2532 * When you override this method, you can create a new OO.ui.Process and return it, or add additional
2533 * accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
2534 * and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
2535 *
2536 * @abstract
2537 * @param {string} [action] Symbolic name of action
2538 * @return {OO.ui.Process} Action process
2539 */
2540 OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
2541 return new OO.ui.Process()
2542 .next( function () {
2543 if ( !action ) {
2544 // An empty action always closes the dialog without data, which should always be
2545 // safe and make no changes
2546 this.close();
2547 }
2548 }, this );
2549 };
2550
2551 /**
2552 * @inheritdoc
2553 *
2554 * @param {Object} [data] Dialog opening data
2555 * @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
2556 * the {@link #static-title static title}
2557 * @param {Object[]} [data.actions] List of configuration options for each
2558 * {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
2559 */
2560 OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
2561 data = data || {};
2562
2563 // Parent method
2564 return OO.ui.Dialog.super.prototype.getSetupProcess.call( this, data )
2565 .next( function () {
2566 var config = this.constructor.static,
2567 actions = data.actions !== undefined ? data.actions : config.actions;
2568
2569 this.title.setLabel(
2570 data.title !== undefined ? data.title : this.constructor.static.title
2571 );
2572 this.actions.add( this.getActionWidgets( actions ) );
2573
2574 if ( this.constructor.static.escapable ) {
2575 this.$document.on( 'keydown', this.onDocumentKeyDownHandler );
2576 }
2577 }, this );
2578 };
2579
2580 /**
2581 * @inheritdoc
2582 */
2583 OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
2584 // Parent method
2585 return OO.ui.Dialog.super.prototype.getTeardownProcess.call( this, data )
2586 .first( function () {
2587 if ( this.constructor.static.escapable ) {
2588 this.$document.off( 'keydown', this.onDocumentKeyDownHandler );
2589 }
2590
2591 this.actions.clear();
2592 this.currentAction = null;
2593 }, this );
2594 };
2595
2596 /**
2597 * @inheritdoc
2598 */
2599 OO.ui.Dialog.prototype.initialize = function () {
2600 // Parent method
2601 OO.ui.Dialog.super.prototype.initialize.call( this );
2602
2603 // Properties
2604 this.title = new OO.ui.LabelWidget();
2605
2606 // Initialization
2607 this.$content.addClass( 'oo-ui-dialog-content' );
2608 this.setPendingElement( this.$head );
2609 };
2610
2611 /**
2612 * Get action widgets from a list of configs
2613 *
2614 * @param {Object[]} actions Action widget configs
2615 * @return {OO.ui.ActionWidget[]} Action widgets
2616 */
2617 OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
2618 var i, len, widgets = [];
2619 for ( i = 0, len = actions.length; i < len; i++ ) {
2620 widgets.push(
2621 new OO.ui.ActionWidget( actions[ i ] )
2622 );
2623 }
2624 return widgets;
2625 };
2626
2627 /**
2628 * Attach action actions.
2629 *
2630 * @protected
2631 */
2632 OO.ui.Dialog.prototype.attachActions = function () {
2633 // Remember the list of potentially attached actions
2634 this.attachedActions = this.actions.get();
2635 };
2636
2637 /**
2638 * Detach action actions.
2639 *
2640 * @protected
2641 * @chainable
2642 */
2643 OO.ui.Dialog.prototype.detachActions = function () {
2644 var i, len;
2645
2646 // Detach all actions that may have been previously attached
2647 for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
2648 this.attachedActions[ i ].$element.detach();
2649 }
2650 this.attachedActions = [];
2651 };
2652
2653 /**
2654 * Execute an action.
2655 *
2656 * @param {string} action Symbolic name of action to execute
2657 * @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
2658 */
2659 OO.ui.Dialog.prototype.executeAction = function ( action ) {
2660 this.pushPending();
2661 this.currentAction = action;
2662 return this.getActionProcess( action ).execute()
2663 .always( this.popPending.bind( this ) );
2664 };
2665
2666 /**
2667 * Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
2668 * Managed windows are mutually exclusive. If a new window is opened while a current window is opening
2669 * or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
2670 * themselves are persistent and—rather than being torn down when closed—can be repopulated with the
2671 * pertinent data and reused.
2672 *
2673 * Over the lifecycle of a window, the window manager makes available three promises: `opening`,
2674 * `opened`, and `closing`, which represent the primary stages of the cycle:
2675 *
2676 * **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
2677 * {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
2678 *
2679 * - an `opening` event is emitted with an `opening` promise
2680 * - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
2681 * the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
2682 * window and its result executed
2683 * - a `setup` progress notification is emitted from the `opening` promise
2684 * - the #getReadyDelay method is called the returned value is used to time a pause in execution before
2685 * the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
2686 * window and its result executed
2687 * - a `ready` progress notification is emitted from the `opening` promise
2688 * - the `opening` promise is resolved with an `opened` promise
2689 *
2690 * **Opened**: the window is now open.
2691 *
2692 * **Closing**: the closing stage begins when the window manager's #closeWindow or the
2693 * window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
2694 * to close the window.
2695 *
2696 * - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
2697 * - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
2698 * the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
2699 * window and its result executed
2700 * - a `hold` progress notification is emitted from the `closing` promise
2701 * - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
2702 * the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
2703 * window and its result executed
2704 * - a `teardown` progress notification is emitted from the `closing` promise
2705 * - the `closing` promise is resolved. The window is now closed
2706 *
2707 * See the [OOjs UI documentation on MediaWiki][1] for more information.
2708 *
2709 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2710 *
2711 * @class
2712 * @extends OO.ui.Element
2713 * @mixins OO.EventEmitter
2714 *
2715 * @constructor
2716 * @param {Object} [config] Configuration options
2717 * @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
2718 * Note that window classes that are instantiated with a factory must have
2719 * a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
2720 * @cfg {boolean} [modal=true] Prevent interaction outside the dialog
2721 */
2722 OO.ui.WindowManager = function OoUiWindowManager( config ) {
2723 // Configuration initialization
2724 config = config || {};
2725
2726 // Parent constructor
2727 OO.ui.WindowManager.super.call( this, config );
2728
2729 // Mixin constructors
2730 OO.EventEmitter.call( this );
2731
2732 // Properties
2733 this.factory = config.factory;
2734 this.modal = config.modal === undefined || !!config.modal;
2735 this.windows = {};
2736 this.opening = null;
2737 this.opened = null;
2738 this.closing = null;
2739 this.preparingToOpen = null;
2740 this.preparingToClose = null;
2741 this.currentWindow = null;
2742 this.globalEvents = false;
2743 this.$ariaHidden = null;
2744 this.onWindowResizeTimeout = null;
2745 this.onWindowResizeHandler = this.onWindowResize.bind( this );
2746 this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
2747
2748 // Initialization
2749 this.$element
2750 .addClass( 'oo-ui-windowManager' )
2751 .toggleClass( 'oo-ui-windowManager-modal', this.modal );
2752 };
2753
2754 /* Setup */
2755
2756 OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
2757 OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
2758
2759 /* Events */
2760
2761 /**
2762 * An 'opening' event is emitted when the window begins to be opened.
2763 *
2764 * @event opening
2765 * @param {OO.ui.Window} win Window that's being opened
2766 * @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
2767 * When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
2768 * is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
2769 * @param {Object} data Window opening data
2770 */
2771
2772 /**
2773 * A 'closing' event is emitted when the window begins to be closed.
2774 *
2775 * @event closing
2776 * @param {OO.ui.Window} win Window that's being closed
2777 * @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
2778 * is closed successfully. The promise emits `hold` and `teardown` notifications when those
2779 * processes are complete. When the `closing` promise is resolved, the first argument of its value
2780 * is the closing data.
2781 * @param {Object} data Window closing data
2782 */
2783
2784 /**
2785 * A 'resize' event is emitted when a window is resized.
2786 *
2787 * @event resize
2788 * @param {OO.ui.Window} win Window that was resized
2789 */
2790
2791 /* Static Properties */
2792
2793 /**
2794 * Map of the symbolic name of each window size and its CSS properties.
2795 *
2796 * @static
2797 * @inheritable
2798 * @property {Object}
2799 */
2800 OO.ui.WindowManager.static.sizes = {
2801 small: {
2802 width: 300
2803 },
2804 medium: {
2805 width: 500
2806 },
2807 large: {
2808 width: 700
2809 },
2810 larger: {
2811 width: 900
2812 },
2813 full: {
2814 // These can be non-numeric because they are never used in calculations
2815 width: '100%',
2816 height: '100%'
2817 }
2818 };
2819
2820 /**
2821 * Symbolic name of the default window size.
2822 *
2823 * The default size is used if the window's requested size is not recognized.
2824 *
2825 * @static
2826 * @inheritable
2827 * @property {string}
2828 */
2829 OO.ui.WindowManager.static.defaultSize = 'medium';
2830
2831 /* Methods */
2832
2833 /**
2834 * Handle window resize events.
2835 *
2836 * @private
2837 * @param {jQuery.Event} e Window resize event
2838 */
2839 OO.ui.WindowManager.prototype.onWindowResize = function () {
2840 clearTimeout( this.onWindowResizeTimeout );
2841 this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
2842 };
2843
2844 /**
2845 * Handle window resize events.
2846 *
2847 * @private
2848 * @param {jQuery.Event} e Window resize event
2849 */
2850 OO.ui.WindowManager.prototype.afterWindowResize = function () {
2851 if ( this.currentWindow ) {
2852 this.updateWindowSize( this.currentWindow );
2853 }
2854 };
2855
2856 /**
2857 * Check if window is opening.
2858 *
2859 * @return {boolean} Window is opening
2860 */
2861 OO.ui.WindowManager.prototype.isOpening = function ( win ) {
2862 return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
2863 };
2864
2865 /**
2866 * Check if window is closing.
2867 *
2868 * @return {boolean} Window is closing
2869 */
2870 OO.ui.WindowManager.prototype.isClosing = function ( win ) {
2871 return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
2872 };
2873
2874 /**
2875 * Check if window is opened.
2876 *
2877 * @return {boolean} Window is opened
2878 */
2879 OO.ui.WindowManager.prototype.isOpened = function ( win ) {
2880 return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
2881 };
2882
2883 /**
2884 * Check if a window is being managed.
2885 *
2886 * @param {OO.ui.Window} win Window to check
2887 * @return {boolean} Window is being managed
2888 */
2889 OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
2890 var name;
2891
2892 for ( name in this.windows ) {
2893 if ( this.windows[ name ] === win ) {
2894 return true;
2895 }
2896 }
2897
2898 return false;
2899 };
2900
2901 /**
2902 * Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
2903 *
2904 * @param {OO.ui.Window} win Window being opened
2905 * @param {Object} [data] Window opening data
2906 * @return {number} Milliseconds to wait
2907 */
2908 OO.ui.WindowManager.prototype.getSetupDelay = function () {
2909 return 0;
2910 };
2911
2912 /**
2913 * Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
2914 *
2915 * @param {OO.ui.Window} win Window being opened
2916 * @param {Object} [data] Window opening data
2917 * @return {number} Milliseconds to wait
2918 */
2919 OO.ui.WindowManager.prototype.getReadyDelay = function () {
2920 return 0;
2921 };
2922
2923 /**
2924 * Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
2925 *
2926 * @param {OO.ui.Window} win Window being closed
2927 * @param {Object} [data] Window closing data
2928 * @return {number} Milliseconds to wait
2929 */
2930 OO.ui.WindowManager.prototype.getHoldDelay = function () {
2931 return 0;
2932 };
2933
2934 /**
2935 * Get the number of milliseconds to wait after the ‘hold’ process has finished before
2936 * executing the ‘teardown’ process.
2937 *
2938 * @param {OO.ui.Window} win Window being closed
2939 * @param {Object} [data] Window closing data
2940 * @return {number} Milliseconds to wait
2941 */
2942 OO.ui.WindowManager.prototype.getTeardownDelay = function () {
2943 return this.modal ? 250 : 0;
2944 };
2945
2946 /**
2947 * Get a window by its symbolic name.
2948 *
2949 * If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
2950 * instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
2951 * for more information about using factories.
2952 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
2953 *
2954 * @param {string} name Symbolic name of the window
2955 * @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
2956 * @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
2957 * @throws {Error} An error is thrown if the named window is not recognized as a managed window.
2958 */
2959 OO.ui.WindowManager.prototype.getWindow = function ( name ) {
2960 var deferred = $.Deferred(),
2961 win = this.windows[ name ];
2962
2963 if ( !( win instanceof OO.ui.Window ) ) {
2964 if ( this.factory ) {
2965 if ( !this.factory.lookup( name ) ) {
2966 deferred.reject( new OO.ui.Error(
2967 'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
2968 ) );
2969 } else {
2970 win = this.factory.create( name );
2971 this.addWindows( [ win ] );
2972 deferred.resolve( win );
2973 }
2974 } else {
2975 deferred.reject( new OO.ui.Error(
2976 'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
2977 ) );
2978 }
2979 } else {
2980 deferred.resolve( win );
2981 }
2982
2983 return deferred.promise();
2984 };
2985
2986 /**
2987 * Get current window.
2988 *
2989 * @return {OO.ui.Window|null} Currently opening/opened/closing window
2990 */
2991 OO.ui.WindowManager.prototype.getCurrentWindow = function () {
2992 return this.currentWindow;
2993 };
2994
2995 /**
2996 * Open a window.
2997 *
2998 * @param {OO.ui.Window|string} win Window object or symbolic name of window to open
2999 * @param {Object} [data] Window opening data
3000 * @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
3001 * See {@link #event-opening 'opening' event} for more information about `opening` promises.
3002 * @fires opening
3003 */
3004 OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
3005 var manager = this,
3006 opening = $.Deferred();
3007
3008 // Argument handling
3009 if ( typeof win === 'string' ) {
3010 return this.getWindow( win ).then( function ( win ) {
3011 return manager.openWindow( win, data );
3012 } );
3013 }
3014
3015 // Error handling
3016 if ( !this.hasWindow( win ) ) {
3017 opening.reject( new OO.ui.Error(
3018 'Cannot open window: window is not attached to manager'
3019 ) );
3020 } else if ( this.preparingToOpen || this.opening || this.opened ) {
3021 opening.reject( new OO.ui.Error(
3022 'Cannot open window: another window is opening or open'
3023 ) );
3024 }
3025
3026 // Window opening
3027 if ( opening.state() !== 'rejected' ) {
3028 // If a window is currently closing, wait for it to complete
3029 this.preparingToOpen = $.when( this.closing );
3030 // Ensure handlers get called after preparingToOpen is set
3031 this.preparingToOpen.done( function () {
3032 if ( manager.modal ) {
3033 manager.toggleGlobalEvents( true );
3034 manager.toggleAriaIsolation( true );
3035 }
3036 manager.currentWindow = win;
3037 manager.opening = opening;
3038 manager.preparingToOpen = null;
3039 manager.emit( 'opening', win, opening, data );
3040 setTimeout( function () {
3041 win.setup( data ).then( function () {
3042 manager.updateWindowSize( win );
3043 manager.opening.notify( { state: 'setup' } );
3044 setTimeout( function () {
3045 win.ready( data ).then( function () {
3046 manager.opening.notify( { state: 'ready' } );
3047 manager.opening = null;
3048 manager.opened = $.Deferred();
3049 opening.resolve( manager.opened.promise(), data );
3050 } );
3051 }, manager.getReadyDelay() );
3052 } );
3053 }, manager.getSetupDelay() );
3054 } );
3055 }
3056
3057 return opening.promise();
3058 };
3059
3060 /**
3061 * Close a window.
3062 *
3063 * @param {OO.ui.Window|string} win Window object or symbolic name of window to close
3064 * @param {Object} [data] Window closing data
3065 * @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
3066 * See {@link #event-closing 'closing' event} for more information about closing promises.
3067 * @throws {Error} An error is thrown if the window is not managed by the window manager.
3068 * @fires closing
3069 */
3070 OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
3071 var manager = this,
3072 closing = $.Deferred(),
3073 opened;
3074
3075 // Argument handling
3076 if ( typeof win === 'string' ) {
3077 win = this.windows[ win ];
3078 } else if ( !this.hasWindow( win ) ) {
3079 win = null;
3080 }
3081
3082 // Error handling
3083 if ( !win ) {
3084 closing.reject( new OO.ui.Error(
3085 'Cannot close window: window is not attached to manager'
3086 ) );
3087 } else if ( win !== this.currentWindow ) {
3088 closing.reject( new OO.ui.Error(
3089 'Cannot close window: window already closed with different data'
3090 ) );
3091 } else if ( this.preparingToClose || this.closing ) {
3092 closing.reject( new OO.ui.Error(
3093 'Cannot close window: window already closing with different data'
3094 ) );
3095 }
3096
3097 // Window closing
3098 if ( closing.state() !== 'rejected' ) {
3099 // If the window is currently opening, close it when it's done
3100 this.preparingToClose = $.when( this.opening );
3101 // Ensure handlers get called after preparingToClose is set
3102 this.preparingToClose.done( function () {
3103 manager.closing = closing;
3104 manager.preparingToClose = null;
3105 manager.emit( 'closing', win, closing, data );
3106 opened = manager.opened;
3107 manager.opened = null;
3108 opened.resolve( closing.promise(), data );
3109 setTimeout( function () {
3110 win.hold( data ).then( function () {
3111 closing.notify( { state: 'hold' } );
3112 setTimeout( function () {
3113 win.teardown( data ).then( function () {
3114 closing.notify( { state: 'teardown' } );
3115 if ( manager.modal ) {
3116 manager.toggleGlobalEvents( false );
3117 manager.toggleAriaIsolation( false );
3118 }
3119 manager.closing = null;
3120 manager.currentWindow = null;
3121 closing.resolve( data );
3122 } );
3123 }, manager.getTeardownDelay() );
3124 } );
3125 }, manager.getHoldDelay() );
3126 } );
3127 }
3128
3129 return closing.promise();
3130 };
3131
3132 /**
3133 * Add windows to the window manager.
3134 *
3135 * Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
3136 * See the [OOjs ui documentation on MediaWiki] [2] for examples.
3137 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
3138 *
3139 * @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
3140 * by reference, symbolic name, or explicitly defined symbolic names.
3141 * @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
3142 * explicit nor a statically configured symbolic name.
3143 */
3144 OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
3145 var i, len, win, name, list;
3146
3147 if ( Array.isArray( windows ) ) {
3148 // Convert to map of windows by looking up symbolic names from static configuration
3149 list = {};
3150 for ( i = 0, len = windows.length; i < len; i++ ) {
3151 name = windows[ i ].constructor.static.name;
3152 if ( typeof name !== 'string' ) {
3153 throw new Error( 'Cannot add window' );
3154 }
3155 list[ name ] = windows[ i ];
3156 }
3157 } else if ( OO.isPlainObject( windows ) ) {
3158 list = windows;
3159 }
3160
3161 // Add windows
3162 for ( name in list ) {
3163 win = list[ name ];
3164 this.windows[ name ] = win.toggle( false );
3165 this.$element.append( win.$element );
3166 win.setManager( this );
3167 }
3168 };
3169
3170 /**
3171 * Remove the specified windows from the windows manager.
3172 *
3173 * Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
3174 * the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
3175 * longer listens to events, use the #destroy method.
3176 *
3177 * @param {string[]} names Symbolic names of windows to remove
3178 * @return {jQuery.Promise} Promise resolved when window is closed and removed
3179 * @throws {Error} An error is thrown if the named windows are not managed by the window manager.
3180 */
3181 OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
3182 var i, len, win, name, cleanupWindow,
3183 manager = this,
3184 promises = [],
3185 cleanup = function ( name, win ) {
3186 delete manager.windows[ name ];
3187 win.$element.detach();
3188 };
3189
3190 for ( i = 0, len = names.length; i < len; i++ ) {
3191 name = names[ i ];
3192 win = this.windows[ name ];
3193 if ( !win ) {
3194 throw new Error( 'Cannot remove window' );
3195 }
3196 cleanupWindow = cleanup.bind( null, name, win );
3197 promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
3198 }
3199
3200 return $.when.apply( $, promises );
3201 };
3202
3203 /**
3204 * Remove all windows from the window manager.
3205 *
3206 * Windows will be closed before they are removed. Note that the window manager, though not in use, will still
3207 * listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
3208 * To remove just a subset of windows, use the #removeWindows method.
3209 *
3210 * @return {jQuery.Promise} Promise resolved when all windows are closed and removed
3211 */
3212 OO.ui.WindowManager.prototype.clearWindows = function () {
3213 return this.removeWindows( Object.keys( this.windows ) );
3214 };
3215
3216 /**
3217 * Set dialog size. In general, this method should not be called directly.
3218 *
3219 * Fullscreen mode will be used if the dialog is too wide to fit in the screen.
3220 *
3221 * @chainable
3222 */
3223 OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
3224 // Bypass for non-current, and thus invisible, windows
3225 if ( win !== this.currentWindow ) {
3226 return;
3227 }
3228
3229 var viewport = OO.ui.Element.static.getDimensions( win.getElementWindow() ),
3230 sizes = this.constructor.static.sizes,
3231 size = win.getSize();
3232
3233 if ( !sizes[ size ] ) {
3234 size = this.constructor.static.defaultSize;
3235 }
3236 if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
3237 size = 'full';
3238 }
3239
3240 this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', size === 'full' );
3241 this.$element.toggleClass( 'oo-ui-windowManager-floating', size !== 'full' );
3242 win.setDimensions( sizes[ size ] );
3243
3244 this.emit( 'resize', win );
3245
3246 return this;
3247 };
3248
3249 /**
3250 * Bind or unbind global events for scrolling.
3251 *
3252 * @private
3253 * @param {boolean} [on] Bind global events
3254 * @chainable
3255 */
3256 OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
3257 on = on === undefined ? !!this.globalEvents : !!on;
3258
3259 var scrollWidth, bodyMargin,
3260 $body = $( this.getElementDocument().body ),
3261 // We could have multiple window managers open so only modify
3262 // the body css at the bottom of the stack
3263 stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0 ;
3264
3265 if ( on ) {
3266 if ( !this.globalEvents ) {
3267 $( this.getElementWindow() ).on( {
3268 // Start listening for top-level window dimension changes
3269 'orientationchange resize': this.onWindowResizeHandler
3270 } );
3271 if ( stackDepth === 0 ) {
3272 scrollWidth = window.innerWidth - document.documentElement.clientWidth;
3273 bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
3274 $body.css( {
3275 overflow: 'hidden',
3276 'margin-right': bodyMargin + scrollWidth
3277 } );
3278 }
3279 stackDepth++;
3280 this.globalEvents = true;
3281 }
3282 } else if ( this.globalEvents ) {
3283 $( this.getElementWindow() ).off( {
3284 // Stop listening for top-level window dimension changes
3285 'orientationchange resize': this.onWindowResizeHandler
3286 } );
3287 stackDepth--;
3288 if ( stackDepth === 0 ) {
3289 $body.css( {
3290 overflow: '',
3291 'margin-right': ''
3292 } );
3293 }
3294 this.globalEvents = false;
3295 }
3296 $body.data( 'windowManagerGlobalEvents', stackDepth );
3297
3298 return this;
3299 };
3300
3301 /**
3302 * Toggle screen reader visibility of content other than the window manager.
3303 *
3304 * @private
3305 * @param {boolean} [isolate] Make only the window manager visible to screen readers
3306 * @chainable
3307 */
3308 OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
3309 isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
3310
3311 if ( isolate ) {
3312 if ( !this.$ariaHidden ) {
3313 // Hide everything other than the window manager from screen readers
3314 this.$ariaHidden = $( 'body' )
3315 .children()
3316 .not( this.$element.parentsUntil( 'body' ).last() )
3317 .attr( 'aria-hidden', '' );
3318 }
3319 } else if ( this.$ariaHidden ) {
3320 // Restore screen reader visibility
3321 this.$ariaHidden.removeAttr( 'aria-hidden' );
3322 this.$ariaHidden = null;
3323 }
3324
3325 return this;
3326 };
3327
3328 /**
3329 * Destroy the window manager.
3330 *
3331 * Destroying the window manager ensures that it will no longer listen to events. If you would like to
3332 * continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
3333 * instead.
3334 */
3335 OO.ui.WindowManager.prototype.destroy = function () {
3336 this.toggleGlobalEvents( false );
3337 this.toggleAriaIsolation( false );
3338 this.clearWindows();
3339 this.$element.remove();
3340 };
3341
3342 /**
3343 * @class
3344 *
3345 * @constructor
3346 * @param {string|jQuery} message Description of error
3347 * @param {Object} [config] Configuration options
3348 * @cfg {boolean} [recoverable=true] Error is recoverable
3349 * @cfg {boolean} [warning=false] Whether this error is a warning or not.
3350 */
3351 OO.ui.Error = function OoUiError( message, config ) {
3352 // Allow passing positional parameters inside the config object
3353 if ( OO.isPlainObject( message ) && config === undefined ) {
3354 config = message;
3355 message = config.message;
3356 }
3357
3358 // Configuration initialization
3359 config = config || {};
3360
3361 // Properties
3362 this.message = message instanceof jQuery ? message : String( message );
3363 this.recoverable = config.recoverable === undefined || !!config.recoverable;
3364 this.warning = !!config.warning;
3365 };
3366
3367 /* Setup */
3368
3369 OO.initClass( OO.ui.Error );
3370
3371 /* Methods */
3372
3373 /**
3374 * Check if error can be recovered from.
3375 *
3376 * @return {boolean} Error is recoverable
3377 */
3378 OO.ui.Error.prototype.isRecoverable = function () {
3379 return this.recoverable;
3380 };
3381
3382 /**
3383 * Check if the error is a warning
3384 *
3385 * @return {boolean} Error is warning
3386 */
3387 OO.ui.Error.prototype.isWarning = function () {
3388 return this.warning;
3389 };
3390
3391 /**
3392 * Get error message as DOM nodes.
3393 *
3394 * @return {jQuery} Error message in DOM nodes
3395 */
3396 OO.ui.Error.prototype.getMessage = function () {
3397 return this.message instanceof jQuery ?
3398 this.message.clone() :
3399 $( '<div>' ).text( this.message ).contents();
3400 };
3401
3402 /**
3403 * Get error message as text.
3404 *
3405 * @return {string} Error message
3406 */
3407 OO.ui.Error.prototype.getMessageText = function () {
3408 return this.message instanceof jQuery ? this.message.text() : this.message;
3409 };
3410
3411 /**
3412 * Wraps an HTML snippet for use with configuration values which default
3413 * to strings. This bypasses the default html-escaping done to string
3414 * values.
3415 *
3416 * @class
3417 *
3418 * @constructor
3419 * @param {string} [content] HTML content
3420 */
3421 OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) {
3422 // Properties
3423 this.content = content;
3424 };
3425
3426 /* Setup */
3427
3428 OO.initClass( OO.ui.HtmlSnippet );
3429
3430 /* Methods */
3431
3432 /**
3433 * Render into HTML.
3434 *
3435 * @return {string} Unchanged HTML snippet.
3436 */
3437 OO.ui.HtmlSnippet.prototype.toString = function () {
3438 return this.content;
3439 };
3440
3441 /**
3442 * A list of functions, called in sequence.
3443 *
3444 * If a function added to a process returns boolean false the process will stop; if it returns an
3445 * object with a `promise` method the process will use the promise to either continue to the next
3446 * step when the promise is resolved or stop when the promise is rejected.
3447 *
3448 * @class
3449 *
3450 * @constructor
3451 * @param {number|jQuery.Promise|Function} step Time to wait, promise to wait for or function to
3452 * call, see #createStep for more information
3453 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3454 * or a promise
3455 * @return {Object} Step object, with `callback` and `context` properties
3456 */
3457 OO.ui.Process = function ( step, context ) {
3458 // Properties
3459 this.steps = [];
3460
3461 // Initialization
3462 if ( step !== undefined ) {
3463 this.next( step, context );
3464 }
3465 };
3466
3467 /* Setup */
3468
3469 OO.initClass( OO.ui.Process );
3470
3471 /* Methods */
3472
3473 /**
3474 * Start the process.
3475 *
3476 * @return {jQuery.Promise} Promise that is resolved when all steps have completed or rejected when
3477 * any of the steps return boolean false or a promise which gets rejected; upon stopping the
3478 * process, the remaining steps will not be taken
3479 */
3480 OO.ui.Process.prototype.execute = function () {
3481 var i, len, promise;
3482
3483 /**
3484 * Continue execution.
3485 *
3486 * @ignore
3487 * @param {Array} step A function and the context it should be called in
3488 * @return {Function} Function that continues the process
3489 */
3490 function proceed( step ) {
3491 return function () {
3492 // Execute step in the correct context
3493 var deferred,
3494 result = step.callback.call( step.context );
3495
3496 if ( result === false ) {
3497 // Use rejected promise for boolean false results
3498 return $.Deferred().reject( [] ).promise();
3499 }
3500 if ( typeof result === 'number' ) {
3501 if ( result < 0 ) {
3502 throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
3503 }
3504 // Use a delayed promise for numbers, expecting them to be in milliseconds
3505 deferred = $.Deferred();
3506 setTimeout( deferred.resolve, result );
3507 return deferred.promise();
3508 }
3509 if ( result instanceof OO.ui.Error ) {
3510 // Use rejected promise for error
3511 return $.Deferred().reject( [ result ] ).promise();
3512 }
3513 if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
3514 // Use rejected promise for list of errors
3515 return $.Deferred().reject( result ).promise();
3516 }
3517 // Duck-type the object to see if it can produce a promise
3518 if ( result && $.isFunction( result.promise ) ) {
3519 // Use a promise generated from the result
3520 return result.promise();
3521 }
3522 // Use resolved promise for other results
3523 return $.Deferred().resolve().promise();
3524 };
3525 }
3526
3527 if ( this.steps.length ) {
3528 // Generate a chain reaction of promises
3529 promise = proceed( this.steps[ 0 ] )();
3530 for ( i = 1, len = this.steps.length; i < len; i++ ) {
3531 promise = promise.then( proceed( this.steps[ i ] ) );
3532 }
3533 } else {
3534 promise = $.Deferred().resolve().promise();
3535 }
3536
3537 return promise;
3538 };
3539
3540 /**
3541 * Create a process step.
3542 *
3543 * @private
3544 * @param {number|jQuery.Promise|Function} step
3545 *
3546 * - Number of milliseconds to wait; or
3547 * - Promise to wait to be resolved; or
3548 * - Function to execute
3549 * - If it returns boolean false the process will stop
3550 * - If it returns an object with a `promise` method the process will use the promise to either
3551 * continue to the next step when the promise is resolved or stop when the promise is rejected
3552 * - If it returns a number, the process will wait for that number of milliseconds before
3553 * proceeding
3554 * @param {Object} [context=null] Context to call the step function in, ignored if step is a number
3555 * or a promise
3556 * @return {Object} Step object, with `callback` and `context` properties
3557 */
3558 OO.ui.Process.prototype.createStep = function ( step, context ) {
3559 if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
3560 return {
3561 callback: function () {
3562 return step;
3563 },
3564 context: null
3565 };
3566 }
3567 if ( $.isFunction( step ) ) {
3568 return {
3569 callback: step,
3570 context: context
3571 };
3572 }
3573 throw new Error( 'Cannot create process step: number, promise or function expected' );
3574 };
3575
3576 /**
3577 * Add step to the beginning of the process.
3578 *
3579 * @inheritdoc #createStep
3580 * @return {OO.ui.Process} this
3581 * @chainable
3582 */
3583 OO.ui.Process.prototype.first = function ( step, context ) {
3584 this.steps.unshift( this.createStep( step, context ) );
3585 return this;
3586 };
3587
3588 /**
3589 * Add step to the end of the process.
3590 *
3591 * @inheritdoc #createStep
3592 * @return {OO.ui.Process} this
3593 * @chainable
3594 */
3595 OO.ui.Process.prototype.next = function ( step, context ) {
3596 this.steps.push( this.createStep( step, context ) );
3597 return this;
3598 };
3599
3600 /**
3601 * Factory for tools.
3602 *
3603 * @class
3604 * @extends OO.Factory
3605 * @constructor
3606 */
3607 OO.ui.ToolFactory = function OoUiToolFactory() {
3608 // Parent constructor
3609 OO.ui.ToolFactory.super.call( this );
3610 };
3611
3612 /* Setup */
3613
3614 OO.inheritClass( OO.ui.ToolFactory, OO.Factory );
3615
3616 /* Methods */
3617
3618 /**
3619 * Get tools from the factory
3620 *
3621 * @param {Array} include Included tools
3622 * @param {Array} exclude Excluded tools
3623 * @param {Array} promote Promoted tools
3624 * @param {Array} demote Demoted tools
3625 * @return {string[]} List of tools
3626 */
3627 OO.ui.ToolFactory.prototype.getTools = function ( include, exclude, promote, demote ) {
3628 var i, len, included, promoted, demoted,
3629 auto = [],
3630 used = {};
3631
3632 // Collect included and not excluded tools
3633 included = OO.simpleArrayDifference( this.extract( include ), this.extract( exclude ) );
3634
3635 // Promotion
3636 promoted = this.extract( promote, used );
3637 demoted = this.extract( demote, used );
3638
3639 // Auto
3640 for ( i = 0, len = included.length; i < len; i++ ) {
3641 if ( !used[ included[ i ] ] ) {
3642 auto.push( included[ i ] );
3643 }
3644 }
3645
3646 return promoted.concat( auto ).concat( demoted );
3647 };
3648
3649 /**
3650 * Get a flat list of names from a list of names or groups.
3651 *
3652 * Tools can be specified in the following ways:
3653 *
3654 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
3655 * - All tools in a group: `{ group: 'group-name' }`
3656 * - All tools: `'*'`
3657 *
3658 * @private
3659 * @param {Array|string} collection List of tools
3660 * @param {Object} [used] Object with names that should be skipped as properties; extracted
3661 * names will be added as properties
3662 * @return {string[]} List of extracted names
3663 */
3664 OO.ui.ToolFactory.prototype.extract = function ( collection, used ) {
3665 var i, len, item, name, tool,
3666 names = [];
3667
3668 if ( collection === '*' ) {
3669 for ( name in this.registry ) {
3670 tool = this.registry[ name ];
3671 if (
3672 // Only add tools by group name when auto-add is enabled
3673 tool.static.autoAddToCatchall &&
3674 // Exclude already used tools
3675 ( !used || !used[ name ] )
3676 ) {
3677 names.push( name );
3678 if ( used ) {
3679 used[ name ] = true;
3680 }
3681 }
3682 }
3683 } else if ( Array.isArray( collection ) ) {
3684 for ( i = 0, len = collection.length; i < len; i++ ) {
3685 item = collection[ i ];
3686 // Allow plain strings as shorthand for named tools
3687 if ( typeof item === 'string' ) {
3688 item = { name: item };
3689 }
3690 if ( OO.isPlainObject( item ) ) {
3691 if ( item.group ) {
3692 for ( name in this.registry ) {
3693 tool = this.registry[ name ];
3694 if (
3695 // Include tools with matching group
3696 tool.static.group === item.group &&
3697 // Only add tools by group name when auto-add is enabled
3698 tool.static.autoAddToGroup &&
3699 // Exclude already used tools
3700 ( !used || !used[ name ] )
3701 ) {
3702 names.push( name );
3703 if ( used ) {
3704 used[ name ] = true;
3705 }
3706 }
3707 }
3708 // Include tools with matching name and exclude already used tools
3709 } else if ( item.name && ( !used || !used[ item.name ] ) ) {
3710 names.push( item.name );
3711 if ( used ) {
3712 used[ item.name ] = true;
3713 }
3714 }
3715 }
3716 }
3717 }
3718 return names;
3719 };
3720
3721 /**
3722 * Factory for tool groups.
3723 *
3724 * @class
3725 * @extends OO.Factory
3726 * @constructor
3727 */
3728 OO.ui.ToolGroupFactory = function OoUiToolGroupFactory() {
3729 // Parent constructor
3730 OO.Factory.call( this );
3731
3732 var i, l,
3733 defaultClasses = this.constructor.static.getDefaultClasses();
3734
3735 // Register default toolgroups
3736 for ( i = 0, l = defaultClasses.length; i < l; i++ ) {
3737 this.register( defaultClasses[ i ] );
3738 }
3739 };
3740
3741 /* Setup */
3742
3743 OO.inheritClass( OO.ui.ToolGroupFactory, OO.Factory );
3744
3745 /* Static Methods */
3746
3747 /**
3748 * Get a default set of classes to be registered on construction
3749 *
3750 * @return {Function[]} Default classes
3751 */
3752 OO.ui.ToolGroupFactory.static.getDefaultClasses = function () {
3753 return [
3754 OO.ui.BarToolGroup,
3755 OO.ui.ListToolGroup,
3756 OO.ui.MenuToolGroup
3757 ];
3758 };
3759
3760 /**
3761 * Theme logic.
3762 *
3763 * @abstract
3764 * @class
3765 *
3766 * @constructor
3767 * @param {Object} [config] Configuration options
3768 */
3769 OO.ui.Theme = function OoUiTheme( config ) {
3770 // Configuration initialization
3771 config = config || {};
3772 };
3773
3774 /* Setup */
3775
3776 OO.initClass( OO.ui.Theme );
3777
3778 /* Methods */
3779
3780 /**
3781 * Get a list of classes to be applied to a widget.
3782 *
3783 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
3784 * otherwise state transitions will not work properly.
3785 *
3786 * @param {OO.ui.Element} element Element for which to get classes
3787 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3788 */
3789 OO.ui.Theme.prototype.getElementClasses = function ( /* element */ ) {
3790 return { on: [], off: [] };
3791 };
3792
3793 /**
3794 * Update CSS classes provided by the theme.
3795 *
3796 * For elements with theme logic hooks, this should be called any time there's a state change.
3797 *
3798 * @param {OO.ui.Element} element Element for which to update classes
3799 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
3800 */
3801 OO.ui.Theme.prototype.updateElementClasses = function ( element ) {
3802 var classes = this.getElementClasses( element );
3803
3804 element.$element
3805 .removeClass( classes.off.join( ' ' ) )
3806 .addClass( classes.on.join( ' ' ) );
3807 };
3808
3809 /**
3810 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
3811 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
3812 * order in which users will navigate through the focusable elements via the "tab" key.
3813 *
3814 * @example
3815 * // TabIndexedElement is mixed into the ButtonWidget class
3816 * // to provide a tabIndex property.
3817 * var button1 = new OO.ui.ButtonWidget( {
3818 * label: 'fourth',
3819 * tabIndex: 4
3820 * } );
3821 * var button2 = new OO.ui.ButtonWidget( {
3822 * label: 'second',
3823 * tabIndex: 2
3824 * } );
3825 * var button3 = new OO.ui.ButtonWidget( {
3826 * label: 'third',
3827 * tabIndex: 3
3828 * } );
3829 * var button4 = new OO.ui.ButtonWidget( {
3830 * label: 'first',
3831 * tabIndex: 1
3832 * } );
3833 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
3834 *
3835 * @abstract
3836 * @class
3837 *
3838 * @constructor
3839 * @param {Object} [config] Configuration options
3840 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
3841 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
3842 * functionality will be applied to it instead.
3843 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
3844 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
3845 * to remove the element from the tab-navigation flow.
3846 */
3847 OO.ui.TabIndexedElement = function OoUiTabIndexedElement( config ) {
3848 // Configuration initialization
3849 config = $.extend( { tabIndex: 0 }, config );
3850
3851 // Properties
3852 this.$tabIndexed = null;
3853 this.tabIndex = null;
3854
3855 // Events
3856 this.connect( this, { disable: 'onDisable' } );
3857
3858 // Initialization
3859 this.setTabIndex( config.tabIndex );
3860 this.setTabIndexedElement( config.$tabIndexed || this.$element );
3861 };
3862
3863 /* Setup */
3864
3865 OO.initClass( OO.ui.TabIndexedElement );
3866
3867 /* Methods */
3868
3869 /**
3870 * Set the element that should use the tabindex functionality.
3871 *
3872 * This method is used to retarget a tabindex mixin so that its functionality applies
3873 * to the specified element. If an element is currently using the functionality, the mixin’s
3874 * effect on that element is removed before the new element is set up.
3875 *
3876 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
3877 * @chainable
3878 */
3879 OO.ui.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) {
3880 var tabIndex = this.tabIndex;
3881 // Remove attributes from old $tabIndexed
3882 this.setTabIndex( null );
3883 // Force update of new $tabIndexed
3884 this.$tabIndexed = $tabIndexed;
3885 this.tabIndex = tabIndex;
3886 return this.updateTabIndex();
3887 };
3888
3889 /**
3890 * Set the value of the tabindex.
3891 *
3892 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
3893 * @chainable
3894 */
3895 OO.ui.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) {
3896 tabIndex = typeof tabIndex === 'number' ? tabIndex : null;
3897
3898 if ( this.tabIndex !== tabIndex ) {
3899 this.tabIndex = tabIndex;
3900 this.updateTabIndex();
3901 }
3902
3903 return this;
3904 };
3905
3906 /**
3907 * Update the `tabindex` attribute, in case of changes to tab index or
3908 * disabled state.
3909 *
3910 * @private
3911 * @chainable
3912 */
3913 OO.ui.TabIndexedElement.prototype.updateTabIndex = function () {
3914 if ( this.$tabIndexed ) {
3915 if ( this.tabIndex !== null ) {
3916 // Do not index over disabled elements
3917 this.$tabIndexed.attr( {
3918 tabindex: this.isDisabled() ? -1 : this.tabIndex,
3919 // ChromeVox and NVDA do not seem to inherit this from parent elements
3920 'aria-disabled': this.isDisabled().toString()
3921 } );
3922 } else {
3923 this.$tabIndexed.removeAttr( 'tabindex aria-disabled' );
3924 }
3925 }
3926 return this;
3927 };
3928
3929 /**
3930 * Handle disable events.
3931 *
3932 * @private
3933 * @param {boolean} disabled Element is disabled
3934 */
3935 OO.ui.TabIndexedElement.prototype.onDisable = function () {
3936 this.updateTabIndex();
3937 };
3938
3939 /**
3940 * Get the value of the tabindex.
3941 *
3942 * @return {number|null} Tabindex value
3943 */
3944 OO.ui.TabIndexedElement.prototype.getTabIndex = function () {
3945 return this.tabIndex;
3946 };
3947
3948 /**
3949 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
3950 * interface element that can be configured with access keys for accessibility.
3951 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
3952 *
3953 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
3954 * @abstract
3955 * @class
3956 *
3957 * @constructor
3958 * @param {Object} [config] Configuration options
3959 * @cfg {jQuery} [$button] The button element created by the class.
3960 * If this configuration is omitted, the button element will use a generated `<a>`.
3961 * @cfg {boolean} [framed=true] Render the button with a frame
3962 * @cfg {string} [accessKey] Button's access key
3963 */
3964 OO.ui.ButtonElement = function OoUiButtonElement( config ) {
3965 // Configuration initialization
3966 config = config || {};
3967
3968 // Properties
3969 this.$button = null;
3970 this.framed = null;
3971 this.accessKey = null;
3972 this.active = false;
3973 this.onMouseUpHandler = this.onMouseUp.bind( this );
3974 this.onMouseDownHandler = this.onMouseDown.bind( this );
3975 this.onKeyDownHandler = this.onKeyDown.bind( this );
3976 this.onKeyUpHandler = this.onKeyUp.bind( this );
3977 this.onClickHandler = this.onClick.bind( this );
3978 this.onKeyPressHandler = this.onKeyPress.bind( this );
3979
3980 // Initialization
3981 this.$element.addClass( 'oo-ui-buttonElement' );
3982 this.toggleFramed( config.framed === undefined || config.framed );
3983 this.setAccessKey( config.accessKey );
3984 this.setButtonElement( config.$button || $( '<a>' ) );
3985 };
3986
3987 /* Setup */
3988
3989 OO.initClass( OO.ui.ButtonElement );
3990
3991 /* Static Properties */
3992
3993 /**
3994 * Cancel mouse down events.
3995 *
3996 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
3997 * Classes such as {@link OO.ui.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
3998 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
3999 * parent widget.
4000 *
4001 * @static
4002 * @inheritable
4003 * @property {boolean}
4004 */
4005 OO.ui.ButtonElement.static.cancelButtonMouseDownEvents = true;
4006
4007 /* Events */
4008
4009 /**
4010 * A 'click' event is emitted when the button element is clicked.
4011 *
4012 * @event click
4013 */
4014
4015 /* Methods */
4016
4017 /**
4018 * Set the button element.
4019 *
4020 * This method is used to retarget a button mixin so that its functionality applies to
4021 * the specified button element instead of the one created by the class. If a button element
4022 * is already set, the method will remove the mixin’s effect on that element.
4023 *
4024 * @param {jQuery} $button Element to use as button
4025 */
4026 OO.ui.ButtonElement.prototype.setButtonElement = function ( $button ) {
4027 if ( this.$button ) {
4028 this.$button
4029 .removeClass( 'oo-ui-buttonElement-button' )
4030 .removeAttr( 'role accesskey' )
4031 .off( {
4032 mousedown: this.onMouseDownHandler,
4033 keydown: this.onKeyDownHandler,
4034 click: this.onClickHandler,
4035 keypress: this.onKeyPressHandler
4036 } );
4037 }
4038
4039 this.$button = $button
4040 .addClass( 'oo-ui-buttonElement-button' )
4041 .attr( { role: 'button', accesskey: this.accessKey } )
4042 .on( {
4043 mousedown: this.onMouseDownHandler,
4044 keydown: this.onKeyDownHandler,
4045 click: this.onClickHandler,
4046 keypress: this.onKeyPressHandler
4047 } );
4048 };
4049
4050 /**
4051 * Handles mouse down events.
4052 *
4053 * @protected
4054 * @param {jQuery.Event} e Mouse down event
4055 */
4056 OO.ui.ButtonElement.prototype.onMouseDown = function ( e ) {
4057 if ( this.isDisabled() || e.which !== 1 ) {
4058 return;
4059 }
4060 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4061 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
4062 // reliably remove the pressed class
4063 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true );
4064 // Prevent change of focus unless specifically configured otherwise
4065 if ( this.constructor.static.cancelButtonMouseDownEvents ) {
4066 return false;
4067 }
4068 };
4069
4070 /**
4071 * Handles mouse up events.
4072 *
4073 * @protected
4074 * @param {jQuery.Event} e Mouse up event
4075 */
4076 OO.ui.ButtonElement.prototype.onMouseUp = function ( e ) {
4077 if ( this.isDisabled() || e.which !== 1 ) {
4078 return;
4079 }
4080 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4081 // Stop listening for mouseup, since we only needed this once
4082 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true );
4083 };
4084
4085 /**
4086 * Handles mouse click events.
4087 *
4088 * @protected
4089 * @param {jQuery.Event} e Mouse click event
4090 * @fires click
4091 */
4092 OO.ui.ButtonElement.prototype.onClick = function ( e ) {
4093 if ( !this.isDisabled() && e.which === 1 ) {
4094 this.emit( 'click' );
4095 }
4096 return false;
4097 };
4098
4099 /**
4100 * Handles key down events.
4101 *
4102 * @protected
4103 * @param {jQuery.Event} e Key down event
4104 */
4105 OO.ui.ButtonElement.prototype.onKeyDown = function ( e ) {
4106 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4107 return;
4108 }
4109 this.$element.addClass( 'oo-ui-buttonElement-pressed' );
4110 // Run the keyup handler no matter where the key is when the button is let go, so we can
4111 // reliably remove the pressed class
4112 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true );
4113 };
4114
4115 /**
4116 * Handles key up events.
4117 *
4118 * @protected
4119 * @param {jQuery.Event} e Key up event
4120 */
4121 OO.ui.ButtonElement.prototype.onKeyUp = function ( e ) {
4122 if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) {
4123 return;
4124 }
4125 this.$element.removeClass( 'oo-ui-buttonElement-pressed' );
4126 // Stop listening for keyup, since we only needed this once
4127 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true );
4128 };
4129
4130 /**
4131 * Handles key press events.
4132 *
4133 * @protected
4134 * @param {jQuery.Event} e Key press event
4135 * @fires click
4136 */
4137 OO.ui.ButtonElement.prototype.onKeyPress = function ( e ) {
4138 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
4139 this.emit( 'click' );
4140 return false;
4141 }
4142 };
4143
4144 /**
4145 * Check if button has a frame.
4146 *
4147 * @return {boolean} Button is framed
4148 */
4149 OO.ui.ButtonElement.prototype.isFramed = function () {
4150 return this.framed;
4151 };
4152
4153 /**
4154 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
4155 *
4156 * @param {boolean} [framed] Make button framed, omit to toggle
4157 * @chainable
4158 */
4159 OO.ui.ButtonElement.prototype.toggleFramed = function ( framed ) {
4160 framed = framed === undefined ? !this.framed : !!framed;
4161 if ( framed !== this.framed ) {
4162 this.framed = framed;
4163 this.$element
4164 .toggleClass( 'oo-ui-buttonElement-frameless', !framed )
4165 .toggleClass( 'oo-ui-buttonElement-framed', framed );
4166 this.updateThemeClasses();
4167 }
4168
4169 return this;
4170 };
4171
4172 /**
4173 * Set the button's access key.
4174 *
4175 * @param {string} accessKey Button's access key, use empty string to remove
4176 * @chainable
4177 */
4178 OO.ui.ButtonElement.prototype.setAccessKey = function ( accessKey ) {
4179 accessKey = typeof accessKey === 'string' && accessKey.length ? accessKey : null;
4180
4181 if ( this.accessKey !== accessKey ) {
4182 if ( this.$button ) {
4183 if ( accessKey !== null ) {
4184 this.$button.attr( 'accesskey', accessKey );
4185 } else {
4186 this.$button.removeAttr( 'accesskey' );
4187 }
4188 }
4189 this.accessKey = accessKey;
4190 }
4191
4192 return this;
4193 };
4194
4195 /**
4196 * Set the button to its 'active' state.
4197 *
4198 * The active state occurs when a {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} or
4199 * a {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} is pressed. This method does nothing
4200 * for other button types.
4201 *
4202 * @param {boolean} [value] Make button active
4203 * @chainable
4204 */
4205 OO.ui.ButtonElement.prototype.setActive = function ( value ) {
4206 this.$element.toggleClass( 'oo-ui-buttonElement-active', !!value );
4207 return this;
4208 };
4209
4210 /**
4211 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
4212 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
4213 * items from the group is done through the interface the class provides.
4214 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
4215 *
4216 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
4217 *
4218 * @abstract
4219 * @class
4220 *
4221 * @constructor
4222 * @param {Object} [config] Configuration options
4223 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
4224 * is omitted, the group element will use a generated `<div>`.
4225 */
4226 OO.ui.GroupElement = function OoUiGroupElement( config ) {
4227 // Configuration initialization
4228 config = config || {};
4229
4230 // Properties
4231 this.$group = null;
4232 this.items = [];
4233 this.aggregateItemEvents = {};
4234
4235 // Initialization
4236 this.setGroupElement( config.$group || $( '<div>' ) );
4237 };
4238
4239 /* Methods */
4240
4241 /**
4242 * Set the group element.
4243 *
4244 * If an element is already set, items will be moved to the new element.
4245 *
4246 * @param {jQuery} $group Element to use as group
4247 */
4248 OO.ui.GroupElement.prototype.setGroupElement = function ( $group ) {
4249 var i, len;
4250
4251 this.$group = $group;
4252 for ( i = 0, len = this.items.length; i < len; i++ ) {
4253 this.$group.append( this.items[ i ].$element );
4254 }
4255 };
4256
4257 /**
4258 * Check if a group contains no items.
4259 *
4260 * @return {boolean} Group is empty
4261 */
4262 OO.ui.GroupElement.prototype.isEmpty = function () {
4263 return !this.items.length;
4264 };
4265
4266 /**
4267 * Get all items in the group.
4268 *
4269 * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful
4270 * when synchronizing groups of items, or whenever the references are required (e.g., when removing items
4271 * from a group).
4272 *
4273 * @return {OO.ui.Element[]} An array of items.
4274 */
4275 OO.ui.GroupElement.prototype.getItems = function () {
4276 return this.items.slice( 0 );
4277 };
4278
4279 /**
4280 * Get an item by its data.
4281 *
4282 * Only the first item with matching data will be returned. To return all matching items,
4283 * use the #getItemsFromData method.
4284 *
4285 * @param {Object} data Item data to search for
4286 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
4287 */
4288 OO.ui.GroupElement.prototype.getItemFromData = function ( data ) {
4289 var i, len, item,
4290 hash = OO.getHash( data );
4291
4292 for ( i = 0, len = this.items.length; i < len; i++ ) {
4293 item = this.items[ i ];
4294 if ( hash === OO.getHash( item.getData() ) ) {
4295 return item;
4296 }
4297 }
4298
4299 return null;
4300 };
4301
4302 /**
4303 * Get items by their data.
4304 *
4305 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
4306 *
4307 * @param {Object} data Item data to search for
4308 * @return {OO.ui.Element[]} Items with equivalent data
4309 */
4310 OO.ui.GroupElement.prototype.getItemsFromData = function ( data ) {
4311 var i, len, item,
4312 hash = OO.getHash( data ),
4313 items = [];
4314
4315 for ( i = 0, len = this.items.length; i < len; i++ ) {
4316 item = this.items[ i ];
4317 if ( hash === OO.getHash( item.getData() ) ) {
4318 items.push( item );
4319 }
4320 }
4321
4322 return items;
4323 };
4324
4325 /**
4326 * Aggregate the events emitted by the group.
4327 *
4328 * When events are aggregated, the group will listen to all contained items for the event,
4329 * and then emit the event under a new name. The new event will contain an additional leading
4330 * parameter containing the item that emitted the original event. Other arguments emitted from
4331 * the original event are passed through.
4332 *
4333 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
4334 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
4335 * A `null` value will remove aggregated events.
4336
4337 * @throws {Error} An error is thrown if aggregation already exists.
4338 */
4339 OO.ui.GroupElement.prototype.aggregate = function ( events ) {
4340 var i, len, item, add, remove, itemEvent, groupEvent;
4341
4342 for ( itemEvent in events ) {
4343 groupEvent = events[ itemEvent ];
4344
4345 // Remove existing aggregated event
4346 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4347 // Don't allow duplicate aggregations
4348 if ( groupEvent ) {
4349 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
4350 }
4351 // Remove event aggregation from existing items
4352 for ( i = 0, len = this.items.length; i < len; i++ ) {
4353 item = this.items[ i ];
4354 if ( item.connect && item.disconnect ) {
4355 remove = {};
4356 remove[ itemEvent ] = [ 'emit', groupEvent, item ];
4357 item.disconnect( this, remove );
4358 }
4359 }
4360 // Prevent future items from aggregating event
4361 delete this.aggregateItemEvents[ itemEvent ];
4362 }
4363
4364 // Add new aggregate event
4365 if ( groupEvent ) {
4366 // Make future items aggregate event
4367 this.aggregateItemEvents[ itemEvent ] = groupEvent;
4368 // Add event aggregation to existing items
4369 for ( i = 0, len = this.items.length; i < len; i++ ) {
4370 item = this.items[ i ];
4371 if ( item.connect && item.disconnect ) {
4372 add = {};
4373 add[ itemEvent ] = [ 'emit', groupEvent, item ];
4374 item.connect( this, add );
4375 }
4376 }
4377 }
4378 }
4379 };
4380
4381 /**
4382 * Add items to the group.
4383 *
4384 * Items will be added to the end of the group array unless the optional `index` parameter specifies
4385 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
4386 *
4387 * @param {OO.ui.Element[]} items An array of items to add to the group
4388 * @param {number} [index] Index of the insertion point
4389 * @chainable
4390 */
4391 OO.ui.GroupElement.prototype.addItems = function ( items, index ) {
4392 var i, len, item, event, events, currentIndex,
4393 itemElements = [];
4394
4395 for ( i = 0, len = items.length; i < len; i++ ) {
4396 item = items[ i ];
4397
4398 // Check if item exists then remove it first, effectively "moving" it
4399 currentIndex = $.inArray( item, this.items );
4400 if ( currentIndex >= 0 ) {
4401 this.removeItems( [ item ] );
4402 // Adjust index to compensate for removal
4403 if ( currentIndex < index ) {
4404 index--;
4405 }
4406 }
4407 // Add the item
4408 if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) {
4409 events = {};
4410 for ( event in this.aggregateItemEvents ) {
4411 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
4412 }
4413 item.connect( this, events );
4414 }
4415 item.setElementGroup( this );
4416 itemElements.push( item.$element.get( 0 ) );
4417 }
4418
4419 if ( index === undefined || index < 0 || index >= this.items.length ) {
4420 this.$group.append( itemElements );
4421 this.items.push.apply( this.items, items );
4422 } else if ( index === 0 ) {
4423 this.$group.prepend( itemElements );
4424 this.items.unshift.apply( this.items, items );
4425 } else {
4426 this.items[ index ].$element.before( itemElements );
4427 this.items.splice.apply( this.items, [ index, 0 ].concat( items ) );
4428 }
4429
4430 return this;
4431 };
4432
4433 /**
4434 * Remove the specified items from a group.
4435 *
4436 * Removed items are detached (not removed) from the DOM so that they may be reused.
4437 * To remove all items from a group, you may wish to use the #clearItems method instead.
4438 *
4439 * @param {OO.ui.Element[]} items An array of items to remove
4440 * @chainable
4441 */
4442 OO.ui.GroupElement.prototype.removeItems = function ( items ) {
4443 var i, len, item, index, remove, itemEvent;
4444
4445 // Remove specific items
4446 for ( i = 0, len = items.length; i < len; i++ ) {
4447 item = items[ i ];
4448 index = $.inArray( item, this.items );
4449 if ( index !== -1 ) {
4450 if (
4451 item.connect && item.disconnect &&
4452 !$.isEmptyObject( this.aggregateItemEvents )
4453 ) {
4454 remove = {};
4455 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4456 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4457 }
4458 item.disconnect( this, remove );
4459 }
4460 item.setElementGroup( null );
4461 this.items.splice( index, 1 );
4462 item.$element.detach();
4463 }
4464 }
4465
4466 return this;
4467 };
4468
4469 /**
4470 * Clear all items from the group.
4471 *
4472 * Cleared items are detached from the DOM, not removed, so that they may be reused.
4473 * To remove only a subset of items from a group, use the #removeItems method.
4474 *
4475 * @chainable
4476 */
4477 OO.ui.GroupElement.prototype.clearItems = function () {
4478 var i, len, item, remove, itemEvent;
4479
4480 // Remove all items
4481 for ( i = 0, len = this.items.length; i < len; i++ ) {
4482 item = this.items[ i ];
4483 if (
4484 item.connect && item.disconnect &&
4485 !$.isEmptyObject( this.aggregateItemEvents )
4486 ) {
4487 remove = {};
4488 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
4489 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
4490 }
4491 item.disconnect( this, remove );
4492 }
4493 item.setElementGroup( null );
4494 item.$element.detach();
4495 }
4496
4497 this.items = [];
4498 return this;
4499 };
4500
4501 /**
4502 * DraggableElement is a mixin class used to create elements that can be clicked
4503 * and dragged by a mouse to a new position within a group. This class must be used
4504 * in conjunction with OO.ui.DraggableGroupElement, which provides a container for
4505 * the draggable elements.
4506 *
4507 * @abstract
4508 * @class
4509 *
4510 * @constructor
4511 */
4512 OO.ui.DraggableElement = function OoUiDraggableElement() {
4513 // Properties
4514 this.index = null;
4515
4516 // Initialize and events
4517 this.$element
4518 .attr( 'draggable', true )
4519 .addClass( 'oo-ui-draggableElement' )
4520 .on( {
4521 dragstart: this.onDragStart.bind( this ),
4522 dragover: this.onDragOver.bind( this ),
4523 dragend: this.onDragEnd.bind( this ),
4524 drop: this.onDrop.bind( this )
4525 } );
4526 };
4527
4528 OO.initClass( OO.ui.DraggableElement );
4529
4530 /* Events */
4531
4532 /**
4533 * @event dragstart
4534 *
4535 * A dragstart event is emitted when the user clicks and begins dragging an item.
4536 * @param {OO.ui.DraggableElement} item The item the user has clicked and is dragging with the mouse.
4537 */
4538
4539 /**
4540 * @event dragend
4541 * A dragend event is emitted when the user drags an item and releases the mouse,
4542 * thus terminating the drag operation.
4543 */
4544
4545 /**
4546 * @event drop
4547 * A drop event is emitted when the user drags an item and then releases the mouse button
4548 * over a valid target.
4549 */
4550
4551 /* Static Properties */
4552
4553 /**
4554 * @inheritdoc OO.ui.ButtonElement
4555 */
4556 OO.ui.DraggableElement.static.cancelButtonMouseDownEvents = false;
4557
4558 /* Methods */
4559
4560 /**
4561 * Respond to dragstart event.
4562 *
4563 * @private
4564 * @param {jQuery.Event} event jQuery event
4565 * @fires dragstart
4566 */
4567 OO.ui.DraggableElement.prototype.onDragStart = function ( e ) {
4568 var dataTransfer = e.originalEvent.dataTransfer;
4569 // Define drop effect
4570 dataTransfer.dropEffect = 'none';
4571 dataTransfer.effectAllowed = 'move';
4572 // We must set up a dataTransfer data property or Firefox seems to
4573 // ignore the fact the element is draggable.
4574 try {
4575 dataTransfer.setData( 'application-x/OOjs-UI-draggable', this.getIndex() );
4576 } catch ( err ) {
4577 // The above is only for firefox. No need to set a catch clause
4578 // if it fails, move on.
4579 }
4580 // Add dragging class
4581 this.$element.addClass( 'oo-ui-draggableElement-dragging' );
4582 // Emit event
4583 this.emit( 'dragstart', this );
4584 return true;
4585 };
4586
4587 /**
4588 * Respond to dragend event.
4589 *
4590 * @private
4591 * @fires dragend
4592 */
4593 OO.ui.DraggableElement.prototype.onDragEnd = function () {
4594 this.$element.removeClass( 'oo-ui-draggableElement-dragging' );
4595 this.emit( 'dragend' );
4596 };
4597
4598 /**
4599 * Handle drop event.
4600 *
4601 * @private
4602 * @param {jQuery.Event} event jQuery event
4603 * @fires drop
4604 */
4605 OO.ui.DraggableElement.prototype.onDrop = function ( e ) {
4606 e.preventDefault();
4607 this.emit( 'drop', e );
4608 };
4609
4610 /**
4611 * In order for drag/drop to work, the dragover event must
4612 * return false and stop propogation.
4613 *
4614 * @private
4615 */
4616 OO.ui.DraggableElement.prototype.onDragOver = function ( e ) {
4617 e.preventDefault();
4618 };
4619
4620 /**
4621 * Set item index.
4622 * Store it in the DOM so we can access from the widget drag event
4623 *
4624 * @private
4625 * @param {number} Item index
4626 */
4627 OO.ui.DraggableElement.prototype.setIndex = function ( index ) {
4628 if ( this.index !== index ) {
4629 this.index = index;
4630 this.$element.data( 'index', index );
4631 }
4632 };
4633
4634 /**
4635 * Get item index
4636 *
4637 * @private
4638 * @return {number} Item index
4639 */
4640 OO.ui.DraggableElement.prototype.getIndex = function () {
4641 return this.index;
4642 };
4643
4644 /**
4645 * DraggableGroupElement is a mixin class used to create a group element to
4646 * contain draggable elements, which are items that can be clicked and dragged by a mouse.
4647 * The class is used with OO.ui.DraggableElement.
4648 *
4649 * @abstract
4650 * @class
4651 * @mixins OO.ui.GroupElement
4652 *
4653 * @constructor
4654 * @param {Object} [config] Configuration options
4655 * @cfg {string} [orientation] Item orientation: 'horizontal' or 'vertical'. The orientation
4656 * should match the layout of the items. Items displayed in a single row
4657 * or in several rows should use horizontal orientation. The vertical orientation should only be
4658 * used when the items are displayed in a single column. Defaults to 'vertical'
4659 */
4660 OO.ui.DraggableGroupElement = function OoUiDraggableGroupElement( config ) {
4661 // Configuration initialization
4662 config = config || {};
4663
4664 // Parent constructor
4665 OO.ui.GroupElement.call( this, config );
4666
4667 // Properties
4668 this.orientation = config.orientation || 'vertical';
4669 this.dragItem = null;
4670 this.itemDragOver = null;
4671 this.itemKeys = {};
4672 this.sideInsertion = '';
4673
4674 // Events
4675 this.aggregate( {
4676 dragstart: 'itemDragStart',
4677 dragend: 'itemDragEnd',
4678 drop: 'itemDrop'
4679 } );
4680 this.connect( this, {
4681 itemDragStart: 'onItemDragStart',
4682 itemDrop: 'onItemDrop',
4683 itemDragEnd: 'onItemDragEnd'
4684 } );
4685 this.$element.on( {
4686 dragover: $.proxy( this.onDragOver, this ),
4687 dragleave: $.proxy( this.onDragLeave, this )
4688 } );
4689
4690 // Initialize
4691 if ( Array.isArray( config.items ) ) {
4692 this.addItems( config.items );
4693 }
4694 this.$placeholder = $( '<div>' )
4695 .addClass( 'oo-ui-draggableGroupElement-placeholder' );
4696 this.$element
4697 .addClass( 'oo-ui-draggableGroupElement' )
4698 .append( this.$status )
4699 .toggleClass( 'oo-ui-draggableGroupElement-horizontal', this.orientation === 'horizontal' )
4700 .prepend( this.$placeholder );
4701 };
4702
4703 /* Setup */
4704 OO.mixinClass( OO.ui.DraggableGroupElement, OO.ui.GroupElement );
4705
4706 /* Events */
4707
4708 /**
4709 * A 'reorder' event is emitted when the order of items in the group changes.
4710 *
4711 * @event reorder
4712 * @param {OO.ui.DraggableElement} item Reordered item
4713 * @param {number} [newIndex] New index for the item
4714 */
4715
4716 /* Methods */
4717
4718 /**
4719 * Respond to item drag start event
4720 *
4721 * @private
4722 * @param {OO.ui.DraggableElement} item Dragged item
4723 */
4724 OO.ui.DraggableGroupElement.prototype.onItemDragStart = function ( item ) {
4725 var i, len;
4726
4727 // Map the index of each object
4728 for ( i = 0, len = this.items.length; i < len; i++ ) {
4729 this.items[ i ].setIndex( i );
4730 }
4731
4732 if ( this.orientation === 'horizontal' ) {
4733 // Set the height of the indicator
4734 this.$placeholder.css( {
4735 height: item.$element.outerHeight(),
4736 width: 2
4737 } );
4738 } else {
4739 // Set the width of the indicator
4740 this.$placeholder.css( {
4741 height: 2,
4742 width: item.$element.outerWidth()
4743 } );
4744 }
4745 this.setDragItem( item );
4746 };
4747
4748 /**
4749 * Respond to item drag end event
4750 *
4751 * @private
4752 */
4753 OO.ui.DraggableGroupElement.prototype.onItemDragEnd = function () {
4754 this.unsetDragItem();
4755 return false;
4756 };
4757
4758 /**
4759 * Handle drop event and switch the order of the items accordingly
4760 *
4761 * @private
4762 * @param {OO.ui.DraggableElement} item Dropped item
4763 * @fires reorder
4764 */
4765 OO.ui.DraggableGroupElement.prototype.onItemDrop = function ( item ) {
4766 var toIndex = item.getIndex();
4767 // Check if the dropped item is from the current group
4768 // TODO: Figure out a way to configure a list of legally droppable
4769 // elements even if they are not yet in the list
4770 if ( this.getDragItem() ) {
4771 // If the insertion point is 'after', the insertion index
4772 // is shifted to the right (or to the left in RTL, hence 'after')
4773 if ( this.sideInsertion === 'after' ) {
4774 toIndex++;
4775 }
4776 // Emit change event
4777 this.emit( 'reorder', this.getDragItem(), toIndex );
4778 }
4779 this.unsetDragItem();
4780 // Return false to prevent propogation
4781 return false;
4782 };
4783
4784 /**
4785 * Handle dragleave event.
4786 *
4787 * @private
4788 */
4789 OO.ui.DraggableGroupElement.prototype.onDragLeave = function () {
4790 // This means the item was dragged outside the widget
4791 this.$placeholder
4792 .css( 'left', 0 )
4793 .addClass( 'oo-ui-element-hidden' );
4794 };
4795
4796 /**
4797 * Respond to dragover event
4798 *
4799 * @private
4800 * @param {jQuery.Event} event Event details
4801 */
4802 OO.ui.DraggableGroupElement.prototype.onDragOver = function ( e ) {
4803 var dragOverObj, $optionWidget, itemOffset, itemMidpoint, itemBoundingRect,
4804 itemSize, cssOutput, dragPosition, itemIndex, itemPosition,
4805 clientX = e.originalEvent.clientX,
4806 clientY = e.originalEvent.clientY;
4807
4808 // Get the OptionWidget item we are dragging over
4809 dragOverObj = this.getElementDocument().elementFromPoint( clientX, clientY );
4810 $optionWidget = $( dragOverObj ).closest( '.oo-ui-draggableElement' );
4811 if ( $optionWidget[ 0 ] ) {
4812 itemOffset = $optionWidget.offset();
4813 itemBoundingRect = $optionWidget[ 0 ].getBoundingClientRect();
4814 itemPosition = $optionWidget.position();
4815 itemIndex = $optionWidget.data( 'index' );
4816 }
4817
4818 if (
4819 itemOffset &&
4820 this.isDragging() &&
4821 itemIndex !== this.getDragItem().getIndex()
4822 ) {
4823 if ( this.orientation === 'horizontal' ) {
4824 // Calculate where the mouse is relative to the item width
4825 itemSize = itemBoundingRect.width;
4826 itemMidpoint = itemBoundingRect.left + itemSize / 2;
4827 dragPosition = clientX;
4828 // Which side of the item we hover over will dictate
4829 // where the placeholder will appear, on the left or
4830 // on the right
4831 cssOutput = {
4832 left: dragPosition < itemMidpoint ? itemPosition.left : itemPosition.left + itemSize,
4833 top: itemPosition.top
4834 };
4835 } else {
4836 // Calculate where the mouse is relative to the item height
4837 itemSize = itemBoundingRect.height;
4838 itemMidpoint = itemBoundingRect.top + itemSize / 2;
4839 dragPosition = clientY;
4840 // Which side of the item we hover over will dictate
4841 // where the placeholder will appear, on the top or
4842 // on the bottom
4843 cssOutput = {
4844 top: dragPosition < itemMidpoint ? itemPosition.top : itemPosition.top + itemSize,
4845 left: itemPosition.left
4846 };
4847 }
4848 // Store whether we are before or after an item to rearrange
4849 // For horizontal layout, we need to account for RTL, as this is flipped
4850 if ( this.orientation === 'horizontal' && this.$element.css( 'direction' ) === 'rtl' ) {
4851 this.sideInsertion = dragPosition < itemMidpoint ? 'after' : 'before';
4852 } else {
4853 this.sideInsertion = dragPosition < itemMidpoint ? 'before' : 'after';
4854 }
4855 // Add drop indicator between objects
4856 this.$placeholder
4857 .css( cssOutput )
4858 .removeClass( 'oo-ui-element-hidden' );
4859 } else {
4860 // This means the item was dragged outside the widget
4861 this.$placeholder
4862 .css( 'left', 0 )
4863 .addClass( 'oo-ui-element-hidden' );
4864 }
4865 // Prevent default
4866 e.preventDefault();
4867 };
4868
4869 /**
4870 * Set a dragged item
4871 *
4872 * @param {OO.ui.DraggableElement} item Dragged item
4873 */
4874 OO.ui.DraggableGroupElement.prototype.setDragItem = function ( item ) {
4875 this.dragItem = item;
4876 };
4877
4878 /**
4879 * Unset the current dragged item
4880 */
4881 OO.ui.DraggableGroupElement.prototype.unsetDragItem = function () {
4882 this.dragItem = null;
4883 this.itemDragOver = null;
4884 this.$placeholder.addClass( 'oo-ui-element-hidden' );
4885 this.sideInsertion = '';
4886 };
4887
4888 /**
4889 * Get the item that is currently being dragged.
4890 *
4891 * @return {OO.ui.DraggableElement|null} The currently dragged item, or `null` if no item is being dragged
4892 */
4893 OO.ui.DraggableGroupElement.prototype.getDragItem = function () {
4894 return this.dragItem;
4895 };
4896
4897 /**
4898 * Check if an item in the group is currently being dragged.
4899 *
4900 * @return {Boolean} Item is being dragged
4901 */
4902 OO.ui.DraggableGroupElement.prototype.isDragging = function () {
4903 return this.getDragItem() !== null;
4904 };
4905
4906 /**
4907 * IconElement is often mixed into other classes to generate an icon.
4908 * Icons are graphics, about the size of normal text. They are used to aid the user
4909 * in locating a control or to convey information in a space-efficient way. See the
4910 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
4911 * included in the library.
4912 *
4913 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4914 *
4915 * @abstract
4916 * @class
4917 *
4918 * @constructor
4919 * @param {Object} [config] Configuration options
4920 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
4921 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
4922 * the icon element be set to an existing icon instead of the one generated by this class, set a
4923 * value using a jQuery selection. For example:
4924 *
4925 * // Use a <div> tag instead of a <span>
4926 * $icon: $("<div>")
4927 * // Use an existing icon element instead of the one generated by the class
4928 * $icon: this.$element
4929 * // Use an icon element from a child widget
4930 * $icon: this.childwidget.$element
4931 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
4932 * symbolic names. A map is used for i18n purposes and contains a `default` icon
4933 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
4934 * by the user's language.
4935 *
4936 * Example of an i18n map:
4937 *
4938 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4939 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
4940 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
4941 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
4942 * text. The icon title is displayed when users move the mouse over the icon.
4943 */
4944 OO.ui.IconElement = function OoUiIconElement( config ) {
4945 // Configuration initialization
4946 config = config || {};
4947
4948 // Properties
4949 this.$icon = null;
4950 this.icon = null;
4951 this.iconTitle = null;
4952
4953 // Initialization
4954 this.setIcon( config.icon || this.constructor.static.icon );
4955 this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle );
4956 this.setIconElement( config.$icon || $( '<span>' ) );
4957 };
4958
4959 /* Setup */
4960
4961 OO.initClass( OO.ui.IconElement );
4962
4963 /* Static Properties */
4964
4965 /**
4966 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
4967 * for i18n purposes and contains a `default` icon name and additional names keyed by
4968 * language code. The `default` name is used when no icon is keyed by the user's language.
4969 *
4970 * Example of an i18n map:
4971 *
4972 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
4973 *
4974 * Note: the static property will be overridden if the #icon configuration is used.
4975 *
4976 * @static
4977 * @inheritable
4978 * @property {Object|string}
4979 */
4980 OO.ui.IconElement.static.icon = null;
4981
4982 /**
4983 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
4984 * function that returns title text, or `null` for no title.
4985 *
4986 * The static property will be overridden if the #iconTitle configuration is used.
4987 *
4988 * @static
4989 * @inheritable
4990 * @property {string|Function|null}
4991 */
4992 OO.ui.IconElement.static.iconTitle = null;
4993
4994 /* Methods */
4995
4996 /**
4997 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
4998 * applies to the specified icon element instead of the one created by the class. If an icon
4999 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
5000 * and mixin methods will no longer affect the element.
5001 *
5002 * @param {jQuery} $icon Element to use as icon
5003 */
5004 OO.ui.IconElement.prototype.setIconElement = function ( $icon ) {
5005 if ( this.$icon ) {
5006 this.$icon
5007 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon )
5008 .removeAttr( 'title' );
5009 }
5010
5011 this.$icon = $icon
5012 .addClass( 'oo-ui-iconElement-icon' )
5013 .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon );
5014 if ( this.iconTitle !== null ) {
5015 this.$icon.attr( 'title', this.iconTitle );
5016 }
5017 };
5018
5019 /**
5020 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
5021 * The icon parameter can also be set to a map of icon names. See the #icon config setting
5022 * for an example.
5023 *
5024 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
5025 * by language code, or `null` to remove the icon.
5026 * @chainable
5027 */
5028 OO.ui.IconElement.prototype.setIcon = function ( icon ) {
5029 icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon;
5030 icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null;
5031
5032 if ( this.icon !== icon ) {
5033 if ( this.$icon ) {
5034 if ( this.icon !== null ) {
5035 this.$icon.removeClass( 'oo-ui-icon-' + this.icon );
5036 }
5037 if ( icon !== null ) {
5038 this.$icon.addClass( 'oo-ui-icon-' + icon );
5039 }
5040 }
5041 this.icon = icon;
5042 }
5043
5044 this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon );
5045 this.updateThemeClasses();
5046
5047 return this;
5048 };
5049
5050 /**
5051 * Set the icon title. Use `null` to remove the title.
5052 *
5053 * @param {string|Function|null} iconTitle A text string used as the icon title,
5054 * a function that returns title text, or `null` for no title.
5055 * @chainable
5056 */
5057 OO.ui.IconElement.prototype.setIconTitle = function ( iconTitle ) {
5058 iconTitle = typeof iconTitle === 'function' ||
5059 ( typeof iconTitle === 'string' && iconTitle.length ) ?
5060 OO.ui.resolveMsg( iconTitle ) : null;
5061
5062 if ( this.iconTitle !== iconTitle ) {
5063 this.iconTitle = iconTitle;
5064 if ( this.$icon ) {
5065 if ( this.iconTitle !== null ) {
5066 this.$icon.attr( 'title', iconTitle );
5067 } else {
5068 this.$icon.removeAttr( 'title' );
5069 }
5070 }
5071 }
5072
5073 return this;
5074 };
5075
5076 /**
5077 * Get the symbolic name of the icon.
5078 *
5079 * @return {string} Icon name
5080 */
5081 OO.ui.IconElement.prototype.getIcon = function () {
5082 return this.icon;
5083 };
5084
5085 /**
5086 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
5087 *
5088 * @return {string} Icon title text
5089 */
5090 OO.ui.IconElement.prototype.getIconTitle = function () {
5091 return this.iconTitle;
5092 };
5093
5094 /**
5095 * IndicatorElement is often mixed into other classes to generate an indicator.
5096 * Indicators are small graphics that are generally used in two ways:
5097 *
5098 * - To draw attention to the status of an item. For example, an indicator might be
5099 * used to show that an item in a list has errors that need to be resolved.
5100 * - To clarify the function of a control that acts in an exceptional way (a button
5101 * that opens a menu instead of performing an action directly, for example).
5102 *
5103 * For a list of indicators included in the library, please see the
5104 * [OOjs UI documentation on MediaWiki] [1].
5105 *
5106 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5107 *
5108 * @abstract
5109 * @class
5110 *
5111 * @constructor
5112 * @param {Object} [config] Configuration options
5113 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
5114 * configuration is omitted, the indicator element will use a generated `<span>`.
5115 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5116 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
5117 * in the library.
5118 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
5119 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
5120 * or a function that returns title text. The indicator title is displayed when users move
5121 * the mouse over the indicator.
5122 */
5123 OO.ui.IndicatorElement = function OoUiIndicatorElement( config ) {
5124 // Configuration initialization
5125 config = config || {};
5126
5127 // Properties
5128 this.$indicator = null;
5129 this.indicator = null;
5130 this.indicatorTitle = null;
5131
5132 // Initialization
5133 this.setIndicator( config.indicator || this.constructor.static.indicator );
5134 this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle );
5135 this.setIndicatorElement( config.$indicator || $( '<span>' ) );
5136 };
5137
5138 /* Setup */
5139
5140 OO.initClass( OO.ui.IndicatorElement );
5141
5142 /* Static Properties */
5143
5144 /**
5145 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5146 * The static property will be overridden if the #indicator configuration is used.
5147 *
5148 * @static
5149 * @inheritable
5150 * @property {string|null}
5151 */
5152 OO.ui.IndicatorElement.static.indicator = null;
5153
5154 /**
5155 * A text string used as the indicator title, a function that returns title text, or `null`
5156 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
5157 *
5158 * @static
5159 * @inheritable
5160 * @property {string|Function|null}
5161 */
5162 OO.ui.IndicatorElement.static.indicatorTitle = null;
5163
5164 /* Methods */
5165
5166 /**
5167 * Set the indicator element.
5168 *
5169 * If an element is already set, it will be cleaned up before setting up the new element.
5170 *
5171 * @param {jQuery} $indicator Element to use as indicator
5172 */
5173 OO.ui.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) {
5174 if ( this.$indicator ) {
5175 this.$indicator
5176 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator )
5177 .removeAttr( 'title' );
5178 }
5179
5180 this.$indicator = $indicator
5181 .addClass( 'oo-ui-indicatorElement-indicator' )
5182 .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator );
5183 if ( this.indicatorTitle !== null ) {
5184 this.$indicator.attr( 'title', this.indicatorTitle );
5185 }
5186 };
5187
5188 /**
5189 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
5190 *
5191 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
5192 * @chainable
5193 */
5194 OO.ui.IndicatorElement.prototype.setIndicator = function ( indicator ) {
5195 indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null;
5196
5197 if ( this.indicator !== indicator ) {
5198 if ( this.$indicator ) {
5199 if ( this.indicator !== null ) {
5200 this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator );
5201 }
5202 if ( indicator !== null ) {
5203 this.$indicator.addClass( 'oo-ui-indicator-' + indicator );
5204 }
5205 }
5206 this.indicator = indicator;
5207 }
5208
5209 this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator );
5210 this.updateThemeClasses();
5211
5212 return this;
5213 };
5214
5215 /**
5216 * Set the indicator title.
5217 *
5218 * The title is displayed when a user moves the mouse over the indicator.
5219 *
5220 * @param {string|Function|null} indicator Indicator title text, a function that returns text, or
5221 * `null` for no indicator title
5222 * @chainable
5223 */
5224 OO.ui.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) {
5225 indicatorTitle = typeof indicatorTitle === 'function' ||
5226 ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ?
5227 OO.ui.resolveMsg( indicatorTitle ) : null;
5228
5229 if ( this.indicatorTitle !== indicatorTitle ) {
5230 this.indicatorTitle = indicatorTitle;
5231 if ( this.$indicator ) {
5232 if ( this.indicatorTitle !== null ) {
5233 this.$indicator.attr( 'title', indicatorTitle );
5234 } else {
5235 this.$indicator.removeAttr( 'title' );
5236 }
5237 }
5238 }
5239
5240 return this;
5241 };
5242
5243 /**
5244 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
5245 *
5246 * @return {string} Symbolic name of indicator
5247 */
5248 OO.ui.IndicatorElement.prototype.getIndicator = function () {
5249 return this.indicator;
5250 };
5251
5252 /**
5253 * Get the indicator title.
5254 *
5255 * The title is displayed when a user moves the mouse over the indicator.
5256 *
5257 * @return {string} Indicator title text
5258 */
5259 OO.ui.IndicatorElement.prototype.getIndicatorTitle = function () {
5260 return this.indicatorTitle;
5261 };
5262
5263 /**
5264 * LabelElement is often mixed into other classes to generate a label, which
5265 * helps identify the function of an interface element.
5266 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
5267 *
5268 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5269 *
5270 * @abstract
5271 * @class
5272 *
5273 * @constructor
5274 * @param {Object} [config] Configuration options
5275 * @cfg {jQuery} [$label] The label element created by the class. If this
5276 * configuration is omitted, the label element will use a generated `<span>`.
5277 * @cfg {jQuery|string|Function} [label] The label text. The label can be specified as a plaintext string,
5278 * a jQuery selection of elements, or a function that will produce a string in the future. See the
5279 * [OOjs UI documentation on MediaWiki] [2] for examples.
5280 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
5281 * @cfg {boolean} [autoFitLabel=true] Fit the label to the width of the parent element.
5282 * The label will be truncated to fit if necessary.
5283 */
5284 OO.ui.LabelElement = function OoUiLabelElement( config ) {
5285 // Configuration initialization
5286 config = config || {};
5287
5288 // Properties
5289 this.$label = null;
5290 this.label = null;
5291 this.autoFitLabel = config.autoFitLabel === undefined || !!config.autoFitLabel;
5292
5293 // Initialization
5294 this.setLabel( config.label || this.constructor.static.label );
5295 this.setLabelElement( config.$label || $( '<span>' ) );
5296 };
5297
5298 /* Setup */
5299
5300 OO.initClass( OO.ui.LabelElement );
5301
5302 /* Events */
5303
5304 /**
5305 * @event labelChange
5306 * @param {string} value
5307 */
5308
5309 /* Static Properties */
5310
5311 /**
5312 * The label text. The label can be specified as a plaintext string, a function that will
5313 * produce a string in the future, or `null` for no label. The static value will
5314 * be overridden if a label is specified with the #label config option.
5315 *
5316 * @static
5317 * @inheritable
5318 * @property {string|Function|null}
5319 */
5320 OO.ui.LabelElement.static.label = null;
5321
5322 /* Methods */
5323
5324 /**
5325 * Set the label element.
5326 *
5327 * If an element is already set, it will be cleaned up before setting up the new element.
5328 *
5329 * @param {jQuery} $label Element to use as label
5330 */
5331 OO.ui.LabelElement.prototype.setLabelElement = function ( $label ) {
5332 if ( this.$label ) {
5333 this.$label.removeClass( 'oo-ui-labelElement-label' ).empty();
5334 }
5335
5336 this.$label = $label.addClass( 'oo-ui-labelElement-label' );
5337 this.setLabelContent( this.label );
5338 };
5339
5340 /**
5341 * Set the label.
5342 *
5343 * An empty string will result in the label being hidden. A string containing only whitespace will
5344 * be converted to a single `&nbsp;`.
5345 *
5346 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
5347 * text; or null for no label
5348 * @chainable
5349 */
5350 OO.ui.LabelElement.prototype.setLabel = function ( label ) {
5351 label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label;
5352 label = ( ( typeof label === 'string' && label.length ) || label instanceof jQuery || label instanceof OO.ui.HtmlSnippet ) ? label : null;
5353
5354 this.$element.toggleClass( 'oo-ui-labelElement', !!label );
5355
5356 if ( this.label !== label ) {
5357 if ( this.$label ) {
5358 this.setLabelContent( label );
5359 }
5360 this.label = label;
5361 this.emit( 'labelChange' );
5362 }
5363
5364 return this;
5365 };
5366
5367 /**
5368 * Get the label.
5369 *
5370 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
5371 * text; or null for no label
5372 */
5373 OO.ui.LabelElement.prototype.getLabel = function () {
5374 return this.label;
5375 };
5376
5377 /**
5378 * Fit the label.
5379 *
5380 * @chainable
5381 */
5382 OO.ui.LabelElement.prototype.fitLabel = function () {
5383 if ( this.$label && this.$label.autoEllipsis && this.autoFitLabel ) {
5384 this.$label.autoEllipsis( { hasSpan: false, tooltip: true } );
5385 }
5386
5387 return this;
5388 };
5389
5390 /**
5391 * Set the content of the label.
5392 *
5393 * Do not call this method until after the label element has been set by #setLabelElement.
5394 *
5395 * @private
5396 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
5397 * text; or null for no label
5398 */
5399 OO.ui.LabelElement.prototype.setLabelContent = function ( label ) {
5400 if ( typeof label === 'string' ) {
5401 if ( label.match( /^\s*$/ ) ) {
5402 // Convert whitespace only string to a single non-breaking space
5403 this.$label.html( '&nbsp;' );
5404 } else {
5405 this.$label.text( label );
5406 }
5407 } else if ( label instanceof OO.ui.HtmlSnippet ) {
5408 this.$label.html( label.toString() );
5409 } else if ( label instanceof jQuery ) {
5410 this.$label.empty().append( label );
5411 } else {
5412 this.$label.empty();
5413 }
5414 };
5415
5416 /**
5417 * LookupElement is a mixin that creates a {@link OO.ui.TextInputMenuSelectWidget menu} of suggested values for
5418 * a {@link OO.ui.TextInputWidget text input widget}. Suggested values are based on the characters the user types
5419 * into the text input field and, in general, the menu is only displayed when the user types. If a suggested value is chosen
5420 * from the lookup menu, that value becomes the value of the input field.
5421 *
5422 * Note that a new menu of suggested items is displayed when a value is chosen from the lookup menu. If this is
5423 * not the desired behavior, disable lookup menus with the #setLookupsDisabled method, then set the value, then
5424 * re-enable lookups.
5425 *
5426 * See the [OOjs UI demos][1] for an example.
5427 *
5428 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/index.html#widgets-apex-vector-ltr
5429 *
5430 * @class
5431 * @abstract
5432 *
5433 * @constructor
5434 * @param {Object} [config] Configuration options
5435 * @cfg {jQuery} [$overlay] Overlay for the lookup menu; defaults to relative positioning
5436 * @cfg {jQuery} [$container=this.$element] The container element. The lookup menu is rendered beneath the specified element.
5437 * @cfg {boolean} [allowSuggestionsWhenEmpty=false] Request and display a lookup menu when the text input is empty.
5438 * By default, the lookup menu is not generated and displayed until the user begins to type.
5439 */
5440 OO.ui.LookupElement = function OoUiLookupElement( config ) {
5441 // Configuration initialization
5442 config = config || {};
5443
5444 // Properties
5445 this.$overlay = config.$overlay || this.$element;
5446 this.lookupMenu = new OO.ui.TextInputMenuSelectWidget( this, {
5447 widget: this,
5448 input: this,
5449 $container: config.$container
5450 } );
5451
5452 this.allowSuggestionsWhenEmpty = config.allowSuggestionsWhenEmpty || false;
5453
5454 this.lookupCache = {};
5455 this.lookupQuery = null;
5456 this.lookupRequest = null;
5457 this.lookupsDisabled = false;
5458 this.lookupInputFocused = false;
5459
5460 // Events
5461 this.$input.on( {
5462 focus: this.onLookupInputFocus.bind( this ),
5463 blur: this.onLookupInputBlur.bind( this ),
5464 mousedown: this.onLookupInputMouseDown.bind( this )
5465 } );
5466 this.connect( this, { change: 'onLookupInputChange' } );
5467 this.lookupMenu.connect( this, {
5468 toggle: 'onLookupMenuToggle',
5469 choose: 'onLookupMenuItemChoose'
5470 } );
5471
5472 // Initialization
5473 this.$element.addClass( 'oo-ui-lookupElement' );
5474 this.lookupMenu.$element.addClass( 'oo-ui-lookupElement-menu' );
5475 this.$overlay.append( this.lookupMenu.$element );
5476 };
5477
5478 /* Methods */
5479
5480 /**
5481 * Handle input focus event.
5482 *
5483 * @protected
5484 * @param {jQuery.Event} e Input focus event
5485 */
5486 OO.ui.LookupElement.prototype.onLookupInputFocus = function () {
5487 this.lookupInputFocused = true;
5488 this.populateLookupMenu();
5489 };
5490
5491 /**
5492 * Handle input blur event.
5493 *
5494 * @protected
5495 * @param {jQuery.Event} e Input blur event
5496 */
5497 OO.ui.LookupElement.prototype.onLookupInputBlur = function () {
5498 this.closeLookupMenu();
5499 this.lookupInputFocused = false;
5500 };
5501
5502 /**
5503 * Handle input mouse down event.
5504 *
5505 * @protected
5506 * @param {jQuery.Event} e Input mouse down event
5507 */
5508 OO.ui.LookupElement.prototype.onLookupInputMouseDown = function () {
5509 // Only open the menu if the input was already focused.
5510 // This way we allow the user to open the menu again after closing it with Esc
5511 // by clicking in the input. Opening (and populating) the menu when initially
5512 // clicking into the input is handled by the focus handler.
5513 if ( this.lookupInputFocused && !this.lookupMenu.isVisible() ) {
5514 this.populateLookupMenu();
5515 }
5516 };
5517
5518 /**
5519 * Handle input change event.
5520 *
5521 * @protected
5522 * @param {string} value New input value
5523 */
5524 OO.ui.LookupElement.prototype.onLookupInputChange = function () {
5525 if ( this.lookupInputFocused ) {
5526 this.populateLookupMenu();
5527 }
5528 };
5529
5530 /**
5531 * Handle the lookup menu being shown/hidden.
5532 *
5533 * @protected
5534 * @param {boolean} visible Whether the lookup menu is now visible.
5535 */
5536 OO.ui.LookupElement.prototype.onLookupMenuToggle = function ( visible ) {
5537 if ( !visible ) {
5538 // When the menu is hidden, abort any active request and clear the menu.
5539 // This has to be done here in addition to closeLookupMenu(), because
5540 // MenuSelectWidget will close itself when the user presses Esc.
5541 this.abortLookupRequest();
5542 this.lookupMenu.clearItems();
5543 }
5544 };
5545
5546 /**
5547 * Handle menu item 'choose' event, updating the text input value to the value of the clicked item.
5548 *
5549 * @protected
5550 * @param {OO.ui.MenuOptionWidget|null} item Selected item
5551 */
5552 OO.ui.LookupElement.prototype.onLookupMenuItemChoose = function ( item ) {
5553 if ( item ) {
5554 this.setValue( item.getData() );
5555 }
5556 };
5557
5558 /**
5559 * Get lookup menu.
5560 *
5561 * @private
5562 * @return {OO.ui.TextInputMenuSelectWidget}
5563 */
5564 OO.ui.LookupElement.prototype.getLookupMenu = function () {
5565 return this.lookupMenu;
5566 };
5567
5568 /**
5569 * Disable or re-enable lookups.
5570 *
5571 * When lookups are disabled, calls to #populateLookupMenu will be ignored.
5572 *
5573 * @param {boolean} disabled Disable lookups
5574 */
5575 OO.ui.LookupElement.prototype.setLookupsDisabled = function ( disabled ) {
5576 this.lookupsDisabled = !!disabled;
5577 };
5578
5579 /**
5580 * Open the menu. If there are no entries in the menu, this does nothing.
5581 *
5582 * @private
5583 * @chainable
5584 */
5585 OO.ui.LookupElement.prototype.openLookupMenu = function () {
5586 if ( !this.lookupMenu.isEmpty() ) {
5587 this.lookupMenu.toggle( true );
5588 }
5589 return this;
5590 };
5591
5592 /**
5593 * Close the menu, empty it, and abort any pending request.
5594 *
5595 * @private
5596 * @chainable
5597 */
5598 OO.ui.LookupElement.prototype.closeLookupMenu = function () {
5599 this.lookupMenu.toggle( false );
5600 this.abortLookupRequest();
5601 this.lookupMenu.clearItems();
5602 return this;
5603 };
5604
5605 /**
5606 * Request menu items based on the input's current value, and when they arrive,
5607 * populate the menu with these items and show the menu.
5608 *
5609 * If lookups have been disabled with #setLookupsDisabled, this function does nothing.
5610 *
5611 * @private
5612 * @chainable
5613 */
5614 OO.ui.LookupElement.prototype.populateLookupMenu = function () {
5615 var widget = this,
5616 value = this.getValue();
5617
5618 if ( this.lookupsDisabled ) {
5619 return;
5620 }
5621
5622 // If the input is empty, clear the menu, unless suggestions when empty are allowed.
5623 if ( !this.allowSuggestionsWhenEmpty && value === '' ) {
5624 this.closeLookupMenu();
5625 // Skip population if there is already a request pending for the current value
5626 } else if ( value !== this.lookupQuery ) {
5627 this.getLookupMenuItems()
5628 .done( function ( items ) {
5629 widget.lookupMenu.clearItems();
5630 if ( items.length ) {
5631 widget.lookupMenu
5632 .addItems( items )
5633 .toggle( true );
5634 widget.initializeLookupMenuSelection();
5635 } else {
5636 widget.lookupMenu.toggle( false );
5637 }
5638 } )
5639 .fail( function () {
5640 widget.lookupMenu.clearItems();
5641 } );
5642 }
5643
5644 return this;
5645 };
5646
5647 /**
5648 * Select and highlight the first selectable item in the menu.
5649 *
5650 * @private
5651 * @chainable
5652 */
5653 OO.ui.LookupElement.prototype.initializeLookupMenuSelection = function () {
5654 if ( !this.lookupMenu.getSelectedItem() ) {
5655 this.lookupMenu.selectItem( this.lookupMenu.getFirstSelectableItem() );
5656 }
5657 this.lookupMenu.highlightItem( this.lookupMenu.getSelectedItem() );
5658 };
5659
5660 /**
5661 * Get lookup menu items for the current query.
5662 *
5663 * @private
5664 * @return {jQuery.Promise} Promise object which will be passed menu items as the first argument of
5665 * the done event. If the request was aborted to make way for a subsequent request, this promise
5666 * will not be rejected: it will remain pending forever.
5667 */
5668 OO.ui.LookupElement.prototype.getLookupMenuItems = function () {
5669 var widget = this,
5670 value = this.getValue(),
5671 deferred = $.Deferred(),
5672 ourRequest;
5673
5674 this.abortLookupRequest();
5675 if ( Object.prototype.hasOwnProperty.call( this.lookupCache, value ) ) {
5676 deferred.resolve( this.getLookupMenuOptionsFromData( this.lookupCache[ value ] ) );
5677 } else {
5678 this.pushPending();
5679 this.lookupQuery = value;
5680 ourRequest = this.lookupRequest = this.getLookupRequest();
5681 ourRequest
5682 .always( function () {
5683 // We need to pop pending even if this is an old request, otherwise
5684 // the widget will remain pending forever.
5685 // TODO: this assumes that an aborted request will fail or succeed soon after
5686 // being aborted, or at least eventually. It would be nice if we could popPending()
5687 // at abort time, but only if we knew that we hadn't already called popPending()
5688 // for that request.
5689 widget.popPending();
5690 } )
5691 .done( function ( response ) {
5692 // If this is an old request (and aborting it somehow caused it to still succeed),
5693 // ignore its success completely
5694 if ( ourRequest === widget.lookupRequest ) {
5695 widget.lookupQuery = null;
5696 widget.lookupRequest = null;
5697 widget.lookupCache[ value ] = widget.getLookupCacheDataFromResponse( response );
5698 deferred.resolve( widget.getLookupMenuOptionsFromData( widget.lookupCache[ value ] ) );
5699 }
5700 } )
5701 .fail( function () {
5702 // If this is an old request (or a request failing because it's being aborted),
5703 // ignore its failure completely
5704 if ( ourRequest === widget.lookupRequest ) {
5705 widget.lookupQuery = null;
5706 widget.lookupRequest = null;
5707 deferred.reject();
5708 }
5709 } );
5710 }
5711 return deferred.promise();
5712 };
5713
5714 /**
5715 * Abort the currently pending lookup request, if any.
5716 *
5717 * @private
5718 */
5719 OO.ui.LookupElement.prototype.abortLookupRequest = function () {
5720 var oldRequest = this.lookupRequest;
5721 if ( oldRequest ) {
5722 // First unset this.lookupRequest to the fail handler will notice
5723 // that the request is no longer current
5724 this.lookupRequest = null;
5725 this.lookupQuery = null;
5726 oldRequest.abort();
5727 }
5728 };
5729
5730 /**
5731 * Get a new request object of the current lookup query value.
5732 *
5733 * @protected
5734 * @abstract
5735 * @return {jQuery.Promise} jQuery AJAX object, or promise object with an .abort() method
5736 */
5737 OO.ui.LookupElement.prototype.getLookupRequest = function () {
5738 // Stub, implemented in subclass
5739 return null;
5740 };
5741
5742 /**
5743 * Pre-process data returned by the request from #getLookupRequest.
5744 *
5745 * The return value of this function will be cached, and any further queries for the given value
5746 * will use the cache rather than doing API requests.
5747 *
5748 * @protected
5749 * @abstract
5750 * @param {Mixed} response Response from server
5751 * @return {Mixed} Cached result data
5752 */
5753 OO.ui.LookupElement.prototype.getLookupCacheDataFromResponse = function () {
5754 // Stub, implemented in subclass
5755 return [];
5756 };
5757
5758 /**
5759 * Get a list of menu option widgets from the (possibly cached) data returned by
5760 * #getLookupCacheDataFromResponse.
5761 *
5762 * @protected
5763 * @abstract
5764 * @param {Mixed} data Cached result data, usually an array
5765 * @return {OO.ui.MenuOptionWidget[]} Menu items
5766 */
5767 OO.ui.LookupElement.prototype.getLookupMenuOptionsFromData = function () {
5768 // Stub, implemented in subclass
5769 return [];
5770 };
5771
5772 /**
5773 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5774 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5775 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5776 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5777 *
5778 * @abstract
5779 * @class
5780 *
5781 * @constructor
5782 * @param {Object} [config] Configuration options
5783 * @cfg {Object} [popup] Configuration to pass to popup
5784 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5785 */
5786 OO.ui.PopupElement = function OoUiPopupElement( config ) {
5787 // Configuration initialization
5788 config = config || {};
5789
5790 // Properties
5791 this.popup = new OO.ui.PopupWidget( $.extend(
5792 { autoClose: true },
5793 config.popup,
5794 { $autoCloseIgnore: this.$element }
5795 ) );
5796 };
5797
5798 /* Methods */
5799
5800 /**
5801 * Get popup.
5802 *
5803 * @return {OO.ui.PopupWidget} Popup widget
5804 */
5805 OO.ui.PopupElement.prototype.getPopup = function () {
5806 return this.popup;
5807 };
5808
5809 /**
5810 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
5811 * additional functionality to an element created by another class. The class provides
5812 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
5813 * which are used to customize the look and feel of a widget to better describe its
5814 * importance and functionality.
5815 *
5816 * The library currently contains the following styling flags for general use:
5817 *
5818 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
5819 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
5820 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
5821 *
5822 * The flags affect the appearance of the buttons:
5823 *
5824 * @example
5825 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
5826 * var button1 = new OO.ui.ButtonWidget( {
5827 * label: 'Constructive',
5828 * flags: 'constructive'
5829 * } );
5830 * var button2 = new OO.ui.ButtonWidget( {
5831 * label: 'Destructive',
5832 * flags: 'destructive'
5833 * } );
5834 * var button3 = new OO.ui.ButtonWidget( {
5835 * label: 'Progressive',
5836 * flags: 'progressive'
5837 * } );
5838 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
5839 *
5840 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
5841 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
5842 *
5843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5844 *
5845 * @abstract
5846 * @class
5847 *
5848 * @constructor
5849 * @param {Object} [config] Configuration options
5850 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
5851 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
5852 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
5853 * @cfg {jQuery} [$flagged] The flagged element. By default,
5854 * the flagged functionality is applied to the element created by the class ($element).
5855 * If a different element is specified, the flagged functionality will be applied to it instead.
5856 */
5857 OO.ui.FlaggedElement = function OoUiFlaggedElement( config ) {
5858 // Configuration initialization
5859 config = config || {};
5860
5861 // Properties
5862 this.flags = {};
5863 this.$flagged = null;
5864
5865 // Initialization
5866 this.setFlags( config.flags );
5867 this.setFlaggedElement( config.$flagged || this.$element );
5868 };
5869
5870 /* Events */
5871
5872 /**
5873 * @event flag
5874 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
5875 * parameter contains the name of each modified flag and indicates whether it was
5876 * added or removed.
5877 *
5878 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
5879 * that the flag was added, `false` that the flag was removed.
5880 */
5881
5882 /* Methods */
5883
5884 /**
5885 * Set the flagged element.
5886 *
5887 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
5888 * If an element is already set, the method will remove the mixin’s effect on that element.
5889 *
5890 * @param {jQuery} $flagged Element that should be flagged
5891 */
5892 OO.ui.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) {
5893 var classNames = Object.keys( this.flags ).map( function ( flag ) {
5894 return 'oo-ui-flaggedElement-' + flag;
5895 } ).join( ' ' );
5896
5897 if ( this.$flagged ) {
5898 this.$flagged.removeClass( classNames );
5899 }
5900
5901 this.$flagged = $flagged.addClass( classNames );
5902 };
5903
5904 /**
5905 * Check if the specified flag is set.
5906 *
5907 * @param {string} flag Name of flag
5908 * @return {boolean} The flag is set
5909 */
5910 OO.ui.FlaggedElement.prototype.hasFlag = function ( flag ) {
5911 return flag in this.flags;
5912 };
5913
5914 /**
5915 * Get the names of all flags set.
5916 *
5917 * @return {string[]} Flag names
5918 */
5919 OO.ui.FlaggedElement.prototype.getFlags = function () {
5920 return Object.keys( this.flags );
5921 };
5922
5923 /**
5924 * Clear all flags.
5925 *
5926 * @chainable
5927 * @fires flag
5928 */
5929 OO.ui.FlaggedElement.prototype.clearFlags = function () {
5930 var flag, className,
5931 changes = {},
5932 remove = [],
5933 classPrefix = 'oo-ui-flaggedElement-';
5934
5935 for ( flag in this.flags ) {
5936 className = classPrefix + flag;
5937 changes[ flag ] = false;
5938 delete this.flags[ flag ];
5939 remove.push( className );
5940 }
5941
5942 if ( this.$flagged ) {
5943 this.$flagged.removeClass( remove.join( ' ' ) );
5944 }
5945
5946 this.updateThemeClasses();
5947 this.emit( 'flag', changes );
5948
5949 return this;
5950 };
5951
5952 /**
5953 * Add one or more flags.
5954 *
5955 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
5956 * or an object keyed by flag name with a boolean value that indicates whether the flag should
5957 * be added (`true`) or removed (`false`).
5958 * @chainable
5959 * @fires flag
5960 */
5961 OO.ui.FlaggedElement.prototype.setFlags = function ( flags ) {
5962 var i, len, flag, className,
5963 changes = {},
5964 add = [],
5965 remove = [],
5966 classPrefix = 'oo-ui-flaggedElement-';
5967
5968 if ( typeof flags === 'string' ) {
5969 className = classPrefix + flags;
5970 // Set
5971 if ( !this.flags[ flags ] ) {
5972 this.flags[ flags ] = true;
5973 add.push( className );
5974 }
5975 } else if ( Array.isArray( flags ) ) {
5976 for ( i = 0, len = flags.length; i < len; i++ ) {
5977 flag = flags[ i ];
5978 className = classPrefix + flag;
5979 // Set
5980 if ( !this.flags[ flag ] ) {
5981 changes[ flag ] = true;
5982 this.flags[ flag ] = true;
5983 add.push( className );
5984 }
5985 }
5986 } else if ( OO.isPlainObject( flags ) ) {
5987 for ( flag in flags ) {
5988 className = classPrefix + flag;
5989 if ( flags[ flag ] ) {
5990 // Set
5991 if ( !this.flags[ flag ] ) {
5992 changes[ flag ] = true;
5993 this.flags[ flag ] = true;
5994 add.push( className );
5995 }
5996 } else {
5997 // Remove
5998 if ( this.flags[ flag ] ) {
5999 changes[ flag ] = false;
6000 delete this.flags[ flag ];
6001 remove.push( className );
6002 }
6003 }
6004 }
6005 }
6006
6007 if ( this.$flagged ) {
6008 this.$flagged
6009 .addClass( add.join( ' ' ) )
6010 .removeClass( remove.join( ' ' ) );
6011 }
6012
6013 this.updateThemeClasses();
6014 this.emit( 'flag', changes );
6015
6016 return this;
6017 };
6018
6019 /**
6020 * TitledElement is mixed into other classes to provide a `title` attribute.
6021 * Titles are rendered by the browser and are made visible when the user moves
6022 * the mouse over the element. Titles are not visible on touch devices.
6023 *
6024 * @example
6025 * // TitledElement provides a 'title' attribute to the
6026 * // ButtonWidget class
6027 * var button = new OO.ui.ButtonWidget( {
6028 * label: 'Button with Title',
6029 * title: 'I am a button'
6030 * } );
6031 * $( 'body' ).append( button.$element );
6032 *
6033 * @abstract
6034 * @class
6035 *
6036 * @constructor
6037 * @param {Object} [config] Configuration options
6038 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
6039 * If this config is omitted, the title functionality is applied to $element, the
6040 * element created by the class.
6041 * @cfg {string|Function} [title] The title text or a function that returns text. If
6042 * this config is omitted, the value of the {@link #static-title static title} property is used.
6043 */
6044 OO.ui.TitledElement = function OoUiTitledElement( config ) {
6045 // Configuration initialization
6046 config = config || {};
6047
6048 // Properties
6049 this.$titled = null;
6050 this.title = null;
6051
6052 // Initialization
6053 this.setTitle( config.title || this.constructor.static.title );
6054 this.setTitledElement( config.$titled || this.$element );
6055 };
6056
6057 /* Setup */
6058
6059 OO.initClass( OO.ui.TitledElement );
6060
6061 /* Static Properties */
6062
6063 /**
6064 * The title text, a function that returns text, or `null` for no title. The value of the static property
6065 * is overridden if the #title config option is used.
6066 *
6067 * @static
6068 * @inheritable
6069 * @property {string|Function|null}
6070 */
6071 OO.ui.TitledElement.static.title = null;
6072
6073 /* Methods */
6074
6075 /**
6076 * Set the titled element.
6077 *
6078 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
6079 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
6080 *
6081 * @param {jQuery} $titled Element that should use the 'titled' functionality
6082 */
6083 OO.ui.TitledElement.prototype.setTitledElement = function ( $titled ) {
6084 if ( this.$titled ) {
6085 this.$titled.removeAttr( 'title' );
6086 }
6087
6088 this.$titled = $titled;
6089 if ( this.title ) {
6090 this.$titled.attr( 'title', this.title );
6091 }
6092 };
6093
6094 /**
6095 * Set title.
6096 *
6097 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
6098 * @chainable
6099 */
6100 OO.ui.TitledElement.prototype.setTitle = function ( title ) {
6101 title = typeof title === 'string' ? OO.ui.resolveMsg( title ) : null;
6102
6103 if ( this.title !== title ) {
6104 if ( this.$titled ) {
6105 if ( title !== null ) {
6106 this.$titled.attr( 'title', title );
6107 } else {
6108 this.$titled.removeAttr( 'title' );
6109 }
6110 }
6111 this.title = title;
6112 }
6113
6114 return this;
6115 };
6116
6117 /**
6118 * Get title.
6119 *
6120 * @return {string} Title string
6121 */
6122 OO.ui.TitledElement.prototype.getTitle = function () {
6123 return this.title;
6124 };
6125
6126 /**
6127 * Element that can be automatically clipped to visible boundaries.
6128 *
6129 * Whenever the element's natural height changes, you have to call
6130 * #clip to make sure it's still clipping correctly.
6131 *
6132 * @abstract
6133 * @class
6134 *
6135 * @constructor
6136 * @param {Object} [config] Configuration options
6137 * @cfg {jQuery} [$clippable] Nodes to clip, assigned to #$clippable, omit to use #$element
6138 */
6139 OO.ui.ClippableElement = function OoUiClippableElement( config ) {
6140 // Configuration initialization
6141 config = config || {};
6142
6143 // Properties
6144 this.$clippable = null;
6145 this.clipping = false;
6146 this.clippedHorizontally = false;
6147 this.clippedVertically = false;
6148 this.$clippableContainer = null;
6149 this.$clippableScroller = null;
6150 this.$clippableWindow = null;
6151 this.idealWidth = null;
6152 this.idealHeight = null;
6153 this.onClippableContainerScrollHandler = this.clip.bind( this );
6154 this.onClippableWindowResizeHandler = this.clip.bind( this );
6155
6156 // Initialization
6157 this.setClippableElement( config.$clippable || this.$element );
6158 };
6159
6160 /* Methods */
6161
6162 /**
6163 * Set clippable element.
6164 *
6165 * If an element is already set, it will be cleaned up before setting up the new element.
6166 *
6167 * @param {jQuery} $clippable Element to make clippable
6168 */
6169 OO.ui.ClippableElement.prototype.setClippableElement = function ( $clippable ) {
6170 if ( this.$clippable ) {
6171 this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' );
6172 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6173 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6174 }
6175
6176 this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' );
6177 this.clip();
6178 };
6179
6180 /**
6181 * Toggle clipping.
6182 *
6183 * Do not turn clipping on until after the element is attached to the DOM and visible.
6184 *
6185 * @param {boolean} [clipping] Enable clipping, omit to toggle
6186 * @chainable
6187 */
6188 OO.ui.ClippableElement.prototype.toggleClipping = function ( clipping ) {
6189 clipping = clipping === undefined ? !this.clipping : !!clipping;
6190
6191 if ( this.clipping !== clipping ) {
6192 this.clipping = clipping;
6193 if ( clipping ) {
6194 this.$clippableContainer = $( this.getClosestScrollableElementContainer() );
6195 // If the clippable container is the root, we have to listen to scroll events and check
6196 // jQuery.scrollTop on the window because of browser inconsistencies
6197 this.$clippableScroller = this.$clippableContainer.is( 'html, body' ) ?
6198 $( OO.ui.Element.static.getWindow( this.$clippableContainer ) ) :
6199 this.$clippableContainer;
6200 this.$clippableScroller.on( 'scroll', this.onClippableContainerScrollHandler );
6201 this.$clippableWindow = $( this.getElementWindow() )
6202 .on( 'resize', this.onClippableWindowResizeHandler );
6203 // Initial clip after visible
6204 this.clip();
6205 } else {
6206 this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } );
6207 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6208
6209 this.$clippableContainer = null;
6210 this.$clippableScroller.off( 'scroll', this.onClippableContainerScrollHandler );
6211 this.$clippableScroller = null;
6212 this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler );
6213 this.$clippableWindow = null;
6214 }
6215 }
6216
6217 return this;
6218 };
6219
6220 /**
6221 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
6222 *
6223 * @return {boolean} Element will be clipped to the visible area
6224 */
6225 OO.ui.ClippableElement.prototype.isClipping = function () {
6226 return this.clipping;
6227 };
6228
6229 /**
6230 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
6231 *
6232 * @return {boolean} Part of the element is being clipped
6233 */
6234 OO.ui.ClippableElement.prototype.isClipped = function () {
6235 return this.clippedHorizontally || this.clippedVertically;
6236 };
6237
6238 /**
6239 * Check if the right of the element is being clipped by the nearest scrollable container.
6240 *
6241 * @return {boolean} Part of the element is being clipped
6242 */
6243 OO.ui.ClippableElement.prototype.isClippedHorizontally = function () {
6244 return this.clippedHorizontally;
6245 };
6246
6247 /**
6248 * Check if the bottom of the element is being clipped by the nearest scrollable container.
6249 *
6250 * @return {boolean} Part of the element is being clipped
6251 */
6252 OO.ui.ClippableElement.prototype.isClippedVertically = function () {
6253 return this.clippedVertically;
6254 };
6255
6256 /**
6257 * Set the ideal size. These are the dimensions the element will have when it's not being clipped.
6258 *
6259 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
6260 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
6261 */
6262 OO.ui.ClippableElement.prototype.setIdealSize = function ( width, height ) {
6263 this.idealWidth = width;
6264 this.idealHeight = height;
6265
6266 if ( !this.clipping ) {
6267 // Update dimensions
6268 this.$clippable.css( { width: width, height: height } );
6269 }
6270 // While clipping, idealWidth and idealHeight are not considered
6271 };
6272
6273 /**
6274 * Clip element to visible boundaries and allow scrolling when needed. Call this method when
6275 * the element's natural height changes.
6276 *
6277 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
6278 * overlapped by, the visible area of the nearest scrollable container.
6279 *
6280 * @chainable
6281 */
6282 OO.ui.ClippableElement.prototype.clip = function () {
6283 if ( !this.clipping ) {
6284 // this.$clippableContainer and this.$clippableWindow are null, so the below will fail
6285 return this;
6286 }
6287
6288 var buffer = 7, // Chosen by fair dice roll
6289 cOffset = this.$clippable.offset(),
6290 $container = this.$clippableContainer.is( 'html, body' ) ?
6291 this.$clippableWindow : this.$clippableContainer,
6292 ccOffset = $container.offset() || { top: 0, left: 0 },
6293 ccHeight = $container.innerHeight() - buffer,
6294 ccWidth = $container.innerWidth() - buffer,
6295 cHeight = this.$clippable.outerHeight() + buffer,
6296 cWidth = this.$clippable.outerWidth() + buffer,
6297 scrollTop = this.$clippableScroller.scrollTop(),
6298 scrollLeft = this.$clippableScroller.scrollLeft(),
6299 desiredWidth = cOffset.left < 0 ?
6300 cWidth + cOffset.left :
6301 ( ccOffset.left + scrollLeft + ccWidth ) - cOffset.left,
6302 desiredHeight = cOffset.top < 0 ?
6303 cHeight + cOffset.top :
6304 ( ccOffset.top + scrollTop + ccHeight ) - cOffset.top,
6305 naturalWidth = this.$clippable.prop( 'scrollWidth' ),
6306 naturalHeight = this.$clippable.prop( 'scrollHeight' ),
6307 clipWidth = desiredWidth < naturalWidth,
6308 clipHeight = desiredHeight < naturalHeight;
6309
6310 if ( clipWidth ) {
6311 this.$clippable.css( { overflowX: 'scroll', width: desiredWidth } );
6312 } else {
6313 this.$clippable.css( { width: this.idealWidth || '', overflowX: '' } );
6314 }
6315 if ( clipHeight ) {
6316 this.$clippable.css( { overflowY: 'scroll', height: desiredHeight } );
6317 } else {
6318 this.$clippable.css( { height: this.idealHeight || '', overflowY: '' } );
6319 }
6320
6321 // If we stopped clipping in at least one of the dimensions
6322 if ( !clipWidth || !clipHeight ) {
6323 OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] );
6324 }
6325
6326 this.clippedHorizontally = clipWidth;
6327 this.clippedVertically = clipHeight;
6328
6329 return this;
6330 };
6331
6332 /**
6333 * Generic toolbar tool.
6334 *
6335 * @abstract
6336 * @class
6337 * @extends OO.ui.Widget
6338 * @mixins OO.ui.IconElement
6339 * @mixins OO.ui.FlaggedElement
6340 *
6341 * @constructor
6342 * @param {OO.ui.ToolGroup} toolGroup
6343 * @param {Object} [config] Configuration options
6344 * @cfg {string|Function} [title] Title text or a function that returns text
6345 */
6346 OO.ui.Tool = function OoUiTool( toolGroup, config ) {
6347 // Allow passing positional parameters inside the config object
6348 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
6349 config = toolGroup;
6350 toolGroup = config.toolGroup;
6351 }
6352
6353 // Configuration initialization
6354 config = config || {};
6355
6356 // Parent constructor
6357 OO.ui.Tool.super.call( this, config );
6358
6359 // Mixin constructors
6360 OO.ui.IconElement.call( this, config );
6361 OO.ui.FlaggedElement.call( this, config );
6362
6363 // Properties
6364 this.toolGroup = toolGroup;
6365 this.toolbar = this.toolGroup.getToolbar();
6366 this.active = false;
6367 this.$title = $( '<span>' );
6368 this.$accel = $( '<span>' );
6369 this.$link = $( '<a>' );
6370 this.title = null;
6371
6372 // Events
6373 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
6374
6375 // Initialization
6376 this.$title.addClass( 'oo-ui-tool-title' );
6377 this.$accel
6378 .addClass( 'oo-ui-tool-accel' )
6379 .prop( {
6380 // This may need to be changed if the key names are ever localized,
6381 // but for now they are essentially written in English
6382 dir: 'ltr',
6383 lang: 'en'
6384 } );
6385 this.$link
6386 .addClass( 'oo-ui-tool-link' )
6387 .append( this.$icon, this.$title, this.$accel )
6388 .prop( 'tabIndex', 0 )
6389 .attr( 'role', 'button' );
6390 this.$element
6391 .data( 'oo-ui-tool', this )
6392 .addClass(
6393 'oo-ui-tool ' + 'oo-ui-tool-name-' +
6394 this.constructor.static.name.replace( /^([^\/]+)\/([^\/]+).*$/, '$1-$2' )
6395 )
6396 .append( this.$link );
6397 this.setTitle( config.title || this.constructor.static.title );
6398 };
6399
6400 /* Setup */
6401
6402 OO.inheritClass( OO.ui.Tool, OO.ui.Widget );
6403 OO.mixinClass( OO.ui.Tool, OO.ui.IconElement );
6404 OO.mixinClass( OO.ui.Tool, OO.ui.FlaggedElement );
6405
6406 /* Events */
6407
6408 /**
6409 * @event select
6410 */
6411
6412 /* Static Properties */
6413
6414 /**
6415 * @static
6416 * @inheritdoc
6417 */
6418 OO.ui.Tool.static.tagName = 'span';
6419
6420 /**
6421 * Symbolic name of tool.
6422 *
6423 * @abstract
6424 * @static
6425 * @inheritable
6426 * @property {string}
6427 */
6428 OO.ui.Tool.static.name = '';
6429
6430 /**
6431 * Tool group.
6432 *
6433 * @abstract
6434 * @static
6435 * @inheritable
6436 * @property {string}
6437 */
6438 OO.ui.Tool.static.group = '';
6439
6440 /**
6441 * Tool title.
6442 *
6443 * Title is used as a tooltip when the tool is part of a bar tool group, or a label when the tool
6444 * is part of a list or menu tool group. If a trigger is associated with an action by the same name
6445 * as the tool, a description of its keyboard shortcut for the appropriate platform will be
6446 * appended to the title if the tool is part of a bar tool group.
6447 *
6448 * @abstract
6449 * @static
6450 * @inheritable
6451 * @property {string|Function} Title text or a function that returns text
6452 */
6453 OO.ui.Tool.static.title = '';
6454
6455 /**
6456 * Tool can be automatically added to catch-all groups.
6457 *
6458 * @static
6459 * @inheritable
6460 * @property {boolean}
6461 */
6462 OO.ui.Tool.static.autoAddToCatchall = true;
6463
6464 /**
6465 * Tool can be automatically added to named groups.
6466 *
6467 * @static
6468 * @property {boolean}
6469 * @inheritable
6470 */
6471 OO.ui.Tool.static.autoAddToGroup = true;
6472
6473 /**
6474 * Check if this tool is compatible with given data.
6475 *
6476 * @static
6477 * @inheritable
6478 * @param {Mixed} data Data to check
6479 * @return {boolean} Tool can be used with data
6480 */
6481 OO.ui.Tool.static.isCompatibleWith = function () {
6482 return false;
6483 };
6484
6485 /* Methods */
6486
6487 /**
6488 * Handle the toolbar state being updated.
6489 *
6490 * This is an abstract method that must be overridden in a concrete subclass.
6491 *
6492 * @abstract
6493 */
6494 OO.ui.Tool.prototype.onUpdateState = function () {
6495 throw new Error(
6496 'OO.ui.Tool.onUpdateState not implemented in this subclass:' + this.constructor
6497 );
6498 };
6499
6500 /**
6501 * Handle the tool being selected.
6502 *
6503 * This is an abstract method that must be overridden in a concrete subclass.
6504 *
6505 * @abstract
6506 */
6507 OO.ui.Tool.prototype.onSelect = function () {
6508 throw new Error(
6509 'OO.ui.Tool.onSelect not implemented in this subclass:' + this.constructor
6510 );
6511 };
6512
6513 /**
6514 * Check if the button is active.
6515 *
6516 * @return {boolean} Button is active
6517 */
6518 OO.ui.Tool.prototype.isActive = function () {
6519 return this.active;
6520 };
6521
6522 /**
6523 * Make the button appear active or inactive.
6524 *
6525 * @param {boolean} state Make button appear active
6526 */
6527 OO.ui.Tool.prototype.setActive = function ( state ) {
6528 this.active = !!state;
6529 if ( this.active ) {
6530 this.$element.addClass( 'oo-ui-tool-active' );
6531 } else {
6532 this.$element.removeClass( 'oo-ui-tool-active' );
6533 }
6534 };
6535
6536 /**
6537 * Get the tool title.
6538 *
6539 * @param {string|Function} title Title text or a function that returns text
6540 * @chainable
6541 */
6542 OO.ui.Tool.prototype.setTitle = function ( title ) {
6543 this.title = OO.ui.resolveMsg( title );
6544 this.updateTitle();
6545 return this;
6546 };
6547
6548 /**
6549 * Get the tool title.
6550 *
6551 * @return {string} Title text
6552 */
6553 OO.ui.Tool.prototype.getTitle = function () {
6554 return this.title;
6555 };
6556
6557 /**
6558 * Get the tool's symbolic name.
6559 *
6560 * @return {string} Symbolic name of tool
6561 */
6562 OO.ui.Tool.prototype.getName = function () {
6563 return this.constructor.static.name;
6564 };
6565
6566 /**
6567 * Update the title.
6568 */
6569 OO.ui.Tool.prototype.updateTitle = function () {
6570 var titleTooltips = this.toolGroup.constructor.static.titleTooltips,
6571 accelTooltips = this.toolGroup.constructor.static.accelTooltips,
6572 accel = this.toolbar.getToolAccelerator( this.constructor.static.name ),
6573 tooltipParts = [];
6574
6575 this.$title.text( this.title );
6576 this.$accel.text( accel );
6577
6578 if ( titleTooltips && typeof this.title === 'string' && this.title.length ) {
6579 tooltipParts.push( this.title );
6580 }
6581 if ( accelTooltips && typeof accel === 'string' && accel.length ) {
6582 tooltipParts.push( accel );
6583 }
6584 if ( tooltipParts.length ) {
6585 this.$link.attr( 'title', tooltipParts.join( ' ' ) );
6586 } else {
6587 this.$link.removeAttr( 'title' );
6588 }
6589 };
6590
6591 /**
6592 * Destroy tool.
6593 */
6594 OO.ui.Tool.prototype.destroy = function () {
6595 this.toolbar.disconnect( this );
6596 this.$element.remove();
6597 };
6598
6599 /**
6600 * Collection of tool groups.
6601 *
6602 * @class
6603 * @extends OO.ui.Element
6604 * @mixins OO.EventEmitter
6605 * @mixins OO.ui.GroupElement
6606 *
6607 * @constructor
6608 * @param {OO.ui.ToolFactory} toolFactory Factory for creating tools
6609 * @param {OO.ui.ToolGroupFactory} toolGroupFactory Factory for creating tool groups
6610 * @param {Object} [config] Configuration options
6611 * @cfg {boolean} [actions] Add an actions section opposite to the tools
6612 * @cfg {boolean} [shadow] Add a shadow below the toolbar
6613 */
6614 OO.ui.Toolbar = function OoUiToolbar( toolFactory, toolGroupFactory, config ) {
6615 // Allow passing positional parameters inside the config object
6616 if ( OO.isPlainObject( toolFactory ) && config === undefined ) {
6617 config = toolFactory;
6618 toolFactory = config.toolFactory;
6619 toolGroupFactory = config.toolGroupFactory;
6620 }
6621
6622 // Configuration initialization
6623 config = config || {};
6624
6625 // Parent constructor
6626 OO.ui.Toolbar.super.call( this, config );
6627
6628 // Mixin constructors
6629 OO.EventEmitter.call( this );
6630 OO.ui.GroupElement.call( this, config );
6631
6632 // Properties
6633 this.toolFactory = toolFactory;
6634 this.toolGroupFactory = toolGroupFactory;
6635 this.groups = [];
6636 this.tools = {};
6637 this.$bar = $( '<div>' );
6638 this.$actions = $( '<div>' );
6639 this.initialized = false;
6640 this.onWindowResizeHandler = this.onWindowResize.bind( this );
6641
6642 // Events
6643 this.$element
6644 .add( this.$bar ).add( this.$group ).add( this.$actions )
6645 .on( 'mousedown', this.onPointerDown.bind( this ) );
6646
6647 // Initialization
6648 this.$group.addClass( 'oo-ui-toolbar-tools' );
6649 if ( config.actions ) {
6650 this.$bar.append( this.$actions.addClass( 'oo-ui-toolbar-actions' ) );
6651 }
6652 this.$bar
6653 .addClass( 'oo-ui-toolbar-bar' )
6654 .append( this.$group, '<div style="clear:both"></div>' );
6655 if ( config.shadow ) {
6656 this.$bar.append( '<div class="oo-ui-toolbar-shadow"></div>' );
6657 }
6658 this.$element.addClass( 'oo-ui-toolbar' ).append( this.$bar );
6659 };
6660
6661 /* Setup */
6662
6663 OO.inheritClass( OO.ui.Toolbar, OO.ui.Element );
6664 OO.mixinClass( OO.ui.Toolbar, OO.EventEmitter );
6665 OO.mixinClass( OO.ui.Toolbar, OO.ui.GroupElement );
6666
6667 /* Methods */
6668
6669 /**
6670 * Get the tool factory.
6671 *
6672 * @return {OO.ui.ToolFactory} Tool factory
6673 */
6674 OO.ui.Toolbar.prototype.getToolFactory = function () {
6675 return this.toolFactory;
6676 };
6677
6678 /**
6679 * Get the tool group factory.
6680 *
6681 * @return {OO.Factory} Tool group factory
6682 */
6683 OO.ui.Toolbar.prototype.getToolGroupFactory = function () {
6684 return this.toolGroupFactory;
6685 };
6686
6687 /**
6688 * Handles mouse down events.
6689 *
6690 * @param {jQuery.Event} e Mouse down event
6691 */
6692 OO.ui.Toolbar.prototype.onPointerDown = function ( e ) {
6693 var $closestWidgetToEvent = $( e.target ).closest( '.oo-ui-widget' ),
6694 $closestWidgetToToolbar = this.$element.closest( '.oo-ui-widget' );
6695 if ( !$closestWidgetToEvent.length || $closestWidgetToEvent[ 0 ] === $closestWidgetToToolbar[ 0 ] ) {
6696 return false;
6697 }
6698 };
6699
6700 /**
6701 * Handle window resize event.
6702 *
6703 * @private
6704 * @param {jQuery.Event} e Window resize event
6705 */
6706 OO.ui.Toolbar.prototype.onWindowResize = function () {
6707 this.$element.toggleClass(
6708 'oo-ui-toolbar-narrow',
6709 this.$bar.width() <= this.narrowThreshold
6710 );
6711 };
6712
6713 /**
6714 * Sets up handles and preloads required information for the toolbar to work.
6715 * This must be called after it is attached to a visible document and before doing anything else.
6716 */
6717 OO.ui.Toolbar.prototype.initialize = function () {
6718 this.initialized = true;
6719 this.narrowThreshold = this.$group.width() + this.$actions.width();
6720 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
6721 this.onWindowResize();
6722 };
6723
6724 /**
6725 * Setup toolbar.
6726 *
6727 * Tools can be specified in the following ways:
6728 *
6729 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6730 * - All tools in a group: `{ group: 'group-name' }`
6731 * - All tools: `'*'` - Using this will make the group a list with a "More" label by default
6732 *
6733 * @param {Object.<string,Array>} groups List of tool group configurations
6734 * @param {Array|string} [groups.include] Tools to include
6735 * @param {Array|string} [groups.exclude] Tools to exclude
6736 * @param {Array|string} [groups.promote] Tools to promote to the beginning
6737 * @param {Array|string} [groups.demote] Tools to demote to the end
6738 */
6739 OO.ui.Toolbar.prototype.setup = function ( groups ) {
6740 var i, len, type, group,
6741 items = [],
6742 defaultType = 'bar';
6743
6744 // Cleanup previous groups
6745 this.reset();
6746
6747 // Build out new groups
6748 for ( i = 0, len = groups.length; i < len; i++ ) {
6749 group = groups[ i ];
6750 if ( group.include === '*' ) {
6751 // Apply defaults to catch-all groups
6752 if ( group.type === undefined ) {
6753 group.type = 'list';
6754 }
6755 if ( group.label === undefined ) {
6756 group.label = OO.ui.msg( 'ooui-toolbar-more' );
6757 }
6758 }
6759 // Check type has been registered
6760 type = this.getToolGroupFactory().lookup( group.type ) ? group.type : defaultType;
6761 items.push(
6762 this.getToolGroupFactory().create( type, this, group )
6763 );
6764 }
6765 this.addItems( items );
6766 };
6767
6768 /**
6769 * Remove all tools and groups from the toolbar.
6770 */
6771 OO.ui.Toolbar.prototype.reset = function () {
6772 var i, len;
6773
6774 this.groups = [];
6775 this.tools = {};
6776 for ( i = 0, len = this.items.length; i < len; i++ ) {
6777 this.items[ i ].destroy();
6778 }
6779 this.clearItems();
6780 };
6781
6782 /**
6783 * Destroys toolbar, removing event handlers and DOM elements.
6784 *
6785 * Call this whenever you are done using a toolbar.
6786 */
6787 OO.ui.Toolbar.prototype.destroy = function () {
6788 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
6789 this.reset();
6790 this.$element.remove();
6791 };
6792
6793 /**
6794 * Check if tool has not been used yet.
6795 *
6796 * @param {string} name Symbolic name of tool
6797 * @return {boolean} Tool is available
6798 */
6799 OO.ui.Toolbar.prototype.isToolAvailable = function ( name ) {
6800 return !this.tools[ name ];
6801 };
6802
6803 /**
6804 * Prevent tool from being used again.
6805 *
6806 * @param {OO.ui.Tool} tool Tool to reserve
6807 */
6808 OO.ui.Toolbar.prototype.reserveTool = function ( tool ) {
6809 this.tools[ tool.getName() ] = tool;
6810 };
6811
6812 /**
6813 * Allow tool to be used again.
6814 *
6815 * @param {OO.ui.Tool} tool Tool to release
6816 */
6817 OO.ui.Toolbar.prototype.releaseTool = function ( tool ) {
6818 delete this.tools[ tool.getName() ];
6819 };
6820
6821 /**
6822 * Get accelerator label for tool.
6823 *
6824 * This is a stub that should be overridden to provide access to accelerator information.
6825 *
6826 * @param {string} name Symbolic name of tool
6827 * @return {string|undefined} Tool accelerator label if available
6828 */
6829 OO.ui.Toolbar.prototype.getToolAccelerator = function () {
6830 return undefined;
6831 };
6832
6833 /**
6834 * Collection of tools.
6835 *
6836 * Tools can be specified in the following ways:
6837 *
6838 * - A specific tool: `{ name: 'tool-name' }` or `'tool-name'`
6839 * - All tools in a group: `{ group: 'group-name' }`
6840 * - All tools: `'*'`
6841 *
6842 * @abstract
6843 * @class
6844 * @extends OO.ui.Widget
6845 * @mixins OO.ui.GroupElement
6846 *
6847 * @constructor
6848 * @param {OO.ui.Toolbar} toolbar
6849 * @param {Object} [config] Configuration options
6850 * @cfg {Array|string} [include=[]] List of tools to include
6851 * @cfg {Array|string} [exclude=[]] List of tools to exclude
6852 * @cfg {Array|string} [promote=[]] List of tools to promote to the beginning
6853 * @cfg {Array|string} [demote=[]] List of tools to demote to the end
6854 */
6855 OO.ui.ToolGroup = function OoUiToolGroup( toolbar, config ) {
6856 // Allow passing positional parameters inside the config object
6857 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
6858 config = toolbar;
6859 toolbar = config.toolbar;
6860 }
6861
6862 // Configuration initialization
6863 config = config || {};
6864
6865 // Parent constructor
6866 OO.ui.ToolGroup.super.call( this, config );
6867
6868 // Mixin constructors
6869 OO.ui.GroupElement.call( this, config );
6870
6871 // Properties
6872 this.toolbar = toolbar;
6873 this.tools = {};
6874 this.pressed = null;
6875 this.autoDisabled = false;
6876 this.include = config.include || [];
6877 this.exclude = config.exclude || [];
6878 this.promote = config.promote || [];
6879 this.demote = config.demote || [];
6880 this.onCapturedMouseUpHandler = this.onCapturedMouseUp.bind( this );
6881
6882 // Events
6883 this.$element.on( {
6884 mousedown: this.onPointerDown.bind( this ),
6885 mouseup: this.onPointerUp.bind( this ),
6886 mouseover: this.onMouseOver.bind( this ),
6887 mouseout: this.onMouseOut.bind( this )
6888 } );
6889 this.toolbar.getToolFactory().connect( this, { register: 'onToolFactoryRegister' } );
6890 this.aggregate( { disable: 'itemDisable' } );
6891 this.connect( this, { itemDisable: 'updateDisabled' } );
6892
6893 // Initialization
6894 this.$group.addClass( 'oo-ui-toolGroup-tools' );
6895 this.$element
6896 .addClass( 'oo-ui-toolGroup' )
6897 .append( this.$group );
6898 this.populate();
6899 };
6900
6901 /* Setup */
6902
6903 OO.inheritClass( OO.ui.ToolGroup, OO.ui.Widget );
6904 OO.mixinClass( OO.ui.ToolGroup, OO.ui.GroupElement );
6905
6906 /* Events */
6907
6908 /**
6909 * @event update
6910 */
6911
6912 /* Static Properties */
6913
6914 /**
6915 * Show labels in tooltips.
6916 *
6917 * @static
6918 * @inheritable
6919 * @property {boolean}
6920 */
6921 OO.ui.ToolGroup.static.titleTooltips = false;
6922
6923 /**
6924 * Show acceleration labels in tooltips.
6925 *
6926 * @static
6927 * @inheritable
6928 * @property {boolean}
6929 */
6930 OO.ui.ToolGroup.static.accelTooltips = false;
6931
6932 /**
6933 * Automatically disable the toolgroup when all tools are disabled
6934 *
6935 * @static
6936 * @inheritable
6937 * @property {boolean}
6938 */
6939 OO.ui.ToolGroup.static.autoDisable = true;
6940
6941 /* Methods */
6942
6943 /**
6944 * @inheritdoc
6945 */
6946 OO.ui.ToolGroup.prototype.isDisabled = function () {
6947 return this.autoDisabled || OO.ui.ToolGroup.super.prototype.isDisabled.apply( this, arguments );
6948 };
6949
6950 /**
6951 * @inheritdoc
6952 */
6953 OO.ui.ToolGroup.prototype.updateDisabled = function () {
6954 var i, item, allDisabled = true;
6955
6956 if ( this.constructor.static.autoDisable ) {
6957 for ( i = this.items.length - 1; i >= 0; i-- ) {
6958 item = this.items[ i ];
6959 if ( !item.isDisabled() ) {
6960 allDisabled = false;
6961 break;
6962 }
6963 }
6964 this.autoDisabled = allDisabled;
6965 }
6966 OO.ui.ToolGroup.super.prototype.updateDisabled.apply( this, arguments );
6967 };
6968
6969 /**
6970 * Handle mouse down events.
6971 *
6972 * @param {jQuery.Event} e Mouse down event
6973 */
6974 OO.ui.ToolGroup.prototype.onPointerDown = function ( e ) {
6975 if ( !this.isDisabled() && e.which === 1 ) {
6976 this.pressed = this.getTargetTool( e );
6977 if ( this.pressed ) {
6978 this.pressed.setActive( true );
6979 this.getElementDocument().addEventListener(
6980 'mouseup', this.onCapturedMouseUpHandler, true
6981 );
6982 }
6983 }
6984 return false;
6985 };
6986
6987 /**
6988 * Handle captured mouse up events.
6989 *
6990 * @param {Event} e Mouse up event
6991 */
6992 OO.ui.ToolGroup.prototype.onCapturedMouseUp = function ( e ) {
6993 this.getElementDocument().removeEventListener( 'mouseup', this.onCapturedMouseUpHandler, true );
6994 // onPointerUp may be called a second time, depending on where the mouse is when the button is
6995 // released, but since `this.pressed` will no longer be true, the second call will be ignored.
6996 this.onPointerUp( e );
6997 };
6998
6999 /**
7000 * Handle mouse up events.
7001 *
7002 * @param {jQuery.Event} e Mouse up event
7003 */
7004 OO.ui.ToolGroup.prototype.onPointerUp = function ( e ) {
7005 var tool = this.getTargetTool( e );
7006
7007 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === tool ) {
7008 this.pressed.onSelect();
7009 }
7010
7011 this.pressed = null;
7012 return false;
7013 };
7014
7015 /**
7016 * Handle mouse over events.
7017 *
7018 * @param {jQuery.Event} e Mouse over event
7019 */
7020 OO.ui.ToolGroup.prototype.onMouseOver = function ( e ) {
7021 var tool = this.getTargetTool( e );
7022
7023 if ( this.pressed && this.pressed === tool ) {
7024 this.pressed.setActive( true );
7025 }
7026 };
7027
7028 /**
7029 * Handle mouse out events.
7030 *
7031 * @param {jQuery.Event} e Mouse out event
7032 */
7033 OO.ui.ToolGroup.prototype.onMouseOut = function ( e ) {
7034 var tool = this.getTargetTool( e );
7035
7036 if ( this.pressed && this.pressed === tool ) {
7037 this.pressed.setActive( false );
7038 }
7039 };
7040
7041 /**
7042 * Get the closest tool to a jQuery.Event.
7043 *
7044 * Only tool links are considered, which prevents other elements in the tool such as popups from
7045 * triggering tool group interactions.
7046 *
7047 * @private
7048 * @param {jQuery.Event} e
7049 * @return {OO.ui.Tool|null} Tool, `null` if none was found
7050 */
7051 OO.ui.ToolGroup.prototype.getTargetTool = function ( e ) {
7052 var tool,
7053 $item = $( e.target ).closest( '.oo-ui-tool-link' );
7054
7055 if ( $item.length ) {
7056 tool = $item.parent().data( 'oo-ui-tool' );
7057 }
7058
7059 return tool && !tool.isDisabled() ? tool : null;
7060 };
7061
7062 /**
7063 * Handle tool registry register events.
7064 *
7065 * If a tool is registered after the group is created, we must repopulate the list to account for:
7066 *
7067 * - a tool being added that may be included
7068 * - a tool already included being overridden
7069 *
7070 * @param {string} name Symbolic name of tool
7071 */
7072 OO.ui.ToolGroup.prototype.onToolFactoryRegister = function () {
7073 this.populate();
7074 };
7075
7076 /**
7077 * Get the toolbar this group is in.
7078 *
7079 * @return {OO.ui.Toolbar} Toolbar of group
7080 */
7081 OO.ui.ToolGroup.prototype.getToolbar = function () {
7082 return this.toolbar;
7083 };
7084
7085 /**
7086 * Add and remove tools based on configuration.
7087 */
7088 OO.ui.ToolGroup.prototype.populate = function () {
7089 var i, len, name, tool,
7090 toolFactory = this.toolbar.getToolFactory(),
7091 names = {},
7092 add = [],
7093 remove = [],
7094 list = this.toolbar.getToolFactory().getTools(
7095 this.include, this.exclude, this.promote, this.demote
7096 );
7097
7098 // Build a list of needed tools
7099 for ( i = 0, len = list.length; i < len; i++ ) {
7100 name = list[ i ];
7101 if (
7102 // Tool exists
7103 toolFactory.lookup( name ) &&
7104 // Tool is available or is already in this group
7105 ( this.toolbar.isToolAvailable( name ) || this.tools[ name ] )
7106 ) {
7107 // Hack to prevent infinite recursion via ToolGroupTool. We need to reserve the tool before
7108 // creating it, but we can't call reserveTool() yet because we haven't created the tool.
7109 this.toolbar.tools[ name ] = true;
7110 tool = this.tools[ name ];
7111 if ( !tool ) {
7112 // Auto-initialize tools on first use
7113 this.tools[ name ] = tool = toolFactory.create( name, this );
7114 tool.updateTitle();
7115 }
7116 this.toolbar.reserveTool( tool );
7117 add.push( tool );
7118 names[ name ] = true;
7119 }
7120 }
7121 // Remove tools that are no longer needed
7122 for ( name in this.tools ) {
7123 if ( !names[ name ] ) {
7124 this.tools[ name ].destroy();
7125 this.toolbar.releaseTool( this.tools[ name ] );
7126 remove.push( this.tools[ name ] );
7127 delete this.tools[ name ];
7128 }
7129 }
7130 if ( remove.length ) {
7131 this.removeItems( remove );
7132 }
7133 // Update emptiness state
7134 if ( add.length ) {
7135 this.$element.removeClass( 'oo-ui-toolGroup-empty' );
7136 } else {
7137 this.$element.addClass( 'oo-ui-toolGroup-empty' );
7138 }
7139 // Re-add tools (moving existing ones to new locations)
7140 this.addItems( add );
7141 // Disabled state may depend on items
7142 this.updateDisabled();
7143 };
7144
7145 /**
7146 * Destroy tool group.
7147 */
7148 OO.ui.ToolGroup.prototype.destroy = function () {
7149 var name;
7150
7151 this.clearItems();
7152 this.toolbar.getToolFactory().disconnect( this );
7153 for ( name in this.tools ) {
7154 this.toolbar.releaseTool( this.tools[ name ] );
7155 this.tools[ name ].disconnect( this ).destroy();
7156 delete this.tools[ name ];
7157 }
7158 this.$element.remove();
7159 };
7160
7161 /**
7162 * MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
7163 * consists of a header that contains the dialog title, a body with the message, and a footer that
7164 * contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
7165 * of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
7166 *
7167 * There are two basic types of message dialogs, confirmation and alert:
7168 *
7169 * - **confirmation**: the dialog title describes what a progressive action will do and the message provides
7170 * more details about the consequences.
7171 * - **alert**: the dialog title describes which event occurred and the message provides more information
7172 * about why the event occurred.
7173 *
7174 * The MessageDialog class specifies two actions: ‘accept’, the primary
7175 * action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
7176 * passing along the selected action.
7177 *
7178 * For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
7179 *
7180 * @example
7181 * // Example: Creating and opening a message dialog window.
7182 * var messageDialog = new OO.ui.MessageDialog();
7183 *
7184 * // Create and append a window manager.
7185 * var windowManager = new OO.ui.WindowManager();
7186 * $( 'body' ).append( windowManager.$element );
7187 * windowManager.addWindows( [ messageDialog ] );
7188 * // Open the window.
7189 * windowManager.openWindow( messageDialog, {
7190 * title: 'Basic message dialog',
7191 * message: 'This is the message'
7192 * } );
7193 *
7194 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
7195 *
7196 * @class
7197 * @extends OO.ui.Dialog
7198 *
7199 * @constructor
7200 * @param {Object} [config] Configuration options
7201 */
7202 OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
7203 // Parent constructor
7204 OO.ui.MessageDialog.super.call( this, config );
7205
7206 // Properties
7207 this.verticalActionLayout = null;
7208
7209 // Initialization
7210 this.$element.addClass( 'oo-ui-messageDialog' );
7211 };
7212
7213 /* Inheritance */
7214
7215 OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
7216
7217 /* Static Properties */
7218
7219 OO.ui.MessageDialog.static.name = 'message';
7220
7221 OO.ui.MessageDialog.static.size = 'small';
7222
7223 OO.ui.MessageDialog.static.verbose = false;
7224
7225 /**
7226 * Dialog title.
7227 *
7228 * The title of a confirmation dialog describes what a progressive action will do. The
7229 * title of an alert dialog describes which event occurred.
7230 *
7231 * @static
7232 * @inheritable
7233 * @property {jQuery|string|Function|null}
7234 */
7235 OO.ui.MessageDialog.static.title = null;
7236
7237 /**
7238 * The message displayed in the dialog body.
7239 *
7240 * A confirmation message describes the consequences of a progressive action. An alert
7241 * message describes why an event occurred.
7242 *
7243 * @static
7244 * @inheritable
7245 * @property {jQuery|string|Function|null}
7246 */
7247 OO.ui.MessageDialog.static.message = null;
7248
7249 OO.ui.MessageDialog.static.actions = [
7250 { action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
7251 { action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
7252 ];
7253
7254 /* Methods */
7255
7256 /**
7257 * @inheritdoc
7258 */
7259 OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
7260 OO.ui.MessageDialog.super.prototype.setManager.call( this, manager );
7261
7262 // Events
7263 this.manager.connect( this, {
7264 resize: 'onResize'
7265 } );
7266
7267 return this;
7268 };
7269
7270 /**
7271 * @inheritdoc
7272 */
7273 OO.ui.MessageDialog.prototype.onActionResize = function ( action ) {
7274 this.fitActions();
7275 return OO.ui.MessageDialog.super.prototype.onActionResize.call( this, action );
7276 };
7277
7278 /**
7279 * Handle window resized events.
7280 *
7281 * @private
7282 */
7283 OO.ui.MessageDialog.prototype.onResize = function () {
7284 var dialog = this;
7285 dialog.fitActions();
7286 // Wait for CSS transition to finish and do it again :(
7287 setTimeout( function () {
7288 dialog.fitActions();
7289 }, 300 );
7290 };
7291
7292 /**
7293 * Toggle action layout between vertical and horizontal.
7294 *
7295 *
7296 * @private
7297 * @param {boolean} [value] Layout actions vertically, omit to toggle
7298 * @chainable
7299 */
7300 OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
7301 value = value === undefined ? !this.verticalActionLayout : !!value;
7302
7303 if ( value !== this.verticalActionLayout ) {
7304 this.verticalActionLayout = value;
7305 this.$actions
7306 .toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
7307 .toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
7308 }
7309
7310 return this;
7311 };
7312
7313 /**
7314 * @inheritdoc
7315 */
7316 OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
7317 if ( action ) {
7318 return new OO.ui.Process( function () {
7319 this.close( { action: action } );
7320 }, this );
7321 }
7322 return OO.ui.MessageDialog.super.prototype.getActionProcess.call( this, action );
7323 };
7324
7325 /**
7326 * @inheritdoc
7327 *
7328 * @param {Object} [data] Dialog opening data
7329 * @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
7330 * @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
7331 * @param {boolean} [data.verbose] Message is verbose and should be styled as a long message
7332 * @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
7333 * action item
7334 */
7335 OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
7336 data = data || {};
7337
7338 // Parent method
7339 return OO.ui.MessageDialog.super.prototype.getSetupProcess.call( this, data )
7340 .next( function () {
7341 this.title.setLabel(
7342 data.title !== undefined ? data.title : this.constructor.static.title
7343 );
7344 this.message.setLabel(
7345 data.message !== undefined ? data.message : this.constructor.static.message
7346 );
7347 this.message.$element.toggleClass(
7348 'oo-ui-messageDialog-message-verbose',
7349 data.verbose !== undefined ? data.verbose : this.constructor.static.verbose
7350 );
7351 }, this );
7352 };
7353
7354 /**
7355 * @inheritdoc
7356 */
7357 OO.ui.MessageDialog.prototype.getBodyHeight = function () {
7358 var bodyHeight, oldOverflow,
7359 $scrollable = this.container.$element;
7360
7361 oldOverflow = $scrollable[ 0 ].style.overflow;
7362 $scrollable[ 0 ].style.overflow = 'hidden';
7363
7364 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7365
7366 bodyHeight = this.text.$element.outerHeight( true );
7367 $scrollable[ 0 ].style.overflow = oldOverflow;
7368
7369 return bodyHeight;
7370 };
7371
7372 /**
7373 * @inheritdoc
7374 */
7375 OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
7376 var $scrollable = this.container.$element;
7377 OO.ui.MessageDialog.super.prototype.setDimensions.call( this, dim );
7378
7379 // Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
7380 // Need to do it after transition completes (250ms), add 50ms just in case.
7381 setTimeout( function () {
7382 var oldOverflow = $scrollable[ 0 ].style.overflow;
7383 $scrollable[ 0 ].style.overflow = 'hidden';
7384
7385 OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
7386
7387 $scrollable[ 0 ].style.overflow = oldOverflow;
7388 }, 300 );
7389
7390 return this;
7391 };
7392
7393 /**
7394 * @inheritdoc
7395 */
7396 OO.ui.MessageDialog.prototype.initialize = function () {
7397 // Parent method
7398 OO.ui.MessageDialog.super.prototype.initialize.call( this );
7399
7400 // Properties
7401 this.$actions = $( '<div>' );
7402 this.container = new OO.ui.PanelLayout( {
7403 scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
7404 } );
7405 this.text = new OO.ui.PanelLayout( {
7406 padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
7407 } );
7408 this.message = new OO.ui.LabelWidget( {
7409 classes: [ 'oo-ui-messageDialog-message' ]
7410 } );
7411
7412 // Initialization
7413 this.title.$element.addClass( 'oo-ui-messageDialog-title' );
7414 this.$content.addClass( 'oo-ui-messageDialog-content' );
7415 this.container.$element.append( this.text.$element );
7416 this.text.$element.append( this.title.$element, this.message.$element );
7417 this.$body.append( this.container.$element );
7418 this.$actions.addClass( 'oo-ui-messageDialog-actions' );
7419 this.$foot.append( this.$actions );
7420 };
7421
7422 /**
7423 * @inheritdoc
7424 */
7425 OO.ui.MessageDialog.prototype.attachActions = function () {
7426 var i, len, other, special, others;
7427
7428 // Parent method
7429 OO.ui.MessageDialog.super.prototype.attachActions.call( this );
7430
7431 special = this.actions.getSpecial();
7432 others = this.actions.getOthers();
7433 if ( special.safe ) {
7434 this.$actions.append( special.safe.$element );
7435 special.safe.toggleFramed( false );
7436 }
7437 if ( others.length ) {
7438 for ( i = 0, len = others.length; i < len; i++ ) {
7439 other = others[ i ];
7440 this.$actions.append( other.$element );
7441 other.toggleFramed( false );
7442 }
7443 }
7444 if ( special.primary ) {
7445 this.$actions.append( special.primary.$element );
7446 special.primary.toggleFramed( false );
7447 }
7448
7449 if ( !this.isOpening() ) {
7450 // If the dialog is currently opening, this will be called automatically soon.
7451 // This also calls #fitActions.
7452 this.updateSize();
7453 }
7454 };
7455
7456 /**
7457 * Fit action actions into columns or rows.
7458 *
7459 * Columns will be used if all labels can fit without overflow, otherwise rows will be used.
7460 *
7461 * @private
7462 */
7463 OO.ui.MessageDialog.prototype.fitActions = function () {
7464 var i, len, action,
7465 previous = this.verticalActionLayout,
7466 actions = this.actions.get();
7467
7468 // Detect clipping
7469 this.toggleVerticalActionLayout( false );
7470 for ( i = 0, len = actions.length; i < len; i++ ) {
7471 action = actions[ i ];
7472 if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
7473 this.toggleVerticalActionLayout( true );
7474 break;
7475 }
7476 }
7477
7478 // Move the body out of the way of the foot
7479 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7480
7481 if ( this.verticalActionLayout !== previous ) {
7482 // We changed the layout, window height might need to be updated.
7483 this.updateSize();
7484 }
7485 };
7486
7487 /**
7488 * ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
7489 * to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
7490 * interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
7491 * relevant. The ProcessDialog class is always extended and customized with the actions and content
7492 * required for each process.
7493 *
7494 * The process dialog box consists of a header that visually represents the ‘working’ state of long
7495 * processes with an animation. The header contains the dialog title as well as
7496 * two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
7497 * a ‘primary’ action on the right (e.g., ‘Done’).
7498 *
7499 * Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
7500 * Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
7501 *
7502 * @example
7503 * // Example: Creating and opening a process dialog window.
7504 * function MyProcessDialog( config ) {
7505 * MyProcessDialog.super.call( this, config );
7506 * }
7507 * OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
7508 *
7509 * MyProcessDialog.static.title = 'Process dialog';
7510 * MyProcessDialog.static.actions = [
7511 * { action: 'save', label: 'Done', flags: 'primary' },
7512 * { label: 'Cancel', flags: 'safe' }
7513 * ];
7514 *
7515 * MyProcessDialog.prototype.initialize = function () {
7516 * MyProcessDialog.super.prototype.initialize.apply( this, arguments );
7517 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true, expanded: false } );
7518 * 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>' );
7519 * this.$body.append( this.content.$element );
7520 * };
7521 * MyProcessDialog.prototype.getActionProcess = function ( action ) {
7522 * var dialog = this;
7523 * if ( action ) {
7524 * return new OO.ui.Process( function () {
7525 * dialog.close( { action: action } );
7526 * } );
7527 * }
7528 * return MyProcessDialog.super.prototype.getActionProcess.call( this, action );
7529 * };
7530 *
7531 * var windowManager = new OO.ui.WindowManager();
7532 * $( 'body' ).append( windowManager.$element );
7533 *
7534 * var dialog = new MyProcessDialog();
7535 * windowManager.addWindows( [ dialog ] );
7536 * windowManager.openWindow( dialog );
7537 *
7538 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
7539 *
7540 * @abstract
7541 * @class
7542 * @extends OO.ui.Dialog
7543 *
7544 * @constructor
7545 * @param {Object} [config] Configuration options
7546 */
7547 OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
7548 // Parent constructor
7549 OO.ui.ProcessDialog.super.call( this, config );
7550
7551 // Initialization
7552 this.$element.addClass( 'oo-ui-processDialog' );
7553 };
7554
7555 /* Setup */
7556
7557 OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
7558
7559 /* Methods */
7560
7561 /**
7562 * Handle dismiss button click events.
7563 *
7564 * Hides errors.
7565 *
7566 * @private
7567 */
7568 OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
7569 this.hideErrors();
7570 };
7571
7572 /**
7573 * Handle retry button click events.
7574 *
7575 * Hides errors and then tries again.
7576 *
7577 * @private
7578 */
7579 OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
7580 this.hideErrors();
7581 this.executeAction( this.currentAction );
7582 };
7583
7584 /**
7585 * @inheritdoc
7586 */
7587 OO.ui.ProcessDialog.prototype.onActionResize = function ( action ) {
7588 if ( this.actions.isSpecial( action ) ) {
7589 this.fitLabel();
7590 }
7591 return OO.ui.ProcessDialog.super.prototype.onActionResize.call( this, action );
7592 };
7593
7594 /**
7595 * @inheritdoc
7596 */
7597 OO.ui.ProcessDialog.prototype.initialize = function () {
7598 // Parent method
7599 OO.ui.ProcessDialog.super.prototype.initialize.call( this );
7600
7601 // Properties
7602 this.$navigation = $( '<div>' );
7603 this.$location = $( '<div>' );
7604 this.$safeActions = $( '<div>' );
7605 this.$primaryActions = $( '<div>' );
7606 this.$otherActions = $( '<div>' );
7607 this.dismissButton = new OO.ui.ButtonWidget( {
7608 label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
7609 } );
7610 this.retryButton = new OO.ui.ButtonWidget();
7611 this.$errors = $( '<div>' );
7612 this.$errorsTitle = $( '<div>' );
7613
7614 // Events
7615 this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
7616 this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
7617
7618 // Initialization
7619 this.title.$element.addClass( 'oo-ui-processDialog-title' );
7620 this.$location
7621 .append( this.title.$element )
7622 .addClass( 'oo-ui-processDialog-location' );
7623 this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
7624 this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
7625 this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
7626 this.$errorsTitle
7627 .addClass( 'oo-ui-processDialog-errors-title' )
7628 .text( OO.ui.msg( 'ooui-dialog-process-error' ) );
7629 this.$errors
7630 .addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
7631 .append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
7632 this.$content
7633 .addClass( 'oo-ui-processDialog-content' )
7634 .append( this.$errors );
7635 this.$navigation
7636 .addClass( 'oo-ui-processDialog-navigation' )
7637 .append( this.$safeActions, this.$location, this.$primaryActions );
7638 this.$head.append( this.$navigation );
7639 this.$foot.append( this.$otherActions );
7640 };
7641
7642 /**
7643 * @inheritdoc
7644 */
7645 OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
7646 var i, len, widgets = [];
7647 for ( i = 0, len = actions.length; i < len; i++ ) {
7648 widgets.push(
7649 new OO.ui.ActionWidget( $.extend( { framed: true }, actions[ i ] ) )
7650 );
7651 }
7652 return widgets;
7653 };
7654
7655 /**
7656 * @inheritdoc
7657 */
7658 OO.ui.ProcessDialog.prototype.attachActions = function () {
7659 var i, len, other, special, others;
7660
7661 // Parent method
7662 OO.ui.ProcessDialog.super.prototype.attachActions.call( this );
7663
7664 special = this.actions.getSpecial();
7665 others = this.actions.getOthers();
7666 if ( special.primary ) {
7667 this.$primaryActions.append( special.primary.$element );
7668 }
7669 for ( i = 0, len = others.length; i < len; i++ ) {
7670 other = others[ i ];
7671 this.$otherActions.append( other.$element );
7672 }
7673 if ( special.safe ) {
7674 this.$safeActions.append( special.safe.$element );
7675 }
7676
7677 this.fitLabel();
7678 this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
7679 };
7680
7681 /**
7682 * @inheritdoc
7683 */
7684 OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
7685 var process = this;
7686 return OO.ui.ProcessDialog.super.prototype.executeAction.call( this, action )
7687 .fail( function ( errors ) {
7688 process.showErrors( errors || [] );
7689 } );
7690 };
7691
7692 /**
7693 * Fit label between actions.
7694 *
7695 * @private
7696 * @chainable
7697 */
7698 OO.ui.ProcessDialog.prototype.fitLabel = function () {
7699 var width = Math.max(
7700 this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0,
7701 this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0
7702 );
7703 this.$location.css( { paddingLeft: width, paddingRight: width } );
7704
7705 return this;
7706 };
7707
7708 /**
7709 * Handle errors that occurred during accept or reject processes.
7710 *
7711 * @private
7712 * @param {OO.ui.Error[]} errors Errors to be handled
7713 */
7714 OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
7715 var i, len, $item, actions,
7716 items = [],
7717 abilities = {},
7718 recoverable = true,
7719 warning = false;
7720
7721 for ( i = 0, len = errors.length; i < len; i++ ) {
7722 if ( !errors[ i ].isRecoverable() ) {
7723 recoverable = false;
7724 }
7725 if ( errors[ i ].isWarning() ) {
7726 warning = true;
7727 }
7728 $item = $( '<div>' )
7729 .addClass( 'oo-ui-processDialog-error' )
7730 .append( errors[ i ].getMessage() );
7731 items.push( $item[ 0 ] );
7732 }
7733 this.$errorItems = $( items );
7734 if ( recoverable ) {
7735 abilities[this.currentAction] = true;
7736 // Copy the flags from the first matching action
7737 actions = this.actions.get( { actions: this.currentAction } );
7738 if ( actions.length ) {
7739 this.retryButton.clearFlags().setFlags( actions[0].getFlags() );
7740 }
7741 } else {
7742 abilities[this.currentAction] = false;
7743 this.actions.setAbilities( abilities );
7744 }
7745 if ( warning ) {
7746 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
7747 } else {
7748 this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
7749 }
7750 this.retryButton.toggle( recoverable );
7751 this.$errorsTitle.after( this.$errorItems );
7752 this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
7753 };
7754
7755 /**
7756 * Hide errors.
7757 *
7758 * @private
7759 */
7760 OO.ui.ProcessDialog.prototype.hideErrors = function () {
7761 this.$errors.addClass( 'oo-ui-element-hidden' );
7762 if ( this.$errorItems ) {
7763 this.$errorItems.remove();
7764 this.$errorItems = null;
7765 }
7766 };
7767
7768 /**
7769 * @inheritdoc
7770 */
7771 OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
7772 // Parent method
7773 return OO.ui.ProcessDialog.super.prototype.getTeardownProcess.call( this, data )
7774 .first( function () {
7775 // Make sure to hide errors
7776 this.hideErrors();
7777 }, this );
7778 };
7779
7780 /**
7781 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
7782 * which is a widget that is specified by reference before any optional configuration settings.
7783 *
7784 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
7785 *
7786 * - **left**: The label is placed before the field-widget and aligned with the left margin.
7787 * A left-alignment is used for forms with many fields.
7788 * - **right**: The label is placed before the field-widget and aligned to the right margin.
7789 * A right-alignment is used for long but familiar forms which users tab through,
7790 * verifying the current field with a quick glance at the label.
7791 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
7792 * that users fill out from top to bottom.
7793 * - **inline**: The label is placed after the field-widget and aligned to the left.
7794 * An inline-alignment is best used with checkboxes or radio buttons.
7795 *
7796 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
7797 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
7798 *
7799 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
7800 * @class
7801 * @extends OO.ui.Layout
7802 * @mixins OO.ui.LabelElement
7803 *
7804 * @constructor
7805 * @param {OO.ui.Widget} fieldWidget Field widget
7806 * @param {Object} [config] Configuration options
7807 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
7808 * @cfg {string} [help] Help text. When help text is specified, a help icon will appear
7809 * in the upper-right corner of the rendered field.
7810 */
7811 OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) {
7812 // Allow passing positional parameters inside the config object
7813 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7814 config = fieldWidget;
7815 fieldWidget = config.fieldWidget;
7816 }
7817
7818 var hasInputWidget = fieldWidget instanceof OO.ui.InputWidget;
7819
7820 // Configuration initialization
7821 config = $.extend( { align: 'left' }, config );
7822
7823 // Parent constructor
7824 OO.ui.FieldLayout.super.call( this, config );
7825
7826 // Mixin constructors
7827 OO.ui.LabelElement.call( this, config );
7828
7829 // Properties
7830 this.fieldWidget = fieldWidget;
7831 this.$field = $( '<div>' );
7832 this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' );
7833 this.align = null;
7834 if ( config.help ) {
7835 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
7836 classes: [ 'oo-ui-fieldLayout-help' ],
7837 framed: false,
7838 icon: 'info'
7839 } );
7840
7841 this.popupButtonWidget.getPopup().$body.append(
7842 $( '<div>' )
7843 .text( config.help )
7844 .addClass( 'oo-ui-fieldLayout-help-content' )
7845 );
7846 this.$help = this.popupButtonWidget.$element;
7847 } else {
7848 this.$help = $( [] );
7849 }
7850
7851 // Events
7852 if ( hasInputWidget ) {
7853 this.$label.on( 'click', this.onLabelClick.bind( this ) );
7854 }
7855 this.fieldWidget.connect( this, { disable: 'onFieldDisable' } );
7856
7857 // Initialization
7858 this.$element
7859 .addClass( 'oo-ui-fieldLayout' )
7860 .append( this.$help, this.$body );
7861 this.$body.addClass( 'oo-ui-fieldLayout-body' );
7862 this.$field
7863 .addClass( 'oo-ui-fieldLayout-field' )
7864 .toggleClass( 'oo-ui-fieldLayout-disable', this.fieldWidget.isDisabled() )
7865 .append( this.fieldWidget.$element );
7866
7867 this.setAlignment( config.align );
7868 };
7869
7870 /* Setup */
7871
7872 OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout );
7873 OO.mixinClass( OO.ui.FieldLayout, OO.ui.LabelElement );
7874
7875 /* Methods */
7876
7877 /**
7878 * Handle field disable events.
7879 *
7880 * @private
7881 * @param {boolean} value Field is disabled
7882 */
7883 OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) {
7884 this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value );
7885 };
7886
7887 /**
7888 * Handle label mouse click events.
7889 *
7890 * @private
7891 * @param {jQuery.Event} e Mouse click event
7892 */
7893 OO.ui.FieldLayout.prototype.onLabelClick = function () {
7894 this.fieldWidget.simulateLabelClick();
7895 return false;
7896 };
7897
7898 /**
7899 * Get the widget contained by the field.
7900 *
7901 * @return {OO.ui.Widget} Field widget
7902 */
7903 OO.ui.FieldLayout.prototype.getField = function () {
7904 return this.fieldWidget;
7905 };
7906
7907 /**
7908 * Set the field alignment mode.
7909 *
7910 * @private
7911 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
7912 * @chainable
7913 */
7914 OO.ui.FieldLayout.prototype.setAlignment = function ( value ) {
7915 if ( value !== this.align ) {
7916 // Default to 'left'
7917 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) {
7918 value = 'left';
7919 }
7920 // Reorder elements
7921 if ( value === 'inline' ) {
7922 this.$body.append( this.$field, this.$label );
7923 } else {
7924 this.$body.append( this.$label, this.$field );
7925 }
7926 // Set classes. The following classes can be used here:
7927 // * oo-ui-fieldLayout-align-left
7928 // * oo-ui-fieldLayout-align-right
7929 // * oo-ui-fieldLayout-align-top
7930 // * oo-ui-fieldLayout-align-inline
7931 if ( this.align ) {
7932 this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align );
7933 }
7934 this.$element.addClass( 'oo-ui-fieldLayout-align-' + value );
7935 this.align = value;
7936 }
7937
7938 return this;
7939 };
7940
7941 /**
7942 * Layout made of a field, a button, and an optional label.
7943 *
7944 * @class
7945 * @extends OO.ui.FieldLayout
7946 *
7947 * @constructor
7948 * @param {OO.ui.Widget} fieldWidget Field widget
7949 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
7950 * @param {Object} [config] Configuration options
7951 * @cfg {string} [align='left'] Alignment mode, either 'left', 'right', 'top' or 'inline'
7952 * @cfg {string} [help] Explanatory text shown as a '?' icon.
7953 */
7954 OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) {
7955 // Allow passing positional parameters inside the config object
7956 if ( OO.isPlainObject( fieldWidget ) && config === undefined ) {
7957 config = fieldWidget;
7958 fieldWidget = config.fieldWidget;
7959 buttonWidget = config.buttonWidget;
7960 }
7961
7962 // Configuration initialization
7963 config = $.extend( { align: 'left' }, config );
7964
7965 // Parent constructor
7966 OO.ui.ActionFieldLayout.super.call( this, fieldWidget, config );
7967
7968 // Properties
7969 this.fieldWidget = fieldWidget;
7970 this.buttonWidget = buttonWidget;
7971 this.$button = $( '<div>' )
7972 .addClass( 'oo-ui-actionFieldLayout-button' )
7973 .append( this.buttonWidget.$element );
7974 this.$input = $( '<div>' )
7975 .addClass( 'oo-ui-actionFieldLayout-input' )
7976 .append( this.fieldWidget.$element );
7977 this.$field
7978 .addClass( 'oo-ui-actionFieldLayout' )
7979 .append( this.$input, this.$button );
7980 };
7981
7982 /* Setup */
7983
7984 OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout );
7985
7986 /**
7987 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
7988 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
7989 * configured with a label as well. For more information and examples,
7990 * please see the [OOjs UI documentation on MediaWiki][1].
7991 *
7992 * @example
7993 * // Example of a fieldset layout
7994 * var input1 = new OO.ui.TextInputWidget( {
7995 * placeholder: 'A text input field'
7996 * } );
7997 *
7998 * var input2 = new OO.ui.TextInputWidget( {
7999 * placeholder: 'A text input field'
8000 * } );
8001 *
8002 * var fieldset = new OO.ui.FieldsetLayout( {
8003 * label: 'Example of a fieldset layout'
8004 * } );
8005 *
8006 * fieldset.addItems( [
8007 * new OO.ui.FieldLayout( input1, {
8008 * label: 'Field One'
8009 * } ),
8010 * new OO.ui.FieldLayout( input2, {
8011 * label: 'Field Two'
8012 * } )
8013 * ] );
8014 * $( 'body' ).append( fieldset.$element );
8015 *
8016 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
8017 *
8018 * @class
8019 * @extends OO.ui.Layout
8020 * @mixins OO.ui.IconElement
8021 * @mixins OO.ui.LabelElement
8022 * @mixins OO.ui.GroupElement
8023 *
8024 * @constructor
8025 * @param {Object} [config] Configuration options
8026 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
8027 */
8028 OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) {
8029 // Configuration initialization
8030 config = config || {};
8031
8032 // Parent constructor
8033 OO.ui.FieldsetLayout.super.call( this, config );
8034
8035 // Mixin constructors
8036 OO.ui.IconElement.call( this, config );
8037 OO.ui.LabelElement.call( this, config );
8038 OO.ui.GroupElement.call( this, config );
8039
8040 if ( config.help ) {
8041 this.popupButtonWidget = new OO.ui.PopupButtonWidget( {
8042 classes: [ 'oo-ui-fieldsetLayout-help' ],
8043 framed: false,
8044 icon: 'info'
8045 } );
8046
8047 this.popupButtonWidget.getPopup().$body.append(
8048 $( '<div>' )
8049 .text( config.help )
8050 .addClass( 'oo-ui-fieldsetLayout-help-content' )
8051 );
8052 this.$help = this.popupButtonWidget.$element;
8053 } else {
8054 this.$help = $( [] );
8055 }
8056
8057 // Initialization
8058 this.$element
8059 .addClass( 'oo-ui-fieldsetLayout' )
8060 .prepend( this.$help, this.$icon, this.$label, this.$group );
8061 if ( Array.isArray( config.items ) ) {
8062 this.addItems( config.items );
8063 }
8064 };
8065
8066 /* Setup */
8067
8068 OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout );
8069 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.IconElement );
8070 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.LabelElement );
8071 OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.GroupElement );
8072
8073 /**
8074 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
8075 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
8076 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
8077 *
8078 * @example
8079 * // Example of a form layout that wraps a fieldset layout
8080 * var input1 = new OO.ui.TextInputWidget( {
8081 * placeholder: 'Username'
8082 * } );
8083 * var input2 = new OO.ui.TextInputWidget( {
8084 * placeholder: 'Password',
8085 * type: 'password'
8086 * } );
8087 * var submit = new OO.ui.ButtonInputWidget( {
8088 * label: 'Submit'
8089 * } );
8090 *
8091 * var fieldset = new OO.ui.FieldsetLayout( {
8092 * label: 'A form layout'
8093 * } );
8094 * fieldset.addItems( [
8095 * new OO.ui.FieldLayout( input1, {
8096 * label: 'Username',
8097 * align: 'top'
8098 * } ),
8099 * new OO.ui.FieldLayout( input2, {
8100 * label: 'Password',
8101 * align: 'top'
8102 * } ),
8103 * new OO.ui.FieldLayout( submit )
8104 * ] );
8105 * var form = new OO.ui.FormLayout( {
8106 * items: [ fieldset ],
8107 * action: '/api/formhandler',
8108 * method: 'get'
8109 * } )
8110 * $( 'body' ).append( form.$element );
8111 *
8112 * @class
8113 * @extends OO.ui.Layout
8114 * @mixins OO.ui.GroupElement
8115 *
8116 * @constructor
8117 * @param {Object} [config] Configuration options
8118 * @cfg {string} [method] HTML form `method` attribute
8119 * @cfg {string} [action] HTML form `action` attribute
8120 * @cfg {string} [enctype] HTML form `enctype` attribute
8121 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
8122 */
8123 OO.ui.FormLayout = function OoUiFormLayout( config ) {
8124 // Configuration initialization
8125 config = config || {};
8126
8127 // Parent constructor
8128 OO.ui.FormLayout.super.call( this, config );
8129
8130 // Mixin constructors
8131 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
8132
8133 // Events
8134 this.$element.on( 'submit', this.onFormSubmit.bind( this ) );
8135
8136 // Initialization
8137 this.$element
8138 .addClass( 'oo-ui-formLayout' )
8139 .attr( {
8140 method: config.method,
8141 action: config.action,
8142 enctype: config.enctype
8143 } );
8144 if ( Array.isArray( config.items ) ) {
8145 this.addItems( config.items );
8146 }
8147 };
8148
8149 /* Setup */
8150
8151 OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout );
8152 OO.mixinClass( OO.ui.FormLayout, OO.ui.GroupElement );
8153
8154 /* Events */
8155
8156 /**
8157 * A 'submit' event is emitted when the form is submitted.
8158 *
8159 * @event submit
8160 */
8161
8162 /* Static Properties */
8163
8164 OO.ui.FormLayout.static.tagName = 'form';
8165
8166 /* Methods */
8167
8168 /**
8169 * Handle form submit events.
8170 *
8171 * @private
8172 * @param {jQuery.Event} e Submit event
8173 * @fires submit
8174 */
8175 OO.ui.FormLayout.prototype.onFormSubmit = function () {
8176 this.emit( 'submit' );
8177 return false;
8178 };
8179
8180 /**
8181 * Layout with a content and menu area.
8182 *
8183 * The menu area can be positioned at the top, after, bottom or before. The content area will fill
8184 * all remaining space.
8185 *
8186 * @class
8187 * @extends OO.ui.Layout
8188 *
8189 * @constructor
8190 * @param {Object} [config] Configuration options
8191 * @cfg {number|string} [menuSize='18em'] Size of menu in pixels or any CSS unit
8192 * @cfg {boolean} [showMenu=true] Show menu
8193 * @cfg {string} [position='before'] Position of menu, either `top`, `after`, `bottom` or `before`
8194 * @cfg {boolean} [collapse] Collapse the menu out of view
8195 */
8196 OO.ui.MenuLayout = function OoUiMenuLayout( config ) {
8197 var positions = this.constructor.static.menuPositions;
8198
8199 // Configuration initialization
8200 config = config || {};
8201
8202 // Parent constructor
8203 OO.ui.MenuLayout.super.call( this, config );
8204
8205 // Properties
8206 this.showMenu = config.showMenu !== false;
8207 this.menuSize = config.menuSize || '18em';
8208 this.menuPosition = positions[ config.menuPosition ] || positions.before;
8209
8210 /**
8211 * Menu DOM node
8212 *
8213 * @property {jQuery}
8214 */
8215 this.$menu = $( '<div>' );
8216 /**
8217 * Content DOM node
8218 *
8219 * @property {jQuery}
8220 */
8221 this.$content = $( '<div>' );
8222
8223 // Initialization
8224 this.toggleMenu( this.showMenu );
8225 this.updateSizes();
8226 this.$menu
8227 .addClass( 'oo-ui-menuLayout-menu' )
8228 .css( this.menuPosition.sizeProperty, this.menuSize );
8229 this.$content.addClass( 'oo-ui-menuLayout-content' );
8230 this.$element
8231 .addClass( 'oo-ui-menuLayout ' + this.menuPosition.className )
8232 .append( this.$content, this.$menu );
8233 };
8234
8235 /* Setup */
8236
8237 OO.inheritClass( OO.ui.MenuLayout, OO.ui.Layout );
8238
8239 /* Static Properties */
8240
8241 OO.ui.MenuLayout.static.menuPositions = {
8242 top: {
8243 sizeProperty: 'height',
8244 className: 'oo-ui-menuLayout-top'
8245 },
8246 after: {
8247 sizeProperty: 'width',
8248 className: 'oo-ui-menuLayout-after'
8249 },
8250 bottom: {
8251 sizeProperty: 'height',
8252 className: 'oo-ui-menuLayout-bottom'
8253 },
8254 before: {
8255 sizeProperty: 'width',
8256 className: 'oo-ui-menuLayout-before'
8257 }
8258 };
8259
8260 /* Methods */
8261
8262 /**
8263 * Toggle menu.
8264 *
8265 * @param {boolean} showMenu Show menu, omit to toggle
8266 * @chainable
8267 */
8268 OO.ui.MenuLayout.prototype.toggleMenu = function ( showMenu ) {
8269 showMenu = showMenu === undefined ? !this.showMenu : !!showMenu;
8270
8271 if ( this.showMenu !== showMenu ) {
8272 this.showMenu = showMenu;
8273 this.updateSizes();
8274 }
8275
8276 return this;
8277 };
8278
8279 /**
8280 * Check if menu is visible
8281 *
8282 * @return {boolean} Menu is visible
8283 */
8284 OO.ui.MenuLayout.prototype.isMenuVisible = function () {
8285 return this.showMenu;
8286 };
8287
8288 /**
8289 * Set menu size.
8290 *
8291 * @param {number|string} size Size of menu in pixels or any CSS unit
8292 * @chainable
8293 */
8294 OO.ui.MenuLayout.prototype.setMenuSize = function ( size ) {
8295 this.menuSize = size;
8296 this.updateSizes();
8297
8298 return this;
8299 };
8300
8301 /**
8302 * Update menu and content CSS based on current menu size and visibility
8303 *
8304 * This method is called internally when size or position is changed.
8305 */
8306 OO.ui.MenuLayout.prototype.updateSizes = function () {
8307 if ( this.showMenu ) {
8308 this.$menu
8309 .css( this.menuPosition.sizeProperty, this.menuSize )
8310 .css( 'overflow', '' );
8311 // Set offsets on all sides. CSS resets all but one with
8312 // 'important' rules so directionality flips are supported
8313 this.$content.css( {
8314 top: this.menuSize,
8315 right: this.menuSize,
8316 bottom: this.menuSize,
8317 left: this.menuSize
8318 } );
8319 } else {
8320 this.$menu
8321 .css( this.menuPosition.sizeProperty, 0 )
8322 .css( 'overflow', 'hidden' );
8323 this.$content.css( {
8324 top: 0,
8325 right: 0,
8326 bottom: 0,
8327 left: 0
8328 } );
8329 }
8330 };
8331
8332 /**
8333 * Get menu size.
8334 *
8335 * @return {number|string} Menu size
8336 */
8337 OO.ui.MenuLayout.prototype.getMenuSize = function () {
8338 return this.menuSize;
8339 };
8340
8341 /**
8342 * Set menu position.
8343 *
8344 * @param {string} position Position of menu, either `top`, `after`, `bottom` or `before`
8345 * @throws {Error} If position value is not supported
8346 * @chainable
8347 */
8348 OO.ui.MenuLayout.prototype.setMenuPosition = function ( position ) {
8349 var positions = this.constructor.static.menuPositions;
8350
8351 if ( !positions[ position ] ) {
8352 throw new Error( 'Cannot set position; unsupported position value: ' + position );
8353 }
8354
8355 this.$menu.css( this.menuPosition.sizeProperty, '' );
8356 this.$element.removeClass( this.menuPosition.className );
8357
8358 this.menuPosition = positions[ position ];
8359
8360 this.updateSizes();
8361 this.$element.addClass( this.menuPosition.className );
8362
8363 return this;
8364 };
8365
8366 /**
8367 * Get menu position.
8368 *
8369 * @return {string} Menu position
8370 */
8371 OO.ui.MenuLayout.prototype.getMenuPosition = function () {
8372 return this.menuPosition;
8373 };
8374
8375 /**
8376 * Layout containing a series of pages.
8377 *
8378 * @class
8379 * @extends OO.ui.MenuLayout
8380 *
8381 * @constructor
8382 * @param {Object} [config] Configuration options
8383 * @cfg {boolean} [continuous=false] Show all pages, one after another
8384 * @cfg {boolean} [autoFocus=true] Focus on the first focusable element when changing to a page
8385 * @cfg {boolean} [outlined=false] Show an outline
8386 * @cfg {boolean} [editable=false] Show controls for adding, removing and reordering pages
8387 */
8388 OO.ui.BookletLayout = function OoUiBookletLayout( config ) {
8389 // Configuration initialization
8390 config = config || {};
8391
8392 // Parent constructor
8393 OO.ui.BookletLayout.super.call( this, config );
8394
8395 // Properties
8396 this.currentPageName = null;
8397 this.pages = {};
8398 this.ignoreFocus = false;
8399 this.stackLayout = new OO.ui.StackLayout( { continuous: !!config.continuous } );
8400 this.$content.append( this.stackLayout.$element );
8401 this.autoFocus = config.autoFocus === undefined || !!config.autoFocus;
8402 this.outlineVisible = false;
8403 this.outlined = !!config.outlined;
8404 if ( this.outlined ) {
8405 this.editable = !!config.editable;
8406 this.outlineControlsWidget = null;
8407 this.outlineSelectWidget = new OO.ui.OutlineSelectWidget();
8408 this.outlinePanel = new OO.ui.PanelLayout( { scrollable: true } );
8409 this.$menu.append( this.outlinePanel.$element );
8410 this.outlineVisible = true;
8411 if ( this.editable ) {
8412 this.outlineControlsWidget = new OO.ui.OutlineControlsWidget(
8413 this.outlineSelectWidget
8414 );
8415 }
8416 }
8417 this.toggleMenu( this.outlined );
8418
8419 // Events
8420 this.stackLayout.connect( this, { set: 'onStackLayoutSet' } );
8421 if ( this.outlined ) {
8422 this.outlineSelectWidget.connect( this, { select: 'onOutlineSelectWidgetSelect' } );
8423 }
8424 if ( this.autoFocus ) {
8425 // Event 'focus' does not bubble, but 'focusin' does
8426 this.stackLayout.$element.on( 'focusin', this.onStackLayoutFocus.bind( this ) );
8427 }
8428
8429 // Initialization
8430 this.$element.addClass( 'oo-ui-bookletLayout' );
8431 this.stackLayout.$element.addClass( 'oo-ui-bookletLayout-stackLayout' );
8432 if ( this.outlined ) {
8433 this.outlinePanel.$element
8434 .addClass( 'oo-ui-bookletLayout-outlinePanel' )
8435 .append( this.outlineSelectWidget.$element );
8436 if ( this.editable ) {
8437 this.outlinePanel.$element
8438 .addClass( 'oo-ui-bookletLayout-outlinePanel-editable' )
8439 .append( this.outlineControlsWidget.$element );
8440 }
8441 }
8442 };
8443
8444 /* Setup */
8445
8446 OO.inheritClass( OO.ui.BookletLayout, OO.ui.MenuLayout );
8447
8448 /* Events */
8449
8450 /**
8451 * @event set
8452 * @param {OO.ui.PageLayout} page Current page
8453 */
8454
8455 /**
8456 * @event add
8457 * @param {OO.ui.PageLayout[]} page Added pages
8458 * @param {number} index Index pages were added at
8459 */
8460
8461 /**
8462 * @event remove
8463 * @param {OO.ui.PageLayout[]} pages Removed pages
8464 */
8465
8466 /* Methods */
8467
8468 /**
8469 * Handle stack layout focus.
8470 *
8471 * @param {jQuery.Event} e Focusin event
8472 */
8473 OO.ui.BookletLayout.prototype.onStackLayoutFocus = function ( e ) {
8474 var name, $target;
8475
8476 // Find the page that an element was focused within
8477 $target = $( e.target ).closest( '.oo-ui-pageLayout' );
8478 for ( name in this.pages ) {
8479 // Check for page match, exclude current page to find only page changes
8480 if ( this.pages[ name ].$element[ 0 ] === $target[ 0 ] && name !== this.currentPageName ) {
8481 this.setPage( name );
8482 break;
8483 }
8484 }
8485 };
8486
8487 /**
8488 * Handle stack layout set events.
8489 *
8490 * @param {OO.ui.PanelLayout|null} page The page panel that is now the current panel
8491 */
8492 OO.ui.BookletLayout.prototype.onStackLayoutSet = function ( page ) {
8493 var layout = this;
8494 if ( page ) {
8495 page.scrollElementIntoView( { complete: function () {
8496 if ( layout.autoFocus ) {
8497 layout.focus();
8498 }
8499 } } );
8500 }
8501 };
8502
8503 /**
8504 * Focus the first input in the current page.
8505 *
8506 * If no page is selected, the first selectable page will be selected.
8507 * If the focus is already in an element on the current page, nothing will happen.
8508 */
8509 OO.ui.BookletLayout.prototype.focus = function () {
8510 var $input, page = this.stackLayout.getCurrentItem();
8511 if ( !page && this.outlined ) {
8512 this.selectFirstSelectablePage();
8513 page = this.stackLayout.getCurrentItem();
8514 }
8515 if ( !page ) {
8516 return;
8517 }
8518 // Only change the focus if is not already in the current page
8519 if ( !page.$element.find( ':focus' ).length ) {
8520 $input = page.$element.find( ':input:first' );
8521 if ( $input.length ) {
8522 $input[ 0 ].focus();
8523 }
8524 }
8525 };
8526
8527 /**
8528 * Handle outline widget select events.
8529 *
8530 * @param {OO.ui.OptionWidget|null} item Selected item
8531 */
8532 OO.ui.BookletLayout.prototype.onOutlineSelectWidgetSelect = function ( item ) {
8533 if ( item ) {
8534 this.setPage( item.getData() );
8535 }
8536 };
8537
8538 /**
8539 * Check if booklet has an outline.
8540 *
8541 * @return {boolean}
8542 */
8543 OO.ui.BookletLayout.prototype.isOutlined = function () {
8544 return this.outlined;
8545 };
8546
8547 /**
8548 * Check if booklet has editing controls.
8549 *
8550 * @return {boolean}
8551 */
8552 OO.ui.BookletLayout.prototype.isEditable = function () {
8553 return this.editable;
8554 };
8555
8556 /**
8557 * Check if booklet has a visible outline.
8558 *
8559 * @return {boolean}
8560 */
8561 OO.ui.BookletLayout.prototype.isOutlineVisible = function () {
8562 return this.outlined && this.outlineVisible;
8563 };
8564
8565 /**
8566 * Hide or show the outline.
8567 *
8568 * @param {boolean} [show] Show outline, omit to invert current state
8569 * @chainable
8570 */
8571 OO.ui.BookletLayout.prototype.toggleOutline = function ( show ) {
8572 if ( this.outlined ) {
8573 show = show === undefined ? !this.outlineVisible : !!show;
8574 this.outlineVisible = show;
8575 this.toggleMenu( show );
8576 }
8577
8578 return this;
8579 };
8580
8581 /**
8582 * Get the outline widget.
8583 *
8584 * @param {OO.ui.PageLayout} page Page to be selected
8585 * @return {OO.ui.PageLayout|null} Closest page to another
8586 */
8587 OO.ui.BookletLayout.prototype.getClosestPage = function ( page ) {
8588 var next, prev, level,
8589 pages = this.stackLayout.getItems(),
8590 index = $.inArray( page, pages );
8591
8592 if ( index !== -1 ) {
8593 next = pages[ index + 1 ];
8594 prev = pages[ index - 1 ];
8595 // Prefer adjacent pages at the same level
8596 if ( this.outlined ) {
8597 level = this.outlineSelectWidget.getItemFromData( page.getName() ).getLevel();
8598 if (
8599 prev &&
8600 level === this.outlineSelectWidget.getItemFromData( prev.getName() ).getLevel()
8601 ) {
8602 return prev;
8603 }
8604 if (
8605 next &&
8606 level === this.outlineSelectWidget.getItemFromData( next.getName() ).getLevel()
8607 ) {
8608 return next;
8609 }
8610 }
8611 }
8612 return prev || next || null;
8613 };
8614
8615 /**
8616 * Get the outline widget.
8617 *
8618 * @return {OO.ui.OutlineSelectWidget|null} Outline widget, or null if booklet has no outline
8619 */
8620 OO.ui.BookletLayout.prototype.getOutline = function () {
8621 return this.outlineSelectWidget;
8622 };
8623
8624 /**
8625 * Get the outline controls widget. If the outline is not editable, null is returned.
8626 *
8627 * @return {OO.ui.OutlineControlsWidget|null} The outline controls widget.
8628 */
8629 OO.ui.BookletLayout.prototype.getOutlineControls = function () {
8630 return this.outlineControlsWidget;
8631 };
8632
8633 /**
8634 * Get a page by name.
8635 *
8636 * @param {string} name Symbolic name of page
8637 * @return {OO.ui.PageLayout|undefined} Page, if found
8638 */
8639 OO.ui.BookletLayout.prototype.getPage = function ( name ) {
8640 return this.pages[ name ];
8641 };
8642
8643 /**
8644 * Get the current page
8645 *
8646 * @return {OO.ui.PageLayout|undefined} Current page, if found
8647 */
8648 OO.ui.BookletLayout.prototype.getCurrentPage = function () {
8649 var name = this.getCurrentPageName();
8650 return name ? this.getPage( name ) : undefined;
8651 };
8652
8653 /**
8654 * Get the current page name.
8655 *
8656 * @return {string|null} Current page name
8657 */
8658 OO.ui.BookletLayout.prototype.getCurrentPageName = function () {
8659 return this.currentPageName;
8660 };
8661
8662 /**
8663 * Add a page to the layout.
8664 *
8665 * When pages are added with the same names as existing pages, the existing pages will be
8666 * automatically removed before the new pages are added.
8667 *
8668 * @param {OO.ui.PageLayout[]} pages Pages to add
8669 * @param {number} index Index to insert pages after
8670 * @fires add
8671 * @chainable
8672 */
8673 OO.ui.BookletLayout.prototype.addPages = function ( pages, index ) {
8674 var i, len, name, page, item, currentIndex,
8675 stackLayoutPages = this.stackLayout.getItems(),
8676 remove = [],
8677 items = [];
8678
8679 // Remove pages with same names
8680 for ( i = 0, len = pages.length; i < len; i++ ) {
8681 page = pages[ i ];
8682 name = page.getName();
8683
8684 if ( Object.prototype.hasOwnProperty.call( this.pages, name ) ) {
8685 // Correct the insertion index
8686 currentIndex = $.inArray( this.pages[ name ], stackLayoutPages );
8687 if ( currentIndex !== -1 && currentIndex + 1 < index ) {
8688 index--;
8689 }
8690 remove.push( this.pages[ name ] );
8691 }
8692 }
8693 if ( remove.length ) {
8694 this.removePages( remove );
8695 }
8696
8697 // Add new pages
8698 for ( i = 0, len = pages.length; i < len; i++ ) {
8699 page = pages[ i ];
8700 name = page.getName();
8701 this.pages[ page.getName() ] = page;
8702 if ( this.outlined ) {
8703 item = new OO.ui.OutlineOptionWidget( { data: name } );
8704 page.setOutlineItem( item );
8705 items.push( item );
8706 }
8707 }
8708
8709 if ( this.outlined && items.length ) {
8710 this.outlineSelectWidget.addItems( items, index );
8711 this.selectFirstSelectablePage();
8712 }
8713 this.stackLayout.addItems( pages, index );
8714 this.emit( 'add', pages, index );
8715
8716 return this;
8717 };
8718
8719 /**
8720 * Remove a page from the layout.
8721 *
8722 * @fires remove
8723 * @chainable
8724 */
8725 OO.ui.BookletLayout.prototype.removePages = function ( pages ) {
8726 var i, len, name, page,
8727 items = [];
8728
8729 for ( i = 0, len = pages.length; i < len; i++ ) {
8730 page = pages[ i ];
8731 name = page.getName();
8732 delete this.pages[ name ];
8733 if ( this.outlined ) {
8734 items.push( this.outlineSelectWidget.getItemFromData( name ) );
8735 page.setOutlineItem( null );
8736 }
8737 }
8738 if ( this.outlined && items.length ) {
8739 this.outlineSelectWidget.removeItems( items );
8740 this.selectFirstSelectablePage();
8741 }
8742 this.stackLayout.removeItems( pages );
8743 this.emit( 'remove', pages );
8744
8745 return this;
8746 };
8747
8748 /**
8749 * Clear all pages from the layout.
8750 *
8751 * @fires remove
8752 * @chainable
8753 */
8754 OO.ui.BookletLayout.prototype.clearPages = function () {
8755 var i, len,
8756 pages = this.stackLayout.getItems();
8757
8758 this.pages = {};
8759 this.currentPageName = null;
8760 if ( this.outlined ) {
8761 this.outlineSelectWidget.clearItems();
8762 for ( i = 0, len = pages.length; i < len; i++ ) {
8763 pages[ i ].setOutlineItem( null );
8764 }
8765 }
8766 this.stackLayout.clearItems();
8767
8768 this.emit( 'remove', pages );
8769
8770 return this;
8771 };
8772
8773 /**
8774 * Set the current page by name.
8775 *
8776 * @fires set
8777 * @param {string} name Symbolic name of page
8778 */
8779 OO.ui.BookletLayout.prototype.setPage = function ( name ) {
8780 var selectedItem,
8781 $focused,
8782 page = this.pages[ name ];
8783
8784 if ( name !== this.currentPageName ) {
8785 if ( this.outlined ) {
8786 selectedItem = this.outlineSelectWidget.getSelectedItem();
8787 if ( selectedItem && selectedItem.getData() !== name ) {
8788 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getItemFromData( name ) );
8789 }
8790 }
8791 if ( page ) {
8792 if ( this.currentPageName && this.pages[ this.currentPageName ] ) {
8793 this.pages[ this.currentPageName ].setActive( false );
8794 // Blur anything focused if the next page doesn't have anything focusable - this
8795 // is not needed if the next page has something focusable because once it is focused
8796 // this blur happens automatically
8797 if ( this.autoFocus && !page.$element.find( ':input' ).length ) {
8798 $focused = this.pages[ this.currentPageName ].$element.find( ':focus' );
8799 if ( $focused.length ) {
8800 $focused[ 0 ].blur();
8801 }
8802 }
8803 }
8804 this.currentPageName = name;
8805 this.stackLayout.setItem( page );
8806 page.setActive( true );
8807 this.emit( 'set', page );
8808 }
8809 }
8810 };
8811
8812 /**
8813 * Select the first selectable page.
8814 *
8815 * @chainable
8816 */
8817 OO.ui.BookletLayout.prototype.selectFirstSelectablePage = function () {
8818 if ( !this.outlineSelectWidget.getSelectedItem() ) {
8819 this.outlineSelectWidget.selectItem( this.outlineSelectWidget.getFirstSelectableItem() );
8820 }
8821
8822 return this;
8823 };
8824
8825 /**
8826 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
8827 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
8828 *
8829 * @example
8830 * // Example of a panel layout
8831 * var panel = new OO.ui.PanelLayout( {
8832 * expanded: false,
8833 * framed: true,
8834 * padded: true,
8835 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
8836 * } );
8837 * $( 'body' ).append( panel.$element );
8838 *
8839 * @class
8840 * @extends OO.ui.Layout
8841 *
8842 * @constructor
8843 * @param {Object} [config] Configuration options
8844 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
8845 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
8846 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
8847 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
8848 */
8849 OO.ui.PanelLayout = function OoUiPanelLayout( config ) {
8850 // Configuration initialization
8851 config = $.extend( {
8852 scrollable: false,
8853 padded: false,
8854 expanded: true,
8855 framed: false
8856 }, config );
8857
8858 // Parent constructor
8859 OO.ui.PanelLayout.super.call( this, config );
8860
8861 // Initialization
8862 this.$element.addClass( 'oo-ui-panelLayout' );
8863 if ( config.scrollable ) {
8864 this.$element.addClass( 'oo-ui-panelLayout-scrollable' );
8865 }
8866 if ( config.padded ) {
8867 this.$element.addClass( 'oo-ui-panelLayout-padded' );
8868 }
8869 if ( config.expanded ) {
8870 this.$element.addClass( 'oo-ui-panelLayout-expanded' );
8871 }
8872 if ( config.framed ) {
8873 this.$element.addClass( 'oo-ui-panelLayout-framed' );
8874 }
8875 };
8876
8877 /* Setup */
8878
8879 OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout );
8880
8881 /**
8882 * Page within an booklet layout.
8883 *
8884 * @class
8885 * @extends OO.ui.PanelLayout
8886 *
8887 * @constructor
8888 * @param {string} name Unique symbolic name of page
8889 * @param {Object} [config] Configuration options
8890 */
8891 OO.ui.PageLayout = function OoUiPageLayout( name, config ) {
8892 // Allow passing positional parameters inside the config object
8893 if ( OO.isPlainObject( name ) && config === undefined ) {
8894 config = name;
8895 name = config.name;
8896 }
8897
8898 // Configuration initialization
8899 config = $.extend( { scrollable: true }, config );
8900
8901 // Parent constructor
8902 OO.ui.PageLayout.super.call( this, config );
8903
8904 // Properties
8905 this.name = name;
8906 this.outlineItem = null;
8907 this.active = false;
8908
8909 // Initialization
8910 this.$element.addClass( 'oo-ui-pageLayout' );
8911 };
8912
8913 /* Setup */
8914
8915 OO.inheritClass( OO.ui.PageLayout, OO.ui.PanelLayout );
8916
8917 /* Events */
8918
8919 /**
8920 * @event active
8921 * @param {boolean} active Page is active
8922 */
8923
8924 /* Methods */
8925
8926 /**
8927 * Get page name.
8928 *
8929 * @return {string} Symbolic name of page
8930 */
8931 OO.ui.PageLayout.prototype.getName = function () {
8932 return this.name;
8933 };
8934
8935 /**
8936 * Check if page is active.
8937 *
8938 * @return {boolean} Page is active
8939 */
8940 OO.ui.PageLayout.prototype.isActive = function () {
8941 return this.active;
8942 };
8943
8944 /**
8945 * Get outline item.
8946 *
8947 * @return {OO.ui.OutlineOptionWidget|null} Outline item widget
8948 */
8949 OO.ui.PageLayout.prototype.getOutlineItem = function () {
8950 return this.outlineItem;
8951 };
8952
8953 /**
8954 * Set outline item.
8955 *
8956 * @localdoc Subclasses should override #setupOutlineItem instead of this method to adjust the
8957 * outline item as desired; this method is called for setting (with an object) and unsetting
8958 * (with null) and overriding methods would have to check the value of `outlineItem` to avoid
8959 * operating on null instead of an OO.ui.OutlineOptionWidget object.
8960 *
8961 * @param {OO.ui.OutlineOptionWidget|null} outlineItem Outline item widget, null to clear
8962 * @chainable
8963 */
8964 OO.ui.PageLayout.prototype.setOutlineItem = function ( outlineItem ) {
8965 this.outlineItem = outlineItem || null;
8966 if ( outlineItem ) {
8967 this.setupOutlineItem();
8968 }
8969 return this;
8970 };
8971
8972 /**
8973 * Setup outline item.
8974 *
8975 * @localdoc Subclasses should override this method to adjust the outline item as desired.
8976 *
8977 * @param {OO.ui.OutlineOptionWidget} outlineItem Outline item widget to setup
8978 * @chainable
8979 */
8980 OO.ui.PageLayout.prototype.setupOutlineItem = function () {
8981 return this;
8982 };
8983
8984 /**
8985 * Set page active state.
8986 *
8987 * @param {boolean} Page is active
8988 * @fires active
8989 */
8990 OO.ui.PageLayout.prototype.setActive = function ( active ) {
8991 active = !!active;
8992
8993 if ( active !== this.active ) {
8994 this.active = active;
8995 this.$element.toggleClass( 'oo-ui-pageLayout-active', active );
8996 this.emit( 'active', this.active );
8997 }
8998 };
8999
9000 /**
9001 * Layout containing a series of mutually exclusive pages.
9002 *
9003 * @class
9004 * @extends OO.ui.PanelLayout
9005 * @mixins OO.ui.GroupElement
9006 *
9007 * @constructor
9008 * @param {Object} [config] Configuration options
9009 * @cfg {boolean} [continuous=false] Show all pages, one after another
9010 * @cfg {OO.ui.Layout[]} [items] Layouts to add
9011 */
9012 OO.ui.StackLayout = function OoUiStackLayout( config ) {
9013 // Configuration initialization
9014 config = $.extend( { scrollable: true }, config );
9015
9016 // Parent constructor
9017 OO.ui.StackLayout.super.call( this, config );
9018
9019 // Mixin constructors
9020 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
9021
9022 // Properties
9023 this.currentItem = null;
9024 this.continuous = !!config.continuous;
9025
9026 // Initialization
9027 this.$element.addClass( 'oo-ui-stackLayout' );
9028 if ( this.continuous ) {
9029 this.$element.addClass( 'oo-ui-stackLayout-continuous' );
9030 }
9031 if ( Array.isArray( config.items ) ) {
9032 this.addItems( config.items );
9033 }
9034 };
9035
9036 /* Setup */
9037
9038 OO.inheritClass( OO.ui.StackLayout, OO.ui.PanelLayout );
9039 OO.mixinClass( OO.ui.StackLayout, OO.ui.GroupElement );
9040
9041 /* Events */
9042
9043 /**
9044 * @event set
9045 * @param {OO.ui.Layout|null} item Current item or null if there is no longer a layout shown
9046 */
9047
9048 /* Methods */
9049
9050 /**
9051 * Get the current item.
9052 *
9053 * @return {OO.ui.Layout|null}
9054 */
9055 OO.ui.StackLayout.prototype.getCurrentItem = function () {
9056 return this.currentItem;
9057 };
9058
9059 /**
9060 * Unset the current item.
9061 *
9062 * @private
9063 * @param {OO.ui.StackLayout} layout
9064 * @fires set
9065 */
9066 OO.ui.StackLayout.prototype.unsetCurrentItem = function () {
9067 var prevItem = this.currentItem;
9068 if ( prevItem === null ) {
9069 return;
9070 }
9071
9072 this.currentItem = null;
9073 this.emit( 'set', null );
9074 };
9075
9076 /**
9077 * Add items.
9078 *
9079 * Adding an existing item (by value) will move it.
9080 *
9081 * @param {OO.ui.Layout[]} items Items to add
9082 * @param {number} [index] Index to insert items after
9083 * @chainable
9084 */
9085 OO.ui.StackLayout.prototype.addItems = function ( items, index ) {
9086 // Update the visibility
9087 this.updateHiddenState( items, this.currentItem );
9088
9089 // Mixin method
9090 OO.ui.GroupElement.prototype.addItems.call( this, items, index );
9091
9092 if ( !this.currentItem && items.length ) {
9093 this.setItem( items[ 0 ] );
9094 }
9095
9096 return this;
9097 };
9098
9099 /**
9100 * Remove items.
9101 *
9102 * Items will be detached, not removed, so they can be used later.
9103 *
9104 * @param {OO.ui.Layout[]} items Items to remove
9105 * @chainable
9106 * @fires set
9107 */
9108 OO.ui.StackLayout.prototype.removeItems = function ( items ) {
9109 // Mixin method
9110 OO.ui.GroupElement.prototype.removeItems.call( this, items );
9111
9112 if ( $.inArray( this.currentItem, items ) !== -1 ) {
9113 if ( this.items.length ) {
9114 this.setItem( this.items[ 0 ] );
9115 } else {
9116 this.unsetCurrentItem();
9117 }
9118 }
9119
9120 return this;
9121 };
9122
9123 /**
9124 * Clear all items.
9125 *
9126 * Items will be detached, not removed, so they can be used later.
9127 *
9128 * @chainable
9129 * @fires set
9130 */
9131 OO.ui.StackLayout.prototype.clearItems = function () {
9132 this.unsetCurrentItem();
9133 OO.ui.GroupElement.prototype.clearItems.call( this );
9134
9135 return this;
9136 };
9137
9138 /**
9139 * Show item.
9140 *
9141 * Any currently shown item will be hidden.
9142 *
9143 * FIXME: If the passed item to show has not been added in the items list, then
9144 * this method drops it and unsets the current item.
9145 *
9146 * @param {OO.ui.Layout} item Item to show
9147 * @chainable
9148 * @fires set
9149 */
9150 OO.ui.StackLayout.prototype.setItem = function ( item ) {
9151 if ( item !== this.currentItem ) {
9152 this.updateHiddenState( this.items, item );
9153
9154 if ( $.inArray( item, this.items ) !== -1 ) {
9155 this.currentItem = item;
9156 this.emit( 'set', item );
9157 } else {
9158 this.unsetCurrentItem();
9159 }
9160 }
9161
9162 return this;
9163 };
9164
9165 /**
9166 * Update the visibility of all items in case of non-continuous view.
9167 *
9168 * Ensure all items are hidden except for the selected one.
9169 * This method does nothing when the stack is continuous.
9170 *
9171 * @param {OO.ui.Layout[]} items Item list iterate over
9172 * @param {OO.ui.Layout} [selectedItem] Selected item to show
9173 */
9174 OO.ui.StackLayout.prototype.updateHiddenState = function ( items, selectedItem ) {
9175 var i, len;
9176
9177 if ( !this.continuous ) {
9178 for ( i = 0, len = items.length; i < len; i++ ) {
9179 if ( !selectedItem || selectedItem !== items[ i ] ) {
9180 items[ i ].$element.addClass( 'oo-ui-element-hidden' );
9181 }
9182 }
9183 if ( selectedItem ) {
9184 selectedItem.$element.removeClass( 'oo-ui-element-hidden' );
9185 }
9186 }
9187 };
9188
9189 /**
9190 * Horizontal bar layout of tools as icon buttons.
9191 *
9192 * @class
9193 * @extends OO.ui.ToolGroup
9194 *
9195 * @constructor
9196 * @param {OO.ui.Toolbar} toolbar
9197 * @param {Object} [config] Configuration options
9198 */
9199 OO.ui.BarToolGroup = function OoUiBarToolGroup( toolbar, config ) {
9200 // Allow passing positional parameters inside the config object
9201 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9202 config = toolbar;
9203 toolbar = config.toolbar;
9204 }
9205
9206 // Parent constructor
9207 OO.ui.BarToolGroup.super.call( this, toolbar, config );
9208
9209 // Initialization
9210 this.$element.addClass( 'oo-ui-barToolGroup' );
9211 };
9212
9213 /* Setup */
9214
9215 OO.inheritClass( OO.ui.BarToolGroup, OO.ui.ToolGroup );
9216
9217 /* Static Properties */
9218
9219 OO.ui.BarToolGroup.static.titleTooltips = true;
9220
9221 OO.ui.BarToolGroup.static.accelTooltips = true;
9222
9223 OO.ui.BarToolGroup.static.name = 'bar';
9224
9225 /**
9226 * Popup list of tools with an icon and optional label.
9227 *
9228 * @abstract
9229 * @class
9230 * @extends OO.ui.ToolGroup
9231 * @mixins OO.ui.IconElement
9232 * @mixins OO.ui.IndicatorElement
9233 * @mixins OO.ui.LabelElement
9234 * @mixins OO.ui.TitledElement
9235 * @mixins OO.ui.ClippableElement
9236 *
9237 * @constructor
9238 * @param {OO.ui.Toolbar} toolbar
9239 * @param {Object} [config] Configuration options
9240 * @cfg {string} [header] Text to display at the top of the pop-up
9241 */
9242 OO.ui.PopupToolGroup = function OoUiPopupToolGroup( toolbar, config ) {
9243 // Allow passing positional parameters inside the config object
9244 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9245 config = toolbar;
9246 toolbar = config.toolbar;
9247 }
9248
9249 // Configuration initialization
9250 config = config || {};
9251
9252 // Parent constructor
9253 OO.ui.PopupToolGroup.super.call( this, toolbar, config );
9254
9255 // Mixin constructors
9256 OO.ui.IconElement.call( this, config );
9257 OO.ui.IndicatorElement.call( this, config );
9258 OO.ui.LabelElement.call( this, config );
9259 OO.ui.TitledElement.call( this, config );
9260 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
9261
9262 // Properties
9263 this.active = false;
9264 this.dragging = false;
9265 this.onBlurHandler = this.onBlur.bind( this );
9266 this.$handle = $( '<span>' );
9267
9268 // Events
9269 this.$handle.on( {
9270 mousedown: this.onHandlePointerDown.bind( this ),
9271 mouseup: this.onHandlePointerUp.bind( this )
9272 } );
9273
9274 // Initialization
9275 this.$handle
9276 .addClass( 'oo-ui-popupToolGroup-handle' )
9277 .append( this.$icon, this.$label, this.$indicator );
9278 // If the pop-up should have a header, add it to the top of the toolGroup.
9279 // Note: If this feature is useful for other widgets, we could abstract it into an
9280 // OO.ui.HeaderedElement mixin constructor.
9281 if ( config.header !== undefined ) {
9282 this.$group
9283 .prepend( $( '<span>' )
9284 .addClass( 'oo-ui-popupToolGroup-header' )
9285 .text( config.header )
9286 );
9287 }
9288 this.$element
9289 .addClass( 'oo-ui-popupToolGroup' )
9290 .prepend( this.$handle );
9291 };
9292
9293 /* Setup */
9294
9295 OO.inheritClass( OO.ui.PopupToolGroup, OO.ui.ToolGroup );
9296 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IconElement );
9297 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.IndicatorElement );
9298 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.LabelElement );
9299 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.TitledElement );
9300 OO.mixinClass( OO.ui.PopupToolGroup, OO.ui.ClippableElement );
9301
9302 /* Static Properties */
9303
9304 /* Methods */
9305
9306 /**
9307 * @inheritdoc
9308 */
9309 OO.ui.PopupToolGroup.prototype.setDisabled = function () {
9310 // Parent method
9311 OO.ui.PopupToolGroup.super.prototype.setDisabled.apply( this, arguments );
9312
9313 if ( this.isDisabled() && this.isElementAttached() ) {
9314 this.setActive( false );
9315 }
9316 };
9317
9318 /**
9319 * Handle focus being lost.
9320 *
9321 * The event is actually generated from a mouseup, so it is not a normal blur event object.
9322 *
9323 * @param {jQuery.Event} e Mouse up event
9324 */
9325 OO.ui.PopupToolGroup.prototype.onBlur = function ( e ) {
9326 // Only deactivate when clicking outside the dropdown element
9327 if ( $( e.target ).closest( '.oo-ui-popupToolGroup' )[ 0 ] !== this.$element[ 0 ] ) {
9328 this.setActive( false );
9329 }
9330 };
9331
9332 /**
9333 * @inheritdoc
9334 */
9335 OO.ui.PopupToolGroup.prototype.onPointerUp = function ( e ) {
9336 // Only close toolgroup when a tool was actually selected
9337 if ( !this.isDisabled() && e.which === 1 && this.pressed && this.pressed === this.getTargetTool( e ) ) {
9338 this.setActive( false );
9339 }
9340 return OO.ui.PopupToolGroup.super.prototype.onPointerUp.call( this, e );
9341 };
9342
9343 /**
9344 * Handle mouse up events.
9345 *
9346 * @param {jQuery.Event} e Mouse up event
9347 */
9348 OO.ui.PopupToolGroup.prototype.onHandlePointerUp = function () {
9349 return false;
9350 };
9351
9352 /**
9353 * Handle mouse down events.
9354 *
9355 * @param {jQuery.Event} e Mouse down event
9356 */
9357 OO.ui.PopupToolGroup.prototype.onHandlePointerDown = function ( e ) {
9358 if ( !this.isDisabled() && e.which === 1 ) {
9359 this.setActive( !this.active );
9360 }
9361 return false;
9362 };
9363
9364 /**
9365 * Switch into active mode.
9366 *
9367 * When active, mouseup events anywhere in the document will trigger deactivation.
9368 */
9369 OO.ui.PopupToolGroup.prototype.setActive = function ( value ) {
9370 value = !!value;
9371 if ( this.active !== value ) {
9372 this.active = value;
9373 if ( value ) {
9374 this.getElementDocument().addEventListener( 'mouseup', this.onBlurHandler, true );
9375
9376 // Try anchoring the popup to the left first
9377 this.$element.addClass( 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left' );
9378 this.toggleClipping( true );
9379 if ( this.isClippedHorizontally() ) {
9380 // Anchoring to the left caused the popup to clip, so anchor it to the right instead
9381 this.toggleClipping( false );
9382 this.$element
9383 .removeClass( 'oo-ui-popupToolGroup-left' )
9384 .addClass( 'oo-ui-popupToolGroup-right' );
9385 this.toggleClipping( true );
9386 }
9387 } else {
9388 this.getElementDocument().removeEventListener( 'mouseup', this.onBlurHandler, true );
9389 this.$element.removeClass(
9390 'oo-ui-popupToolGroup-active oo-ui-popupToolGroup-left oo-ui-popupToolGroup-right'
9391 );
9392 this.toggleClipping( false );
9393 }
9394 }
9395 };
9396
9397 /**
9398 * Drop down list layout of tools as labeled icon buttons.
9399 *
9400 * This layout allows some tools to be collapsible, controlled by a "More" / "Fewer" option at the
9401 * bottom of the main list. These are not automatically positioned at the bottom of the list; you
9402 * may want to use the 'promote' and 'demote' configuration options to achieve this.
9403 *
9404 * @class
9405 * @extends OO.ui.PopupToolGroup
9406 *
9407 * @constructor
9408 * @param {OO.ui.Toolbar} toolbar
9409 * @param {Object} [config] Configuration options
9410 * @cfg {Array} [allowCollapse] List of tools that can be collapsed. Remaining tools will be always
9411 * shown.
9412 * @cfg {Array} [forceExpand] List of tools that *may not* be collapsed. All remaining tools will be
9413 * allowed to be collapsed.
9414 * @cfg {boolean} [expanded=false] Whether the collapsible tools are expanded by default
9415 */
9416 OO.ui.ListToolGroup = function OoUiListToolGroup( toolbar, config ) {
9417 // Allow passing positional parameters inside the config object
9418 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9419 config = toolbar;
9420 toolbar = config.toolbar;
9421 }
9422
9423 // Configuration initialization
9424 config = config || {};
9425
9426 // Properties (must be set before parent constructor, which calls #populate)
9427 this.allowCollapse = config.allowCollapse;
9428 this.forceExpand = config.forceExpand;
9429 this.expanded = config.expanded !== undefined ? config.expanded : false;
9430 this.collapsibleTools = [];
9431
9432 // Parent constructor
9433 OO.ui.ListToolGroup.super.call( this, toolbar, config );
9434
9435 // Initialization
9436 this.$element.addClass( 'oo-ui-listToolGroup' );
9437 };
9438
9439 /* Setup */
9440
9441 OO.inheritClass( OO.ui.ListToolGroup, OO.ui.PopupToolGroup );
9442
9443 /* Static Properties */
9444
9445 OO.ui.ListToolGroup.static.accelTooltips = true;
9446
9447 OO.ui.ListToolGroup.static.name = 'list';
9448
9449 /* Methods */
9450
9451 /**
9452 * @inheritdoc
9453 */
9454 OO.ui.ListToolGroup.prototype.populate = function () {
9455 var i, len, allowCollapse = [];
9456
9457 OO.ui.ListToolGroup.super.prototype.populate.call( this );
9458
9459 // Update the list of collapsible tools
9460 if ( this.allowCollapse !== undefined ) {
9461 allowCollapse = this.allowCollapse;
9462 } else if ( this.forceExpand !== undefined ) {
9463 allowCollapse = OO.simpleArrayDifference( Object.keys( this.tools ), this.forceExpand );
9464 }
9465
9466 this.collapsibleTools = [];
9467 for ( i = 0, len = allowCollapse.length; i < len; i++ ) {
9468 if ( this.tools[ allowCollapse[ i ] ] !== undefined ) {
9469 this.collapsibleTools.push( this.tools[ allowCollapse[ i ] ] );
9470 }
9471 }
9472
9473 // Keep at the end, even when tools are added
9474 this.$group.append( this.getExpandCollapseTool().$element );
9475
9476 this.getExpandCollapseTool().toggle( this.collapsibleTools.length !== 0 );
9477 this.updateCollapsibleState();
9478 };
9479
9480 OO.ui.ListToolGroup.prototype.getExpandCollapseTool = function () {
9481 if ( this.expandCollapseTool === undefined ) {
9482 var ExpandCollapseTool = function () {
9483 ExpandCollapseTool.super.apply( this, arguments );
9484 };
9485
9486 OO.inheritClass( ExpandCollapseTool, OO.ui.Tool );
9487
9488 ExpandCollapseTool.prototype.onSelect = function () {
9489 this.toolGroup.expanded = !this.toolGroup.expanded;
9490 this.toolGroup.updateCollapsibleState();
9491 this.setActive( false );
9492 };
9493 ExpandCollapseTool.prototype.onUpdateState = function () {
9494 // Do nothing. Tool interface requires an implementation of this function.
9495 };
9496
9497 ExpandCollapseTool.static.name = 'more-fewer';
9498
9499 this.expandCollapseTool = new ExpandCollapseTool( this );
9500 }
9501 return this.expandCollapseTool;
9502 };
9503
9504 /**
9505 * @inheritdoc
9506 */
9507 OO.ui.ListToolGroup.prototype.onPointerUp = function ( e ) {
9508 var ret = OO.ui.ListToolGroup.super.prototype.onPointerUp.call( this, e );
9509
9510 // Do not close the popup when the user wants to show more/fewer tools
9511 if ( $( e.target ).closest( '.oo-ui-tool-name-more-fewer' ).length ) {
9512 // Prevent the popup list from being hidden
9513 this.setActive( true );
9514 }
9515
9516 return ret;
9517 };
9518
9519 OO.ui.ListToolGroup.prototype.updateCollapsibleState = function () {
9520 var i, len;
9521
9522 this.getExpandCollapseTool()
9523 .setIcon( this.expanded ? 'collapse' : 'expand' )
9524 .setTitle( OO.ui.msg( this.expanded ? 'ooui-toolgroup-collapse' : 'ooui-toolgroup-expand' ) );
9525
9526 for ( i = 0, len = this.collapsibleTools.length; i < len; i++ ) {
9527 this.collapsibleTools[ i ].toggle( this.expanded );
9528 }
9529 };
9530
9531 /**
9532 * Drop down menu layout of tools as selectable menu items.
9533 *
9534 * @class
9535 * @extends OO.ui.PopupToolGroup
9536 *
9537 * @constructor
9538 * @param {OO.ui.Toolbar} toolbar
9539 * @param {Object} [config] Configuration options
9540 */
9541 OO.ui.MenuToolGroup = function OoUiMenuToolGroup( toolbar, config ) {
9542 // Allow passing positional parameters inside the config object
9543 if ( OO.isPlainObject( toolbar ) && config === undefined ) {
9544 config = toolbar;
9545 toolbar = config.toolbar;
9546 }
9547
9548 // Configuration initialization
9549 config = config || {};
9550
9551 // Parent constructor
9552 OO.ui.MenuToolGroup.super.call( this, toolbar, config );
9553
9554 // Events
9555 this.toolbar.connect( this, { updateState: 'onUpdateState' } );
9556
9557 // Initialization
9558 this.$element.addClass( 'oo-ui-menuToolGroup' );
9559 };
9560
9561 /* Setup */
9562
9563 OO.inheritClass( OO.ui.MenuToolGroup, OO.ui.PopupToolGroup );
9564
9565 /* Static Properties */
9566
9567 OO.ui.MenuToolGroup.static.accelTooltips = true;
9568
9569 OO.ui.MenuToolGroup.static.name = 'menu';
9570
9571 /* Methods */
9572
9573 /**
9574 * Handle the toolbar state being updated.
9575 *
9576 * When the state changes, the title of each active item in the menu will be joined together and
9577 * used as a label for the group. The label will be empty if none of the items are active.
9578 */
9579 OO.ui.MenuToolGroup.prototype.onUpdateState = function () {
9580 var name,
9581 labelTexts = [];
9582
9583 for ( name in this.tools ) {
9584 if ( this.tools[ name ].isActive() ) {
9585 labelTexts.push( this.tools[ name ].getTitle() );
9586 }
9587 }
9588
9589 this.setLabel( labelTexts.join( ', ' ) || ' ' );
9590 };
9591
9592 /**
9593 * Tool that shows a popup when selected.
9594 *
9595 * @abstract
9596 * @class
9597 * @extends OO.ui.Tool
9598 * @mixins OO.ui.PopupElement
9599 *
9600 * @constructor
9601 * @param {OO.ui.ToolGroup} toolGroup
9602 * @param {Object} [config] Configuration options
9603 */
9604 OO.ui.PopupTool = function OoUiPopupTool( toolGroup, config ) {
9605 // Allow passing positional parameters inside the config object
9606 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9607 config = toolGroup;
9608 toolGroup = config.toolGroup;
9609 }
9610
9611 // Parent constructor
9612 OO.ui.PopupTool.super.call( this, toolGroup, config );
9613
9614 // Mixin constructors
9615 OO.ui.PopupElement.call( this, config );
9616
9617 // Initialization
9618 this.$element
9619 .addClass( 'oo-ui-popupTool' )
9620 .append( this.popup.$element );
9621 };
9622
9623 /* Setup */
9624
9625 OO.inheritClass( OO.ui.PopupTool, OO.ui.Tool );
9626 OO.mixinClass( OO.ui.PopupTool, OO.ui.PopupElement );
9627
9628 /* Methods */
9629
9630 /**
9631 * Handle the tool being selected.
9632 *
9633 * @inheritdoc
9634 */
9635 OO.ui.PopupTool.prototype.onSelect = function () {
9636 if ( !this.isDisabled() ) {
9637 this.popup.toggle();
9638 }
9639 this.setActive( false );
9640 return false;
9641 };
9642
9643 /**
9644 * Handle the toolbar state being updated.
9645 *
9646 * @inheritdoc
9647 */
9648 OO.ui.PopupTool.prototype.onUpdateState = function () {
9649 this.setActive( false );
9650 };
9651
9652 /**
9653 * Tool that has a tool group inside. This is a bad workaround for the lack of proper hierarchical
9654 * menus in toolbars (T74159).
9655 *
9656 * @abstract
9657 * @class
9658 * @extends OO.ui.Tool
9659 *
9660 * @constructor
9661 * @param {OO.ui.ToolGroup} toolGroup
9662 * @param {Object} [config] Configuration options
9663 */
9664 OO.ui.ToolGroupTool = function OoUiToolGroupTool( toolGroup, config ) {
9665 // Allow passing positional parameters inside the config object
9666 if ( OO.isPlainObject( toolGroup ) && config === undefined ) {
9667 config = toolGroup;
9668 toolGroup = config.toolGroup;
9669 }
9670
9671 // Parent constructor
9672 OO.ui.ToolGroupTool.super.call( this, toolGroup, config );
9673
9674 // Properties
9675 this.innerToolGroup = this.createGroup( this.constructor.static.groupConfig );
9676
9677 // Initialization
9678 this.$link.remove();
9679 this.$element
9680 .addClass( 'oo-ui-toolGroupTool' )
9681 .append( this.innerToolGroup.$element );
9682 };
9683
9684 /* Setup */
9685
9686 OO.inheritClass( OO.ui.ToolGroupTool, OO.ui.Tool );
9687
9688 /* Static Properties */
9689
9690 /**
9691 * Tool group configuration. See OO.ui.Toolbar#setup for the accepted values.
9692 *
9693 * @property {Object.<string,Array>}
9694 */
9695 OO.ui.ToolGroupTool.static.groupConfig = {};
9696
9697 /* Methods */
9698
9699 /**
9700 * Handle the tool being selected.
9701 *
9702 * @inheritdoc
9703 */
9704 OO.ui.ToolGroupTool.prototype.onSelect = function () {
9705 this.innerToolGroup.setActive( !this.innerToolGroup.active );
9706 return false;
9707 };
9708
9709 /**
9710 * Handle the toolbar state being updated.
9711 *
9712 * @inheritdoc
9713 */
9714 OO.ui.ToolGroupTool.prototype.onUpdateState = function () {
9715 this.setActive( false );
9716 };
9717
9718 /**
9719 * Build a OO.ui.ToolGroup from the configuration.
9720 *
9721 * @param {Object.<string,Array>} group Tool group configuration. See OO.ui.Toolbar#setup for the
9722 * accepted values.
9723 * @return {OO.ui.ListToolGroup}
9724 */
9725 OO.ui.ToolGroupTool.prototype.createGroup = function ( group ) {
9726 if ( group.include === '*' ) {
9727 // Apply defaults to catch-all groups
9728 if ( group.label === undefined ) {
9729 group.label = OO.ui.msg( 'ooui-toolbar-more' );
9730 }
9731 }
9732
9733 return this.toolbar.getToolGroupFactory().create( 'list', this.toolbar, group );
9734 };
9735
9736 /**
9737 * Mixin for OO.ui.Widget subclasses to provide OO.ui.GroupElement.
9738 *
9739 * Use together with OO.ui.ItemWidget to make disabled state inheritable.
9740 *
9741 * @private
9742 * @abstract
9743 * @class
9744 * @extends OO.ui.GroupElement
9745 *
9746 * @constructor
9747 * @param {Object} [config] Configuration options
9748 */
9749 OO.ui.GroupWidget = function OoUiGroupWidget( config ) {
9750 // Parent constructor
9751 OO.ui.GroupWidget.super.call( this, config );
9752 };
9753
9754 /* Setup */
9755
9756 OO.inheritClass( OO.ui.GroupWidget, OO.ui.GroupElement );
9757
9758 /* Methods */
9759
9760 /**
9761 * Set the disabled state of the widget.
9762 *
9763 * This will also update the disabled state of child widgets.
9764 *
9765 * @param {boolean} disabled Disable widget
9766 * @chainable
9767 */
9768 OO.ui.GroupWidget.prototype.setDisabled = function ( disabled ) {
9769 var i, len;
9770
9771 // Parent method
9772 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
9773 OO.ui.Widget.prototype.setDisabled.call( this, disabled );
9774
9775 // During construction, #setDisabled is called before the OO.ui.GroupElement constructor
9776 if ( this.items ) {
9777 for ( i = 0, len = this.items.length; i < len; i++ ) {
9778 this.items[ i ].updateDisabled();
9779 }
9780 }
9781
9782 return this;
9783 };
9784
9785 /**
9786 * Mixin for widgets used as items in widgets that inherit OO.ui.GroupWidget.
9787 *
9788 * Item widgets have a reference to a OO.ui.GroupWidget while they are attached to the group. This
9789 * allows bidirectional communication.
9790 *
9791 * Use together with OO.ui.GroupWidget to make disabled state inheritable.
9792 *
9793 * @private
9794 * @abstract
9795 * @class
9796 *
9797 * @constructor
9798 */
9799 OO.ui.ItemWidget = function OoUiItemWidget() {
9800 //
9801 };
9802
9803 /* Methods */
9804
9805 /**
9806 * Check if widget is disabled.
9807 *
9808 * Checks parent if present, making disabled state inheritable.
9809 *
9810 * @return {boolean} Widget is disabled
9811 */
9812 OO.ui.ItemWidget.prototype.isDisabled = function () {
9813 return this.disabled ||
9814 ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() );
9815 };
9816
9817 /**
9818 * Set group element is in.
9819 *
9820 * @param {OO.ui.GroupElement|null} group Group element, null if none
9821 * @chainable
9822 */
9823 OO.ui.ItemWidget.prototype.setElementGroup = function ( group ) {
9824 // Parent method
9825 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
9826 OO.ui.Element.prototype.setElementGroup.call( this, group );
9827
9828 // Initialize item disabled states
9829 this.updateDisabled();
9830
9831 return this;
9832 };
9833
9834 /**
9835 * OutlineControlsWidget is a set of controls for an {@link OO.ui.OutlineSelectWidget outline select widget}.
9836 * Controls include moving items up and down, removing items, and adding different kinds of items.
9837 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
9838 *
9839 * @class
9840 * @extends OO.ui.Widget
9841 * @mixins OO.ui.GroupElement
9842 * @mixins OO.ui.IconElement
9843 *
9844 * @constructor
9845 * @param {OO.ui.OutlineSelectWidget} outline Outline to control
9846 * @param {Object} [config] Configuration options
9847 * @cfg {Object} [abilities] List of abilties
9848 * @cfg {boolean} [abilities.move=true] Allow moving movable items
9849 * @cfg {boolean} [abilities.remove=true] Allow removing removable items
9850 */
9851 OO.ui.OutlineControlsWidget = function OoUiOutlineControlsWidget( outline, config ) {
9852 // Allow passing positional parameters inside the config object
9853 if ( OO.isPlainObject( outline ) && config === undefined ) {
9854 config = outline;
9855 outline = config.outline;
9856 }
9857
9858 // Configuration initialization
9859 config = $.extend( { icon: 'add' }, config );
9860
9861 // Parent constructor
9862 OO.ui.OutlineControlsWidget.super.call( this, config );
9863
9864 // Mixin constructors
9865 OO.ui.GroupElement.call( this, config );
9866 OO.ui.IconElement.call( this, config );
9867
9868 // Properties
9869 this.outline = outline;
9870 this.$movers = $( '<div>' );
9871 this.upButton = new OO.ui.ButtonWidget( {
9872 framed: false,
9873 icon: 'collapse',
9874 title: OO.ui.msg( 'ooui-outline-control-move-up' )
9875 } );
9876 this.downButton = new OO.ui.ButtonWidget( {
9877 framed: false,
9878 icon: 'expand',
9879 title: OO.ui.msg( 'ooui-outline-control-move-down' )
9880 } );
9881 this.removeButton = new OO.ui.ButtonWidget( {
9882 framed: false,
9883 icon: 'remove',
9884 title: OO.ui.msg( 'ooui-outline-control-remove' )
9885 } );
9886 this.abilities = { move: true, remove: true };
9887
9888 // Events
9889 outline.connect( this, {
9890 select: 'onOutlineChange',
9891 add: 'onOutlineChange',
9892 remove: 'onOutlineChange'
9893 } );
9894 this.upButton.connect( this, { click: [ 'emit', 'move', -1 ] } );
9895 this.downButton.connect( this, { click: [ 'emit', 'move', 1 ] } );
9896 this.removeButton.connect( this, { click: [ 'emit', 'remove' ] } );
9897
9898 // Initialization
9899 this.$element.addClass( 'oo-ui-outlineControlsWidget' );
9900 this.$group.addClass( 'oo-ui-outlineControlsWidget-items' );
9901 this.$movers
9902 .addClass( 'oo-ui-outlineControlsWidget-movers' )
9903 .append( this.removeButton.$element, this.upButton.$element, this.downButton.$element );
9904 this.$element.append( this.$icon, this.$group, this.$movers );
9905 this.setAbilities( config.abilities || {} );
9906 };
9907
9908 /* Setup */
9909
9910 OO.inheritClass( OO.ui.OutlineControlsWidget, OO.ui.Widget );
9911 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.GroupElement );
9912 OO.mixinClass( OO.ui.OutlineControlsWidget, OO.ui.IconElement );
9913
9914 /* Events */
9915
9916 /**
9917 * @event move
9918 * @param {number} places Number of places to move
9919 */
9920
9921 /**
9922 * @event remove
9923 */
9924
9925 /* Methods */
9926
9927 /**
9928 * Set abilities.
9929 *
9930 * @param {Object} abilities List of abilties
9931 * @param {boolean} [abilities.move] Allow moving movable items
9932 * @param {boolean} [abilities.remove] Allow removing removable items
9933 */
9934 OO.ui.OutlineControlsWidget.prototype.setAbilities = function ( abilities ) {
9935 var ability;
9936
9937 for ( ability in this.abilities ) {
9938 if ( abilities[ability] !== undefined ) {
9939 this.abilities[ability] = !!abilities[ability];
9940 }
9941 }
9942
9943 this.onOutlineChange();
9944 };
9945
9946 /**
9947 *
9948 * @private
9949 * Handle outline change events.
9950 */
9951 OO.ui.OutlineControlsWidget.prototype.onOutlineChange = function () {
9952 var i, len, firstMovable, lastMovable,
9953 items = this.outline.getItems(),
9954 selectedItem = this.outline.getSelectedItem(),
9955 movable = this.abilities.move && selectedItem && selectedItem.isMovable(),
9956 removable = this.abilities.remove && selectedItem && selectedItem.isRemovable();
9957
9958 if ( movable ) {
9959 i = -1;
9960 len = items.length;
9961 while ( ++i < len ) {
9962 if ( items[ i ].isMovable() ) {
9963 firstMovable = items[ i ];
9964 break;
9965 }
9966 }
9967 i = len;
9968 while ( i-- ) {
9969 if ( items[ i ].isMovable() ) {
9970 lastMovable = items[ i ];
9971 break;
9972 }
9973 }
9974 }
9975 this.upButton.setDisabled( !movable || selectedItem === firstMovable );
9976 this.downButton.setDisabled( !movable || selectedItem === lastMovable );
9977 this.removeButton.setDisabled( !removable );
9978 };
9979
9980 /**
9981 * ToggleWidget is mixed into other classes to create widgets with an on/off state.
9982 * Please see OO.ui.ToggleButtonWidget and OO.ui.ToggleSwitchWidget for examples.
9983 *
9984 * @abstract
9985 * @class
9986 *
9987 * @constructor
9988 * @param {Object} [config] Configuration options
9989 * @cfg {boolean} [value=false] The toggle’s initial on/off state.
9990 * By default, the toggle is in the 'off' state.
9991 */
9992 OO.ui.ToggleWidget = function OoUiToggleWidget( config ) {
9993 // Configuration initialization
9994 config = config || {};
9995
9996 // Properties
9997 this.value = null;
9998
9999 // Initialization
10000 this.$element.addClass( 'oo-ui-toggleWidget' );
10001 this.setValue( !!config.value );
10002 };
10003
10004 /* Events */
10005
10006 /**
10007 * @event change
10008 *
10009 * A change event is emitted when the on/off state of the toggle changes.
10010 *
10011 * @param {boolean} value Value representing the new state of the toggle
10012 */
10013
10014 /* Methods */
10015
10016 /**
10017 * Get the value representing the toggle’s state.
10018 *
10019 * @return {boolean} The on/off state of the toggle
10020 */
10021 OO.ui.ToggleWidget.prototype.getValue = function () {
10022 return this.value;
10023 };
10024
10025 /**
10026 * Set the state of the toggle: `true` for 'on', `false' for 'off'.
10027 *
10028 * @param {boolean} value The state of the toggle
10029 * @fires change
10030 * @chainable
10031 */
10032 OO.ui.ToggleWidget.prototype.setValue = function ( value ) {
10033 value = !!value;
10034 if ( this.value !== value ) {
10035 this.value = value;
10036 this.emit( 'change', value );
10037 this.$element.toggleClass( 'oo-ui-toggleWidget-on', value );
10038 this.$element.toggleClass( 'oo-ui-toggleWidget-off', !value );
10039 this.$element.attr( 'aria-checked', value.toString() );
10040 }
10041 return this;
10042 };
10043
10044 /**
10045 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
10046 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
10047 * removed, and cleared from the group.
10048 *
10049 * @example
10050 * // Example: A ButtonGroupWidget with two buttons
10051 * var button1 = new OO.ui.PopupButtonWidget( {
10052 * label: 'Select a category',
10053 * icon: 'menu',
10054 * popup: {
10055 * $content: $( '<p>List of categories...</p>' ),
10056 * padded: true,
10057 * align: 'left'
10058 * }
10059 * } );
10060 * var button2 = new OO.ui.ButtonWidget( {
10061 * label: 'Add item'
10062 * });
10063 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
10064 * items: [button1, button2]
10065 * } );
10066 * $( 'body' ).append( buttonGroup.$element );
10067 *
10068 * @class
10069 * @extends OO.ui.Widget
10070 * @mixins OO.ui.GroupElement
10071 *
10072 * @constructor
10073 * @param {Object} [config] Configuration options
10074 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
10075 */
10076 OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) {
10077 // Configuration initialization
10078 config = config || {};
10079
10080 // Parent constructor
10081 OO.ui.ButtonGroupWidget.super.call( this, config );
10082
10083 // Mixin constructors
10084 OO.ui.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) );
10085
10086 // Initialization
10087 this.$element.addClass( 'oo-ui-buttonGroupWidget' );
10088 if ( Array.isArray( config.items ) ) {
10089 this.addItems( config.items );
10090 }
10091 };
10092
10093 /* Setup */
10094
10095 OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget );
10096 OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.GroupElement );
10097
10098 /**
10099 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
10100 * feels, and functionality can be customized via the class’s configuration options
10101 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10102 * and examples.
10103 *
10104 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
10105 *
10106 * @example
10107 * // A button widget
10108 * var button = new OO.ui.ButtonWidget( {
10109 * label: 'Button with Icon',
10110 * icon: 'remove',
10111 * iconTitle: 'Remove'
10112 * } );
10113 * $( 'body' ).append( button.$element );
10114 *
10115 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
10116 *
10117 * @class
10118 * @extends OO.ui.Widget
10119 * @mixins OO.ui.ButtonElement
10120 * @mixins OO.ui.IconElement
10121 * @mixins OO.ui.IndicatorElement
10122 * @mixins OO.ui.LabelElement
10123 * @mixins OO.ui.TitledElement
10124 * @mixins OO.ui.FlaggedElement
10125 * @mixins OO.ui.TabIndexedElement
10126 *
10127 * @constructor
10128 * @param {Object} [config] Configuration options
10129 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
10130 * @cfg {string} [target] The frame or window in which to open the hyperlink.
10131 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
10132 */
10133 OO.ui.ButtonWidget = function OoUiButtonWidget( config ) {
10134 // Configuration initialization
10135 // FIXME: The `nofollow` alias is deprecated and will be removed (T89767)
10136 config = $.extend( { noFollow: config && config.nofollow }, config );
10137
10138 // Parent constructor
10139 OO.ui.ButtonWidget.super.call( this, config );
10140
10141 // Mixin constructors
10142 OO.ui.ButtonElement.call( this, config );
10143 OO.ui.IconElement.call( this, config );
10144 OO.ui.IndicatorElement.call( this, config );
10145 OO.ui.LabelElement.call( this, config );
10146 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) );
10147 OO.ui.FlaggedElement.call( this, config );
10148 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
10149
10150 // Properties
10151 this.href = null;
10152 this.target = null;
10153 this.noFollow = false;
10154 this.isHyperlink = false;
10155
10156 // Initialization
10157 this.$button.append( this.$icon, this.$label, this.$indicator );
10158 this.$element
10159 .addClass( 'oo-ui-buttonWidget' )
10160 .append( this.$button );
10161 this.setHref( config.href );
10162 this.setTarget( config.target );
10163 this.setNoFollow( config.noFollow );
10164 };
10165
10166 /* Setup */
10167
10168 OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget );
10169 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.ButtonElement );
10170 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IconElement );
10171 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.IndicatorElement );
10172 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.LabelElement );
10173 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TitledElement );
10174 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.FlaggedElement );
10175 OO.mixinClass( OO.ui.ButtonWidget, OO.ui.TabIndexedElement );
10176
10177 /* Methods */
10178
10179 /**
10180 * @inheritdoc
10181 */
10182 OO.ui.ButtonWidget.prototype.onMouseDown = function ( e ) {
10183 if ( !this.isDisabled() ) {
10184 // Remove the tab-index while the button is down to prevent the button from stealing focus
10185 this.$button.removeAttr( 'tabindex' );
10186 }
10187
10188 return OO.ui.ButtonElement.prototype.onMouseDown.call( this, e );
10189 };
10190
10191 /**
10192 * @inheritdoc
10193 */
10194 OO.ui.ButtonWidget.prototype.onMouseUp = function ( e ) {
10195 if ( !this.isDisabled() ) {
10196 // Restore the tab-index after the button is up to restore the button's accessibility
10197 this.$button.attr( 'tabindex', this.tabIndex );
10198 }
10199
10200 return OO.ui.ButtonElement.prototype.onMouseUp.call( this, e );
10201 };
10202
10203 /**
10204 * @inheritdoc
10205 */
10206 OO.ui.ButtonWidget.prototype.onClick = function ( e ) {
10207 var ret = OO.ui.ButtonElement.prototype.onClick.call( this, e );
10208 if ( this.isHyperlink ) {
10209 return true;
10210 }
10211 return ret;
10212 };
10213
10214 /**
10215 * @inheritdoc
10216 */
10217 OO.ui.ButtonWidget.prototype.onKeyPress = function ( e ) {
10218 var ret = OO.ui.ButtonElement.prototype.onKeyPress.call( this, e );
10219 if ( this.isHyperlink ) {
10220 return true;
10221 }
10222 return ret;
10223 };
10224
10225 /**
10226 * Get hyperlink location.
10227 *
10228 * @return {string} Hyperlink location
10229 */
10230 OO.ui.ButtonWidget.prototype.getHref = function () {
10231 return this.href;
10232 };
10233
10234 /**
10235 * Get hyperlink target.
10236 *
10237 * @return {string} Hyperlink target
10238 */
10239 OO.ui.ButtonWidget.prototype.getTarget = function () {
10240 return this.target;
10241 };
10242
10243 /**
10244 * Get search engine traversal hint.
10245 *
10246 * @return {boolean} Whether search engines should avoid traversing this hyperlink
10247 */
10248 OO.ui.ButtonWidget.prototype.getNoFollow = function () {
10249 return this.noFollow;
10250 };
10251
10252 /**
10253 * Set hyperlink location.
10254 *
10255 * @param {string|null} href Hyperlink location, null to remove
10256 */
10257 OO.ui.ButtonWidget.prototype.setHref = function ( href ) {
10258 href = typeof href === 'string' ? href : null;
10259
10260 if ( href !== this.href ) {
10261 this.href = href;
10262 if ( href !== null ) {
10263 this.$button.attr( 'href', href );
10264 this.isHyperlink = true;
10265 } else {
10266 this.$button.removeAttr( 'href' );
10267 this.isHyperlink = false;
10268 }
10269 }
10270
10271 return this;
10272 };
10273
10274 /**
10275 * Set hyperlink target.
10276 *
10277 * @param {string|null} target Hyperlink target, null to remove
10278 */
10279 OO.ui.ButtonWidget.prototype.setTarget = function ( target ) {
10280 target = typeof target === 'string' ? target : null;
10281
10282 if ( target !== this.target ) {
10283 this.target = target;
10284 if ( target !== null ) {
10285 this.$button.attr( 'target', target );
10286 } else {
10287 this.$button.removeAttr( 'target' );
10288 }
10289 }
10290
10291 return this;
10292 };
10293
10294 /**
10295 * Set search engine traversal hint.
10296 *
10297 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
10298 */
10299 OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) {
10300 noFollow = typeof noFollow === 'boolean' ? noFollow : true;
10301
10302 if ( noFollow !== this.noFollow ) {
10303 this.noFollow = noFollow;
10304 if ( noFollow ) {
10305 this.$button.attr( 'rel', 'nofollow' );
10306 } else {
10307 this.$button.removeAttr( 'rel' );
10308 }
10309 }
10310
10311 return this;
10312 };
10313
10314 /**
10315 * An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
10316 * Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
10317 * of the actions.
10318 *
10319 * Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
10320 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information
10321 * and examples.
10322 *
10323 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
10324 *
10325 * @class
10326 * @extends OO.ui.ButtonWidget
10327 * @mixins OO.ui.PendingElement
10328 *
10329 * @constructor
10330 * @param {Object} [config] Configuration options
10331 * @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10332 * @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
10333 * should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
10334 * for more information about setting modes.
10335 * @cfg {boolean} [framed=false] Render the action button with a frame
10336 */
10337 OO.ui.ActionWidget = function OoUiActionWidget( config ) {
10338 // Configuration initialization
10339 config = $.extend( { framed: false }, config );
10340
10341 // Parent constructor
10342 OO.ui.ActionWidget.super.call( this, config );
10343
10344 // Mixin constructors
10345 OO.ui.PendingElement.call( this, config );
10346
10347 // Properties
10348 this.action = config.action || '';
10349 this.modes = config.modes || [];
10350 this.width = 0;
10351 this.height = 0;
10352
10353 // Initialization
10354 this.$element.addClass( 'oo-ui-actionWidget' );
10355 };
10356
10357 /* Setup */
10358
10359 OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
10360 OO.mixinClass( OO.ui.ActionWidget, OO.ui.PendingElement );
10361
10362 /* Events */
10363
10364 /**
10365 * A resize event is emitted when the size of the widget changes.
10366 *
10367 * @event resize
10368 */
10369
10370 /* Methods */
10371
10372 /**
10373 * Check if the action is configured to be available in the specified `mode`.
10374 *
10375 * @param {string} mode Name of mode
10376 * @return {boolean} The action is configured with the mode
10377 */
10378 OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
10379 return this.modes.indexOf( mode ) !== -1;
10380 };
10381
10382 /**
10383 * Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
10384 *
10385 * @return {string}
10386 */
10387 OO.ui.ActionWidget.prototype.getAction = function () {
10388 return this.action;
10389 };
10390
10391 /**
10392 * Get the symbolic name of the mode or modes for which the action is configured to be available.
10393 *
10394 * The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
10395 * Only actions that are configured to be avaiable in the current mode will be visible. All other actions
10396 * are hidden.
10397 *
10398 * @return {string[]}
10399 */
10400 OO.ui.ActionWidget.prototype.getModes = function () {
10401 return this.modes.slice();
10402 };
10403
10404 /**
10405 * Emit a resize event if the size has changed.
10406 *
10407 * @private
10408 * @chainable
10409 */
10410 OO.ui.ActionWidget.prototype.propagateResize = function () {
10411 var width, height;
10412
10413 if ( this.isElementAttached() ) {
10414 width = this.$element.width();
10415 height = this.$element.height();
10416
10417 if ( width !== this.width || height !== this.height ) {
10418 this.width = width;
10419 this.height = height;
10420 this.emit( 'resize' );
10421 }
10422 }
10423
10424 return this;
10425 };
10426
10427 /**
10428 * @inheritdoc
10429 */
10430 OO.ui.ActionWidget.prototype.setIcon = function () {
10431 // Mixin method
10432 OO.ui.IconElement.prototype.setIcon.apply( this, arguments );
10433 this.propagateResize();
10434
10435 return this;
10436 };
10437
10438 /**
10439 * @inheritdoc
10440 */
10441 OO.ui.ActionWidget.prototype.setLabel = function () {
10442 // Mixin method
10443 OO.ui.LabelElement.prototype.setLabel.apply( this, arguments );
10444 this.propagateResize();
10445
10446 return this;
10447 };
10448
10449 /**
10450 * @inheritdoc
10451 */
10452 OO.ui.ActionWidget.prototype.setFlags = function () {
10453 // Mixin method
10454 OO.ui.FlaggedElement.prototype.setFlags.apply( this, arguments );
10455 this.propagateResize();
10456
10457 return this;
10458 };
10459
10460 /**
10461 * @inheritdoc
10462 */
10463 OO.ui.ActionWidget.prototype.clearFlags = function () {
10464 // Mixin method
10465 OO.ui.FlaggedElement.prototype.clearFlags.apply( this, arguments );
10466 this.propagateResize();
10467
10468 return this;
10469 };
10470
10471 /**
10472 * Toggle the visibility of the action button.
10473 *
10474 * @param {boolean} [show] Show button, omit to toggle visibility
10475 * @chainable
10476 */
10477 OO.ui.ActionWidget.prototype.toggle = function () {
10478 // Parent method
10479 OO.ui.ActionWidget.super.prototype.toggle.apply( this, arguments );
10480 this.propagateResize();
10481
10482 return this;
10483 };
10484
10485 /**
10486 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
10487 * which is used to display additional information or options.
10488 *
10489 * @example
10490 * // Example of a popup button.
10491 * var popupButton = new OO.ui.PopupButtonWidget( {
10492 * label: 'Popup button with options',
10493 * icon: 'menu',
10494 * popup: {
10495 * $content: $( '<p>Additional options here.</p>' ),
10496 * padded: true,
10497 * align: 'left'
10498 * }
10499 * } );
10500 * // Append the button to the DOM.
10501 * $( 'body' ).append( popupButton.$element );
10502 *
10503 * @class
10504 * @extends OO.ui.ButtonWidget
10505 * @mixins OO.ui.PopupElement
10506 *
10507 * @constructor
10508 * @param {Object} [config] Configuration options
10509 */
10510 OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) {
10511 // Parent constructor
10512 OO.ui.PopupButtonWidget.super.call( this, config );
10513
10514 // Mixin constructors
10515 OO.ui.PopupElement.call( this, config );
10516
10517 // Events
10518 this.connect( this, { click: 'onAction' } );
10519
10520 // Initialization
10521 this.$element
10522 .addClass( 'oo-ui-popupButtonWidget' )
10523 .attr( 'aria-haspopup', 'true' )
10524 .append( this.popup.$element );
10525 };
10526
10527 /* Setup */
10528
10529 OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget );
10530 OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.PopupElement );
10531
10532 /* Methods */
10533
10534 /**
10535 * Handle the button action being triggered.
10536 *
10537 * @private
10538 */
10539 OO.ui.PopupButtonWidget.prototype.onAction = function () {
10540 this.popup.toggle();
10541 };
10542
10543 /**
10544 * ToggleButtons are buttons that have a state (‘on’ or ‘off’) that is represented by a
10545 * Boolean value. Like other {@link OO.ui.ButtonWidget buttons}, toggle buttons can be
10546 * configured with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators},
10547 * {@link OO.ui.TitledElement titles}, {@link OO.ui.FlaggedElement styling flags},
10548 * and {@link OO.ui.LabelElement labels}. Please see
10549 * the [OOjs UI documentation][1] on MediaWiki for more information.
10550 *
10551 * @example
10552 * // Toggle buttons in the 'off' and 'on' state.
10553 * var toggleButton1 = new OO.ui.ToggleButtonWidget( {
10554 * label: 'Toggle Button off'
10555 * } );
10556 * var toggleButton2 = new OO.ui.ToggleButtonWidget( {
10557 * label: 'Toggle Button on',
10558 * value: true
10559 * } );
10560 * // Append the buttons to the DOM.
10561 * $( 'body' ).append( toggleButton1.$element, toggleButton2.$element );
10562 *
10563 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Toggle_buttons
10564 *
10565 * @class
10566 * @extends OO.ui.ButtonWidget
10567 * @mixins OO.ui.ToggleWidget
10568 *
10569 * @constructor
10570 * @param {Object} [config] Configuration options
10571 * @cfg {boolean} [value=false] The toggle button’s initial on/off
10572 * state. By default, the button is in the 'off' state.
10573 */
10574 OO.ui.ToggleButtonWidget = function OoUiToggleButtonWidget( config ) {
10575 // Configuration initialization
10576 config = config || {};
10577
10578 // Parent constructor
10579 OO.ui.ToggleButtonWidget.super.call( this, config );
10580
10581 // Mixin constructors
10582 OO.ui.ToggleWidget.call( this, config );
10583
10584 // Events
10585 this.connect( this, { click: 'onAction' } );
10586
10587 // Initialization
10588 this.$element.addClass( 'oo-ui-toggleButtonWidget' );
10589 };
10590
10591 /* Setup */
10592
10593 OO.inheritClass( OO.ui.ToggleButtonWidget, OO.ui.ButtonWidget );
10594 OO.mixinClass( OO.ui.ToggleButtonWidget, OO.ui.ToggleWidget );
10595
10596 /* Methods */
10597
10598 /**
10599 *
10600 * @private
10601 * Handle the button action being triggered.
10602 */
10603 OO.ui.ToggleButtonWidget.prototype.onAction = function () {
10604 this.setValue( !this.value );
10605 };
10606
10607 /**
10608 * @inheritdoc
10609 */
10610 OO.ui.ToggleButtonWidget.prototype.setValue = function ( value ) {
10611 value = !!value;
10612 if ( value !== this.value ) {
10613 this.$button.attr( 'aria-pressed', value.toString() );
10614 this.setActive( value );
10615 }
10616
10617 // Parent method (from mixin)
10618 OO.ui.ToggleWidget.prototype.setValue.call( this, value );
10619
10620 return this;
10621 };
10622
10623 /**
10624 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
10625 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
10626 * users can interact with it.
10627 *
10628 * @example
10629 * // Example: A DropdownWidget with a menu that contains three options
10630 * var dropDown = new OO.ui.DropdownWidget( {
10631 * label: 'Dropdown menu: Select a menu option',
10632 * menu: {
10633 * items: [
10634 * new OO.ui.MenuOptionWidget( {
10635 * data: 'a',
10636 * label: 'First'
10637 * } ),
10638 * new OO.ui.MenuOptionWidget( {
10639 * data: 'b',
10640 * label: 'Second'
10641 * } ),
10642 * new OO.ui.MenuOptionWidget( {
10643 * data: 'c',
10644 * label: 'Third'
10645 * } )
10646 * ]
10647 * }
10648 * } );
10649 *
10650 * $( 'body' ).append( dropDown.$element );
10651 *
10652 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
10653 *
10654 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10655 *
10656 * @class
10657 * @extends OO.ui.Widget
10658 * @mixins OO.ui.IconElement
10659 * @mixins OO.ui.IndicatorElement
10660 * @mixins OO.ui.LabelElement
10661 * @mixins OO.ui.TitledElement
10662 * @mixins OO.ui.TabIndexedElement
10663 *
10664 * @constructor
10665 * @param {Object} [config] Configuration options
10666 * @cfg {Object} [menu] Configuration options to pass to menu widget
10667 */
10668 OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) {
10669 // Configuration initialization
10670 config = $.extend( { indicator: 'down' }, config );
10671
10672 // Parent constructor
10673 OO.ui.DropdownWidget.super.call( this, config );
10674
10675 // Properties (must be set before TabIndexedElement constructor call)
10676 this.$handle = this.$( '<span>' );
10677
10678 // Mixin constructors
10679 OO.ui.IconElement.call( this, config );
10680 OO.ui.IndicatorElement.call( this, config );
10681 OO.ui.LabelElement.call( this, config );
10682 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) );
10683 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) );
10684
10685 // Properties
10686 this.menu = new OO.ui.MenuSelectWidget( $.extend( { widget: this }, config.menu ) );
10687
10688 // Events
10689 this.$handle.on( {
10690 click: this.onClick.bind( this ),
10691 keypress: this.onKeyPress.bind( this )
10692 } );
10693 this.menu.connect( this, { select: 'onMenuSelect' } );
10694
10695 // Initialization
10696 this.$handle
10697 .addClass( 'oo-ui-dropdownWidget-handle' )
10698 .append( this.$icon, this.$label, this.$indicator );
10699 this.$element
10700 .addClass( 'oo-ui-dropdownWidget' )
10701 .append( this.$handle, this.menu.$element );
10702 };
10703
10704 /* Setup */
10705
10706 OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget );
10707 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IconElement );
10708 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.IndicatorElement );
10709 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.LabelElement );
10710 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TitledElement );
10711 OO.mixinClass( OO.ui.DropdownWidget, OO.ui.TabIndexedElement );
10712
10713 /* Methods */
10714
10715 /**
10716 * Get the menu.
10717 *
10718 * @return {OO.ui.MenuSelectWidget} Menu of widget
10719 */
10720 OO.ui.DropdownWidget.prototype.getMenu = function () {
10721 return this.menu;
10722 };
10723
10724 /**
10725 * Handles menu select events.
10726 *
10727 * @private
10728 * @param {OO.ui.MenuOptionWidget} item Selected menu item
10729 */
10730 OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) {
10731 var selectedLabel;
10732
10733 if ( !item ) {
10734 return;
10735 }
10736
10737 selectedLabel = item.getLabel();
10738
10739 // If the label is a DOM element, clone it, because setLabel will append() it
10740 if ( selectedLabel instanceof jQuery ) {
10741 selectedLabel = selectedLabel.clone();
10742 }
10743
10744 this.setLabel( selectedLabel );
10745 };
10746
10747 /**
10748 * Handle mouse click events.
10749 *
10750 * @private
10751 * @param {jQuery.Event} e Mouse click event
10752 */
10753 OO.ui.DropdownWidget.prototype.onClick = function ( e ) {
10754 if ( !this.isDisabled() && e.which === 1 ) {
10755 this.menu.toggle();
10756 }
10757 return false;
10758 };
10759
10760 /**
10761 * Handle key press events.
10762 *
10763 * @private
10764 * @param {jQuery.Event} e Key press event
10765 */
10766 OO.ui.DropdownWidget.prototype.onKeyPress = function ( e ) {
10767 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
10768 this.menu.toggle();
10769 return false;
10770 }
10771 };
10772
10773 /**
10774 * IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
10775 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
10776 * for a list of icons included in the library.
10777 *
10778 * @example
10779 * // An icon widget with a label
10780 * var myIcon = new OO.ui.IconWidget( {
10781 * icon: 'help',
10782 * iconTitle: 'Help'
10783 * } );
10784 * // Create a label.
10785 * var iconLabel = new OO.ui.LabelWidget( {
10786 * label: 'Help'
10787 * } );
10788 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
10789 *
10790 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
10791 *
10792 * @class
10793 * @extends OO.ui.Widget
10794 * @mixins OO.ui.IconElement
10795 * @mixins OO.ui.TitledElement
10796 *
10797 * @constructor
10798 * @param {Object} [config] Configuration options
10799 */
10800 OO.ui.IconWidget = function OoUiIconWidget( config ) {
10801 // Configuration initialization
10802 config = config || {};
10803
10804 // Parent constructor
10805 OO.ui.IconWidget.super.call( this, config );
10806
10807 // Mixin constructors
10808 OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
10809 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10810
10811 // Initialization
10812 this.$element.addClass( 'oo-ui-iconWidget' );
10813 };
10814
10815 /* Setup */
10816
10817 OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
10818 OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
10819 OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
10820
10821 /* Static Properties */
10822
10823 OO.ui.IconWidget.static.tagName = 'span';
10824
10825 /**
10826 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
10827 * attention to the status of an item or to clarify the function of a control. For a list of
10828 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
10829 *
10830 * @example
10831 * // Example of an indicator widget
10832 * var indicator1 = new OO.ui.IndicatorWidget( {
10833 * indicator: 'alert'
10834 * } );
10835 *
10836 * // Create a fieldset layout to add a label
10837 * var fieldset = new OO.ui.FieldsetLayout();
10838 * fieldset.addItems( [
10839 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
10840 * ] );
10841 * $( 'body' ).append( fieldset.$element );
10842 *
10843 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
10844 *
10845 * @class
10846 * @extends OO.ui.Widget
10847 * @mixins OO.ui.IndicatorElement
10848 * @mixins OO.ui.TitledElement
10849 *
10850 * @constructor
10851 * @param {Object} [config] Configuration options
10852 */
10853 OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) {
10854 // Configuration initialization
10855 config = config || {};
10856
10857 // Parent constructor
10858 OO.ui.IndicatorWidget.super.call( this, config );
10859
10860 // Mixin constructors
10861 OO.ui.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) );
10862 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
10863
10864 // Initialization
10865 this.$element.addClass( 'oo-ui-indicatorWidget' );
10866 };
10867
10868 /* Setup */
10869
10870 OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget );
10871 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.IndicatorElement );
10872 OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.TitledElement );
10873
10874 /* Static Properties */
10875
10876 OO.ui.IndicatorWidget.static.tagName = 'span';
10877
10878 /**
10879 * InputWidget is the base class for all input widgets, which
10880 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
10881 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
10882 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
10883 *
10884 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
10885 *
10886 * @abstract
10887 * @class
10888 * @extends OO.ui.Widget
10889 * @mixins OO.ui.FlaggedElement
10890 * @mixins OO.ui.TabIndexedElement
10891 *
10892 * @constructor
10893 * @param {Object} [config] Configuration options
10894 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
10895 * @cfg {string} [value=''] The value of the input.
10896 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
10897 * before it is accepted.
10898 */
10899 OO.ui.InputWidget = function OoUiInputWidget( config ) {
10900 // Configuration initialization
10901 config = config || {};
10902
10903 // Parent constructor
10904 OO.ui.InputWidget.super.call( this, config );
10905
10906 // Properties
10907 this.$input = this.getInputElement( config );
10908 this.value = '';
10909 this.inputFilter = config.inputFilter;
10910
10911 // Mixin constructors
10912 OO.ui.FlaggedElement.call( this, config );
10913 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) );
10914
10915 // Events
10916 this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) );
10917
10918 // Initialization
10919 this.$input
10920 .attr( 'name', config.name )
10921 .prop( 'disabled', this.isDisabled() );
10922 this.$element.addClass( 'oo-ui-inputWidget' ).append( this.$input, $( '<span>' ) );
10923 this.setValue( config.value );
10924 };
10925
10926 /* Setup */
10927
10928 OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget );
10929 OO.mixinClass( OO.ui.InputWidget, OO.ui.FlaggedElement );
10930 OO.mixinClass( OO.ui.InputWidget, OO.ui.TabIndexedElement );
10931
10932 /* Events */
10933
10934 /**
10935 * @event change
10936 *
10937 * A change event is emitted when the value of the input changes.
10938 *
10939 * @param {string} value
10940 */
10941
10942 /* Methods */
10943
10944 /**
10945 * Get input element.
10946 *
10947 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
10948 * different circumstances. The element must have a `value` property (like form elements).
10949 *
10950 * @private
10951 * @param {Object} config Configuration options
10952 * @return {jQuery} Input element
10953 */
10954 OO.ui.InputWidget.prototype.getInputElement = function () {
10955 return $( '<input>' );
10956 };
10957
10958 /**
10959 * Handle potentially value-changing events.
10960 *
10961 * @private
10962 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
10963 */
10964 OO.ui.InputWidget.prototype.onEdit = function () {
10965 var widget = this;
10966 if ( !this.isDisabled() ) {
10967 // Allow the stack to clear so the value will be updated
10968 setTimeout( function () {
10969 widget.setValue( widget.$input.val() );
10970 } );
10971 }
10972 };
10973
10974 /**
10975 * Get the value of the input.
10976 *
10977 * @return {string} Input value
10978 */
10979 OO.ui.InputWidget.prototype.getValue = function () {
10980 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
10981 // it, and we won't know unless they're kind enough to trigger a 'change' event.
10982 var value = this.$input.val();
10983 if ( this.value !== value ) {
10984 this.setValue( value );
10985 }
10986 return this.value;
10987 };
10988
10989 /**
10990 * Set the direction of the input, either RTL (right-to-left) or LTR (left-to-right).
10991 *
10992 * @param {boolean} isRTL
10993 * Direction is right-to-left
10994 */
10995 OO.ui.InputWidget.prototype.setRTL = function ( isRTL ) {
10996 this.$input.prop( 'dir', isRTL ? 'rtl' : 'ltr' );
10997 };
10998
10999 /**
11000 * Set the value of the input.
11001 *
11002 * @param {string} value New value
11003 * @fires change
11004 * @chainable
11005 */
11006 OO.ui.InputWidget.prototype.setValue = function ( value ) {
11007 value = this.cleanUpValue( value );
11008 // Update the DOM if it has changed. Note that with cleanUpValue, it
11009 // is possible for the DOM value to change without this.value changing.
11010 if ( this.$input.val() !== value ) {
11011 this.$input.val( value );
11012 }
11013 if ( this.value !== value ) {
11014 this.value = value;
11015 this.emit( 'change', this.value );
11016 }
11017 return this;
11018 };
11019
11020 /**
11021 * Clean up incoming value.
11022 *
11023 * Ensures value is a string, and converts undefined and null to empty string.
11024 *
11025 * @private
11026 * @param {string} value Original value
11027 * @return {string} Cleaned up value
11028 */
11029 OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) {
11030 if ( value === undefined || value === null ) {
11031 return '';
11032 } else if ( this.inputFilter ) {
11033 return this.inputFilter( String( value ) );
11034 } else {
11035 return String( value );
11036 }
11037 };
11038
11039 /**
11040 * Simulate the behavior of clicking on a label bound to this input. This method is only called by
11041 * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be
11042 * called directly.
11043 */
11044 OO.ui.InputWidget.prototype.simulateLabelClick = function () {
11045 if ( !this.isDisabled() ) {
11046 if ( this.$input.is( ':checkbox, :radio' ) ) {
11047 this.$input.click();
11048 }
11049 if ( this.$input.is( ':input' ) ) {
11050 this.$input[ 0 ].focus();
11051 }
11052 }
11053 };
11054
11055 /**
11056 * @inheritdoc
11057 */
11058 OO.ui.InputWidget.prototype.setDisabled = function ( state ) {
11059 OO.ui.InputWidget.super.prototype.setDisabled.call( this, state );
11060 if ( this.$input ) {
11061 this.$input.prop( 'disabled', this.isDisabled() );
11062 }
11063 return this;
11064 };
11065
11066 /**
11067 * Focus the input.
11068 *
11069 * @chainable
11070 */
11071 OO.ui.InputWidget.prototype.focus = function () {
11072 this.$input[ 0 ].focus();
11073 return this;
11074 };
11075
11076 /**
11077 * Blur the input.
11078 *
11079 * @chainable
11080 */
11081 OO.ui.InputWidget.prototype.blur = function () {
11082 this.$input[ 0 ].blur();
11083 return this;
11084 };
11085
11086 /**
11087 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
11088 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
11089 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
11090 * HTML `<button/>` (the default) or an HTML `<input/>` tags. See the
11091 * [OOjs UI documentation on MediaWiki] [1] for more information.
11092 *
11093 * @example
11094 * // A ButtonInputWidget rendered as an HTML button, the default.
11095 * var button = new OO.ui.ButtonInputWidget( {
11096 * label: 'Input button',
11097 * icon: 'check',
11098 * value: 'check'
11099 * } );
11100 * $( 'body' ).append( button.$element );
11101 *
11102 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
11103 *
11104 * @class
11105 * @extends OO.ui.InputWidget
11106 * @mixins OO.ui.ButtonElement
11107 * @mixins OO.ui.IconElement
11108 * @mixins OO.ui.IndicatorElement
11109 * @mixins OO.ui.LabelElement
11110 * @mixins OO.ui.TitledElement
11111 * @mixins OO.ui.FlaggedElement
11112 *
11113 * @constructor
11114 * @param {Object} [config] Configuration options
11115 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
11116 * @cfg {boolean} [useInputTag=false] Use an `<input/>` tag instead of a `<button/>` tag, the default.
11117 * Widgets configured to be an `<input/>` do not support {@link #icon icons} and {@link #indicator indicators},
11118 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
11119 * be set to `true` when there’s need to support IE6 in a form with multiple buttons.
11120 */
11121 OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) {
11122 // Configuration initialization
11123 config = $.extend( { type: 'button', useInputTag: false }, config );
11124
11125 // Properties (must be set before parent constructor, which calls #setValue)
11126 this.useInputTag = config.useInputTag;
11127
11128 // Parent constructor
11129 OO.ui.ButtonInputWidget.super.call( this, config );
11130
11131 // Mixin constructors
11132 OO.ui.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) );
11133 OO.ui.IconElement.call( this, config );
11134 OO.ui.IndicatorElement.call( this, config );
11135 OO.ui.LabelElement.call( this, config );
11136 OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) );
11137 OO.ui.FlaggedElement.call( this, config );
11138
11139 // Initialization
11140 if ( !config.useInputTag ) {
11141 this.$input.append( this.$icon, this.$label, this.$indicator );
11142 }
11143 this.$element.addClass( 'oo-ui-buttonInputWidget' );
11144 };
11145
11146 /* Setup */
11147
11148 OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget );
11149 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.ButtonElement );
11150 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IconElement );
11151 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.IndicatorElement );
11152 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.LabelElement );
11153 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.TitledElement );
11154 OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.FlaggedElement );
11155
11156 /* Methods */
11157
11158 /**
11159 * @inheritdoc
11160 * @private
11161 */
11162 OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) {
11163 var html = '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + config.type + '">';
11164 return $( html );
11165 };
11166
11167 /**
11168 * Set label value.
11169 *
11170 * If #useInputTag is `true`, the label is set as the `value` of the `<input/>` tag.
11171 *
11172 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
11173 * text, or `null` for no label
11174 * @chainable
11175 */
11176 OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) {
11177 OO.ui.LabelElement.prototype.setLabel.call( this, label );
11178
11179 if ( this.useInputTag ) {
11180 if ( typeof label === 'function' ) {
11181 label = OO.ui.resolveMsg( label );
11182 }
11183 if ( label instanceof jQuery ) {
11184 label = label.text();
11185 }
11186 if ( !label ) {
11187 label = '';
11188 }
11189 this.$input.val( label );
11190 }
11191
11192 return this;
11193 };
11194
11195 /**
11196 * Set the value of the input.
11197 *
11198 * This method is disabled for button inputs configured as {@link #useInputTag <input/> tags}, as
11199 * they do not support {@link #value values}.
11200 *
11201 * @param {string} value New value
11202 * @chainable
11203 */
11204 OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) {
11205 if ( !this.useInputTag ) {
11206 OO.ui.ButtonInputWidget.super.prototype.setValue.call( this, value );
11207 }
11208 return this;
11209 };
11210
11211 /**
11212 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
11213 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
11214 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
11215 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
11216 *
11217 * @example
11218 * // An example of selected, unselected, and disabled checkbox inputs
11219 * var checkbox1=new OO.ui.CheckboxInputWidget( {
11220 * value: 'a',
11221 * selected: true
11222 * } );
11223 * var checkbox2=new OO.ui.CheckboxInputWidget( {
11224 * value: 'b'
11225 * } );
11226 * var checkbox3=new OO.ui.CheckboxInputWidget( {
11227 * value:'c',
11228 * disabled: true
11229 * } );
11230 * // Create a fieldset layout with fields for each checkbox.
11231 * var fieldset = new OO.ui.FieldsetLayout( {
11232 * label: 'Checkboxes'
11233 * } );
11234 * fieldset.addItems( [
11235 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
11236 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
11237 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
11238 * ] );
11239 * $( 'body' ).append( fieldset.$element );
11240 *
11241 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11242 *
11243 * @class
11244 * @extends OO.ui.InputWidget
11245 *
11246 * @constructor
11247 * @param {Object} [config] Configuration options
11248 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
11249 */
11250 OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) {
11251 // Configuration initialization
11252 config = config || {};
11253
11254 // Parent constructor
11255 OO.ui.CheckboxInputWidget.super.call( this, config );
11256
11257 // Initialization
11258 this.$element.addClass( 'oo-ui-checkboxInputWidget' );
11259 this.setSelected( config.selected !== undefined ? config.selected : false );
11260 };
11261
11262 /* Setup */
11263
11264 OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget );
11265
11266 /* Methods */
11267
11268 /**
11269 * @inheritdoc
11270 * @private
11271 */
11272 OO.ui.CheckboxInputWidget.prototype.getInputElement = function () {
11273 return $( '<input type="checkbox" />' );
11274 };
11275
11276 /**
11277 * @inheritdoc
11278 */
11279 OO.ui.CheckboxInputWidget.prototype.onEdit = function () {
11280 var widget = this;
11281 if ( !this.isDisabled() ) {
11282 // Allow the stack to clear so the value will be updated
11283 setTimeout( function () {
11284 widget.setSelected( widget.$input.prop( 'checked' ) );
11285 } );
11286 }
11287 };
11288
11289 /**
11290 * Set selection state of this checkbox.
11291 *
11292 * @param {boolean} state `true` for selected
11293 * @chainable
11294 */
11295 OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) {
11296 state = !!state;
11297 if ( this.selected !== state ) {
11298 this.selected = state;
11299 this.$input.prop( 'checked', this.selected );
11300 this.emit( 'change', this.selected );
11301 }
11302 return this;
11303 };
11304
11305 /**
11306 * Check if this checkbox is selected.
11307 *
11308 * @return {boolean} Checkbox is selected
11309 */
11310 OO.ui.CheckboxInputWidget.prototype.isSelected = function () {
11311 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
11312 // it, and we won't know unless they're kind enough to trigger a 'change' event.
11313 var selected = this.$input.prop( 'checked' );
11314 if ( this.selected !== selected ) {
11315 this.setSelected( selected );
11316 }
11317 return this.selected;
11318 };
11319
11320 /**
11321 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
11322 * within a {@link OO.ui.FormLayout form}. The selected value is synchronized with the value
11323 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
11324 * more information about input widgets.
11325 *
11326 * @example
11327 * // Example: A DropdownInputWidget with three options
11328 * var dropDown = new OO.ui.DropdownInputWidget( {
11329 * label: 'Dropdown menu: Select a menu option',
11330 * options: [
11331 * { data: 'a', label: 'First' } ,
11332 * { data: 'b', label: 'Second'} ,
11333 * { data: 'c', label: 'Third' }
11334 * ]
11335 * } );
11336 * $( 'body' ).append( dropDown.$element );
11337 *
11338 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11339 *
11340 * @class
11341 * @extends OO.ui.InputWidget
11342 *
11343 * @constructor
11344 * @param {Object} [config] Configuration options
11345 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
11346 */
11347 OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) {
11348 // Configuration initialization
11349 config = config || {};
11350
11351 // Properties (must be done before parent constructor which calls #setDisabled)
11352 this.dropdownWidget = new OO.ui.DropdownWidget();
11353
11354 // Parent constructor
11355 OO.ui.DropdownInputWidget.super.call( this, config );
11356
11357 // Events
11358 this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } );
11359
11360 // Initialization
11361 this.setOptions( config.options || [] );
11362 this.$element
11363 .addClass( 'oo-ui-dropdownInputWidget' )
11364 .append( this.dropdownWidget.$element );
11365 };
11366
11367 /* Setup */
11368
11369 OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget );
11370
11371 /* Methods */
11372
11373 /**
11374 * @inheritdoc
11375 * @private
11376 */
11377 OO.ui.DropdownInputWidget.prototype.getInputElement = function () {
11378 return $( '<input type="hidden">' );
11379 };
11380
11381 /**
11382 * Handles menu select events.
11383 *
11384 * @private
11385 * @param {OO.ui.MenuOptionWidget} item Selected menu item
11386 */
11387 OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) {
11388 this.setValue( item.getData() );
11389 };
11390
11391 /**
11392 * @inheritdoc
11393 */
11394 OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) {
11395 var item = this.dropdownWidget.getMenu().getItemFromData( value );
11396 if ( item ) {
11397 this.dropdownWidget.getMenu().selectItem( item );
11398 }
11399 OO.ui.DropdownInputWidget.super.prototype.setValue.call( this, value );
11400 return this;
11401 };
11402
11403 /**
11404 * @inheritdoc
11405 */
11406 OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) {
11407 this.dropdownWidget.setDisabled( state );
11408 OO.ui.DropdownInputWidget.super.prototype.setDisabled.call( this, state );
11409 return this;
11410 };
11411
11412 /**
11413 * Set the options available for this input.
11414 *
11415 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
11416 * @chainable
11417 */
11418 OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) {
11419 var value = this.getValue();
11420
11421 // Rebuild the dropdown menu
11422 this.dropdownWidget.getMenu()
11423 .clearItems()
11424 .addItems( options.map( function ( opt ) {
11425 return new OO.ui.MenuOptionWidget( {
11426 data: opt.data,
11427 label: opt.label !== undefined ? opt.label : opt.data
11428 } );
11429 } ) );
11430
11431 // Restore the previous value, or reset to something sensible
11432 if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) {
11433 // Previous value is still available, ensure consistency with the dropdown
11434 this.setValue( value );
11435 } else {
11436 // No longer valid, reset
11437 if ( options.length ) {
11438 this.setValue( options[ 0 ].data );
11439 }
11440 }
11441
11442 return this;
11443 };
11444
11445 /**
11446 * @inheritdoc
11447 */
11448 OO.ui.DropdownInputWidget.prototype.focus = function () {
11449 this.dropdownWidget.getMenu().toggle( true );
11450 return this;
11451 };
11452
11453 /**
11454 * @inheritdoc
11455 */
11456 OO.ui.DropdownInputWidget.prototype.blur = function () {
11457 this.dropdownWidget.getMenu().toggle( false );
11458 return this;
11459 };
11460
11461 /**
11462 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
11463 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
11464 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
11465 * please see the [OOjs UI documentation on MediaWiki][1].
11466 *
11467 * @example
11468 * // An example of selected, unselected, and disabled radio inputs
11469 * var radio1 = new OO.ui.RadioInputWidget( {
11470 * value: 'a',
11471 * selected: true
11472 * } );
11473 * var radio2 = new OO.ui.RadioInputWidget( {
11474 * value: 'b'
11475 * } );
11476 * var radio3 = new OO.ui.RadioInputWidget( {
11477 * value: 'c',
11478 * disabled: true
11479 * } );
11480 * // Create a fieldset layout with fields for each radio button.
11481 * var fieldset = new OO.ui.FieldsetLayout( {
11482 * label: 'Radio inputs'
11483 * } );
11484 * fieldset.addItems( [
11485 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
11486 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
11487 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
11488 * ] );
11489 * $( 'body' ).append( fieldset.$element );
11490 *
11491 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11492 *
11493 * @class
11494 * @extends OO.ui.InputWidget
11495 *
11496 * @constructor
11497 * @param {Object} [config] Configuration options
11498 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
11499 */
11500 OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) {
11501 // Configuration initialization
11502 config = config || {};
11503
11504 // Parent constructor
11505 OO.ui.RadioInputWidget.super.call( this, config );
11506
11507 // Initialization
11508 this.$element.addClass( 'oo-ui-radioInputWidget' );
11509 this.setSelected( config.selected !== undefined ? config.selected : false );
11510 };
11511
11512 /* Setup */
11513
11514 OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget );
11515
11516 /* Methods */
11517
11518 /**
11519 * @inheritdoc
11520 * @private
11521 */
11522 OO.ui.RadioInputWidget.prototype.getInputElement = function () {
11523 return $( '<input type="radio" />' );
11524 };
11525
11526 /**
11527 * @inheritdoc
11528 */
11529 OO.ui.RadioInputWidget.prototype.onEdit = function () {
11530 // RadioInputWidget doesn't track its state.
11531 };
11532
11533 /**
11534 * Set selection state of this radio button.
11535 *
11536 * @param {boolean} state `true` for selected
11537 * @chainable
11538 */
11539 OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) {
11540 // RadioInputWidget doesn't track its state.
11541 this.$input.prop( 'checked', state );
11542 return this;
11543 };
11544
11545 /**
11546 * Check if this radio button is selected.
11547 *
11548 * @return {boolean} Radio is selected
11549 */
11550 OO.ui.RadioInputWidget.prototype.isSelected = function () {
11551 return this.$input.prop( 'checked' );
11552 };
11553
11554 /**
11555 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
11556 * size of the field as well as its presentation. In addition, these widgets can be configured
11557 * with {@link OO.ui.IconElement icons}, {@link OO.ui.IndicatorElement indicators}, an optional
11558 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
11559 * which modifies incoming values rather than validating them.
11560 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11561 *
11562 * @example
11563 * // Example of a text input widget
11564 * var textInput = new OO.ui.TextInputWidget( {
11565 * value: 'Text input'
11566 * } )
11567 * $( 'body' ).append( textInput.$element );
11568 *
11569 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11570 *
11571 * @class
11572 * @extends OO.ui.InputWidget
11573 * @mixins OO.ui.IconElement
11574 * @mixins OO.ui.IndicatorElement
11575 * @mixins OO.ui.PendingElement
11576 * @mixins OO.ui.LabelElement
11577 *
11578 * @constructor
11579 * @param {Object} [config] Configuration options
11580 * @cfg {string} [type='text'] The value of the HTML `type` attribute
11581 * @cfg {string} [placeholder] Placeholder text
11582 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
11583 * instruct the browser to focus this widget.
11584 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
11585 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
11586 * @cfg {boolean} [multiline=false] Allow multiple lines of text
11587 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
11588 * Use the #maxRows config to specify a maximum number of displayed rows.
11589 * @cfg {boolean} [maxRows=10] Maximum number of rows to display when #autosize is set to true.
11590 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
11591 * the value or placeholder text: `'before'` or `'after'`
11592 * @cfg {boolean} [required=false] Mark the field as required
11593 * @cfg {RegExp|string} [validate] Validation pattern, either a regular expression or the
11594 * symbolic name of a pattern defined by the class: 'non-empty' (the value cannot be an empty string)
11595 * or 'integer' (the value must contain only numbers).
11596 */
11597 OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) {
11598 // Configuration initialization
11599 config = $.extend( {
11600 type: 'text',
11601 labelPosition: 'after',
11602 maxRows: 10
11603 }, config );
11604
11605 // Parent constructor
11606 OO.ui.TextInputWidget.super.call( this, config );
11607
11608 // Mixin constructors
11609 OO.ui.IconElement.call( this, config );
11610 OO.ui.IndicatorElement.call( this, config );
11611 OO.ui.PendingElement.call( this, config );
11612 OO.ui.LabelElement.call( this, config );
11613
11614 // Properties
11615 this.readOnly = false;
11616 this.multiline = !!config.multiline;
11617 this.autosize = !!config.autosize;
11618 this.maxRows = config.maxRows;
11619 this.validate = null;
11620
11621 // Clone for resizing
11622 if ( this.autosize ) {
11623 this.$clone = this.$input
11624 .clone()
11625 .insertAfter( this.$input )
11626 .attr( 'aria-hidden', 'true' )
11627 .addClass( 'oo-ui-element-hidden' );
11628 }
11629
11630 this.setValidation( config.validate );
11631 this.setLabelPosition( config.labelPosition );
11632
11633 // Events
11634 this.$input.on( {
11635 keypress: this.onKeyPress.bind( this ),
11636 blur: this.setValidityFlag.bind( this )
11637 } );
11638 this.$input.one( {
11639 focus: this.onElementAttach.bind( this )
11640 } );
11641 this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) );
11642 this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) );
11643 this.on( 'labelChange', this.updatePosition.bind( this ) );
11644
11645 // Initialization
11646 this.$element
11647 .addClass( 'oo-ui-textInputWidget' )
11648 .append( this.$icon, this.$indicator );
11649 this.setReadOnly( !!config.readOnly );
11650 if ( config.placeholder ) {
11651 this.$input.attr( 'placeholder', config.placeholder );
11652 }
11653 if ( config.maxLength !== undefined ) {
11654 this.$input.attr( 'maxlength', config.maxLength );
11655 }
11656 if ( config.autofocus ) {
11657 this.$input.attr( 'autofocus', 'autofocus' );
11658 }
11659 if ( config.required ) {
11660 this.$input.attr( 'required', 'true' );
11661 }
11662 if ( this.label || config.autosize ) {
11663 this.installParentChangeDetector();
11664 }
11665 };
11666
11667 /* Setup */
11668
11669 OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget );
11670 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IconElement );
11671 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.IndicatorElement );
11672 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.PendingElement );
11673 OO.mixinClass( OO.ui.TextInputWidget, OO.ui.LabelElement );
11674
11675 /* Static properties */
11676
11677 OO.ui.TextInputWidget.static.validationPatterns = {
11678 'non-empty': /.+/,
11679 integer: /^\d+$/
11680 };
11681
11682 /* Events */
11683
11684 /**
11685 * An `enter` event is emitted when the user presses 'enter' inside the text box.
11686 *
11687 * Not emitted if the input is multiline.
11688 *
11689 * @event enter
11690 */
11691
11692 /* Methods */
11693
11694 /**
11695 * Handle icon mouse down events.
11696 *
11697 * @private
11698 * @param {jQuery.Event} e Mouse down event
11699 * @fires icon
11700 */
11701 OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) {
11702 if ( e.which === 1 ) {
11703 this.$input[ 0 ].focus();
11704 return false;
11705 }
11706 };
11707
11708 /**
11709 * Handle indicator mouse down events.
11710 *
11711 * @private
11712 * @param {jQuery.Event} e Mouse down event
11713 * @fires indicator
11714 */
11715 OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) {
11716 if ( e.which === 1 ) {
11717 this.$input[ 0 ].focus();
11718 return false;
11719 }
11720 };
11721
11722 /**
11723 * Handle key press events.
11724 *
11725 * @private
11726 * @param {jQuery.Event} e Key press event
11727 * @fires enter If enter key is pressed and input is not multiline
11728 */
11729 OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) {
11730 if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) {
11731 this.emit( 'enter', e );
11732 }
11733 };
11734
11735 /**
11736 * Handle element attach events.
11737 *
11738 * @private
11739 * @param {jQuery.Event} e Element attach event
11740 */
11741 OO.ui.TextInputWidget.prototype.onElementAttach = function () {
11742 // Any previously calculated size is now probably invalid if we reattached elsewhere
11743 this.valCache = null;
11744 this.adjustSize();
11745 this.positionLabel();
11746 };
11747
11748 /**
11749 * @inheritdoc
11750 */
11751 OO.ui.TextInputWidget.prototype.onEdit = function () {
11752 this.adjustSize();
11753
11754 // Parent method
11755 return OO.ui.TextInputWidget.super.prototype.onEdit.call( this );
11756 };
11757
11758 /**
11759 * @inheritdoc
11760 */
11761 OO.ui.TextInputWidget.prototype.setValue = function ( value ) {
11762 // Parent method
11763 OO.ui.TextInputWidget.super.prototype.setValue.call( this, value );
11764
11765 this.setValidityFlag();
11766 this.adjustSize();
11767 return this;
11768 };
11769
11770 /**
11771 * Check if the input is {@link #readOnly read-only}.
11772 *
11773 * @return {boolean}
11774 */
11775 OO.ui.TextInputWidget.prototype.isReadOnly = function () {
11776 return this.readOnly;
11777 };
11778
11779 /**
11780 * Set the {@link #readOnly read-only} state of the input.
11781 *
11782 * @param {boolean} state Make input read-only
11783 * @chainable
11784 */
11785 OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) {
11786 this.readOnly = !!state;
11787 this.$input.prop( 'readOnly', this.readOnly );
11788 return this;
11789 };
11790
11791 /**
11792 * Support function for making #onElementAttach work across browsers.
11793 *
11794 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
11795 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
11796 *
11797 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
11798 * first time that the element gets attached to the documented.
11799 */
11800 OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () {
11801 var mutationObserver, onRemove, topmostNode, fakeParentNode,
11802 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
11803 widget = this;
11804
11805 if ( MutationObserver ) {
11806 // The new way. If only it wasn't so ugly.
11807
11808 if ( this.$element.closest( 'html' ).length ) {
11809 // Widget is attached already, do nothing. This breaks the functionality of this function when
11810 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
11811 // would require observation of the whole document, which would hurt performance of other,
11812 // more important code.
11813 return;
11814 }
11815
11816 // Find topmost node in the tree
11817 topmostNode = this.$element[0];
11818 while ( topmostNode.parentNode ) {
11819 topmostNode = topmostNode.parentNode;
11820 }
11821
11822 // We have no way to detect the $element being attached somewhere without observing the entire
11823 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
11824 // parent node of $element, and instead detect when $element is removed from it (and thus
11825 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
11826 // doesn't get attached, we end up back here and create the parent.
11827
11828 mutationObserver = new MutationObserver( function ( mutations ) {
11829 var i, j, removedNodes;
11830 for ( i = 0; i < mutations.length; i++ ) {
11831 removedNodes = mutations[ i ].removedNodes;
11832 for ( j = 0; j < removedNodes.length; j++ ) {
11833 if ( removedNodes[ j ] === topmostNode ) {
11834 setTimeout( onRemove, 0 );
11835 return;
11836 }
11837 }
11838 }
11839 } );
11840
11841 onRemove = function () {
11842 // If the node was attached somewhere else, report it
11843 if ( widget.$element.closest( 'html' ).length ) {
11844 widget.onElementAttach();
11845 }
11846 mutationObserver.disconnect();
11847 widget.installParentChangeDetector();
11848 };
11849
11850 // Create a fake parent and observe it
11851 fakeParentNode = $( '<div>' ).append( this.$element )[0];
11852 mutationObserver.observe( fakeParentNode, { childList: true } );
11853 } else {
11854 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
11855 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
11856 this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) );
11857 }
11858 };
11859
11860 /**
11861 * Automatically adjust the size of the text input.
11862 *
11863 * This only affects #multiline inputs that are {@link #autosize autosized}.
11864 *
11865 * @chainable
11866 */
11867 OO.ui.TextInputWidget.prototype.adjustSize = function () {
11868 var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight;
11869
11870 if ( this.multiline && this.autosize && this.$input.val() !== this.valCache ) {
11871 this.$clone
11872 .val( this.$input.val() )
11873 .attr( 'rows', '' )
11874 // Set inline height property to 0 to measure scroll height
11875 .css( 'height', 0 );
11876
11877 this.$clone.removeClass( 'oo-ui-element-hidden' );
11878
11879 this.valCache = this.$input.val();
11880
11881 scrollHeight = this.$clone[ 0 ].scrollHeight;
11882
11883 // Remove inline height property to measure natural heights
11884 this.$clone.css( 'height', '' );
11885 innerHeight = this.$clone.innerHeight();
11886 outerHeight = this.$clone.outerHeight();
11887
11888 // Measure max rows height
11889 this.$clone
11890 .attr( 'rows', this.maxRows )
11891 .css( 'height', 'auto' )
11892 .val( '' );
11893 maxInnerHeight = this.$clone.innerHeight();
11894
11895 // Difference between reported innerHeight and scrollHeight with no scrollbars present
11896 // Equals 1 on Blink-based browsers and 0 everywhere else
11897 measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight;
11898 idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError );
11899
11900 this.$clone.addClass( 'oo-ui-element-hidden' );
11901
11902 // Only apply inline height when expansion beyond natural height is needed
11903 if ( idealHeight > innerHeight ) {
11904 // Use the difference between the inner and outer height as a buffer
11905 this.$input.css( 'height', idealHeight + ( outerHeight - innerHeight ) );
11906 } else {
11907 this.$input.css( 'height', '' );
11908 }
11909 }
11910 return this;
11911 };
11912
11913 /**
11914 * @inheritdoc
11915 * @private
11916 */
11917 OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) {
11918 return config.multiline ? $( '<textarea>' ) : $( '<input type="' + config.type + '" />' );
11919 };
11920
11921 /**
11922 * Check if the input supports multiple lines.
11923 *
11924 * @return {boolean}
11925 */
11926 OO.ui.TextInputWidget.prototype.isMultiline = function () {
11927 return !!this.multiline;
11928 };
11929
11930 /**
11931 * Check if the input automatically adjusts its size.
11932 *
11933 * @return {boolean}
11934 */
11935 OO.ui.TextInputWidget.prototype.isAutosizing = function () {
11936 return !!this.autosize;
11937 };
11938
11939 /**
11940 * Select the entire text of the input.
11941 *
11942 * @chainable
11943 */
11944 OO.ui.TextInputWidget.prototype.select = function () {
11945 this.$input.select();
11946 return this;
11947 };
11948
11949 /**
11950 * Set the validation pattern.
11951 *
11952 * The validation pattern is either a regular expression or the symbolic name of a pattern
11953 * defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
11954 * value must contain only numbers).
11955 *
11956 * @param {RegExp|string|null} validate Regular expression or the symbolic name of a
11957 * pattern (either ‘integer’ or ‘non-empty’) defined by the class.
11958 */
11959 OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) {
11960 if ( validate instanceof RegExp ) {
11961 this.validate = validate;
11962 } else {
11963 this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/;
11964 }
11965 };
11966
11967 /**
11968 * Sets the 'invalid' flag appropriately.
11969 */
11970 OO.ui.TextInputWidget.prototype.setValidityFlag = function () {
11971 var widget = this;
11972 this.isValid().done( function ( valid ) {
11973 widget.setFlags( { invalid: !valid } );
11974 } );
11975 };
11976
11977 /**
11978 * Check if a value is valid.
11979 *
11980 * This method returns a promise that resolves with a boolean `true` if the current value is
11981 * considered valid according to the supplied {@link #validate validation pattern}.
11982 *
11983 * @return {jQuery.Deferred} A promise that resolves to a boolean `true` if the value is valid.
11984 */
11985 OO.ui.TextInputWidget.prototype.isValid = function () {
11986 return $.Deferred().resolve( !!this.getValue().match( this.validate ) ).promise();
11987 };
11988
11989 /**
11990 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
11991 *
11992 * @param {string} labelPosition Label position, 'before' or 'after'
11993 * @chainable
11994 */
11995 OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) {
11996 this.labelPosition = labelPosition;
11997 this.updatePosition();
11998 return this;
11999 };
12000
12001 /**
12002 * Deprecated alias of #setLabelPosition
12003 *
12004 * @deprecated Use setLabelPosition instead.
12005 */
12006 OO.ui.TextInputWidget.prototype.setPosition =
12007 OO.ui.TextInputWidget.prototype.setLabelPosition;
12008
12009 /**
12010 * Update the position of the inline label.
12011 *
12012 * This method is called by #setLabelPosition, and can also be called on its own if
12013 * something causes the label to be mispositioned.
12014 *
12015 *
12016 * @chainable
12017 */
12018 OO.ui.TextInputWidget.prototype.updatePosition = function () {
12019 var after = this.labelPosition === 'after';
12020
12021 this.$element
12022 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after )
12023 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after );
12024
12025 if ( this.label ) {
12026 this.positionLabel();
12027 }
12028
12029 return this;
12030 };
12031
12032 /**
12033 * Position the label by setting the correct padding on the input.
12034 *
12035 * @private
12036 * @chainable
12037 */
12038 OO.ui.TextInputWidget.prototype.positionLabel = function () {
12039 // Clear old values
12040 this.$input
12041 // Clear old values if present
12042 .css( {
12043 'padding-right': '',
12044 'padding-left': ''
12045 } );
12046
12047 if ( this.label ) {
12048 this.$element.append( this.$label );
12049 } else {
12050 this.$label.detach();
12051 return;
12052 }
12053
12054 var after = this.labelPosition === 'after',
12055 rtl = this.$element.css( 'direction' ) === 'rtl',
12056 property = after === rtl ? 'padding-left' : 'padding-right';
12057
12058 this.$input.css( property, this.$label.outerWidth( true ) );
12059
12060 return this;
12061 };
12062
12063 /**
12064 * ComboBoxWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
12065 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
12066 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
12067 *
12068 * - by typing a value in the text input field. If the value exactly matches the value of a menu
12069 * option, that option will appear to be selected.
12070 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
12071 * input field.
12072 *
12073 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
12074 *
12075 * @example
12076 * // Example: A ComboBoxWidget.
12077 * var comboBox = new OO.ui.ComboBoxWidget( {
12078 * label: 'ComboBoxWidget',
12079 * input: { value: 'Option One' },
12080 * menu: {
12081 * items: [
12082 * new OO.ui.MenuOptionWidget( {
12083 * data: 'Option 1',
12084 * label: 'Option One'
12085 * } ),
12086 * new OO.ui.MenuOptionWidget( {
12087 * data: 'Option 2',
12088 * label: 'Option Two'
12089 * } ),
12090 * new OO.ui.MenuOptionWidget( {
12091 * data: 'Option 3',
12092 * label: 'Option Three'
12093 * } ),
12094 * new OO.ui.MenuOptionWidget( {
12095 * data: 'Option 4',
12096 * label: 'Option Four'
12097 * } ),
12098 * new OO.ui.MenuOptionWidget( {
12099 * data: 'Option 5',
12100 * label: 'Option Five'
12101 * } )
12102 * ]
12103 * }
12104 * } );
12105 * $( 'body' ).append( comboBox.$element );
12106 *
12107 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12108 *
12109 * @class
12110 * @extends OO.ui.Widget
12111 * @mixins OO.ui.TabIndexedElement
12112 *
12113 * @constructor
12114 * @param {Object} [config] Configuration options
12115 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
12116 * @cfg {Object} [input] Configuration options to pass to the {@link OO.ui.TextInputWidget text input widget}.
12117 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
12118 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
12119 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
12120 */
12121 OO.ui.ComboBoxWidget = function OoUiComboBoxWidget( config ) {
12122 // Configuration initialization
12123 config = config || {};
12124
12125 // Parent constructor
12126 OO.ui.ComboBoxWidget.super.call( this, config );
12127
12128 // Properties (must be set before TabIndexedElement constructor call)
12129 this.$indicator = this.$( '<span>' );
12130
12131 // Mixin constructors
12132 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$indicator } ) );
12133
12134 // Properties
12135 this.$overlay = config.$overlay || this.$element;
12136 this.input = new OO.ui.TextInputWidget( $.extend(
12137 {
12138 indicator: 'down',
12139 $indicator: this.$indicator,
12140 disabled: this.isDisabled()
12141 },
12142 config.input
12143 ) );
12144 this.input.$input.eq( 0 ).attr( {
12145 role: 'combobox',
12146 'aria-autocomplete': 'list'
12147 } );
12148 this.menu = new OO.ui.TextInputMenuSelectWidget( this.input, $.extend(
12149 {
12150 widget: this,
12151 input: this.input,
12152 disabled: this.isDisabled()
12153 },
12154 config.menu
12155 ) );
12156
12157 // Events
12158 this.$indicator.on( {
12159 click: this.onClick.bind( this ),
12160 keypress: this.onKeyPress.bind( this )
12161 } );
12162 this.input.connect( this, {
12163 change: 'onInputChange',
12164 enter: 'onInputEnter'
12165 } );
12166 this.menu.connect( this, {
12167 choose: 'onMenuChoose',
12168 add: 'onMenuItemsChange',
12169 remove: 'onMenuItemsChange'
12170 } );
12171
12172 // Initialization
12173 this.$element.addClass( 'oo-ui-comboBoxWidget' ).append( this.input.$element );
12174 this.$overlay.append( this.menu.$element );
12175 this.onMenuItemsChange();
12176 };
12177
12178 /* Setup */
12179
12180 OO.inheritClass( OO.ui.ComboBoxWidget, OO.ui.Widget );
12181 OO.mixinClass( OO.ui.ComboBoxWidget, OO.ui.TabIndexedElement );
12182
12183 /* Methods */
12184
12185 /**
12186 * Get the combobox's menu.
12187 * @return {OO.ui.TextInputMenuSelectWidget} Menu widget
12188 */
12189 OO.ui.ComboBoxWidget.prototype.getMenu = function () {
12190 return this.menu;
12191 };
12192
12193 /**
12194 * Handle input change events.
12195 *
12196 * @private
12197 * @param {string} value New value
12198 */
12199 OO.ui.ComboBoxWidget.prototype.onInputChange = function ( value ) {
12200 var match = this.menu.getItemFromData( value );
12201
12202 this.menu.selectItem( match );
12203 if ( this.menu.getHighlightedItem() ) {
12204 this.menu.highlightItem( match );
12205 }
12206
12207 if ( !this.isDisabled() ) {
12208 this.menu.toggle( true );
12209 }
12210 };
12211
12212 /**
12213 * Handle mouse click events.
12214 *
12215 *
12216 * @private
12217 * @param {jQuery.Event} e Mouse click event
12218 */
12219 OO.ui.ComboBoxWidget.prototype.onClick = function ( e ) {
12220 if ( !this.isDisabled() && e.which === 1 ) {
12221 this.menu.toggle();
12222 this.input.$input[ 0 ].focus();
12223 }
12224 return false;
12225 };
12226
12227 /**
12228 * Handle key press events.
12229 *
12230 *
12231 * @private
12232 * @param {jQuery.Event} e Key press event
12233 */
12234 OO.ui.ComboBoxWidget.prototype.onKeyPress = function ( e ) {
12235 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
12236 this.menu.toggle();
12237 this.input.$input[ 0 ].focus();
12238 return false;
12239 }
12240 };
12241
12242 /**
12243 * Handle input enter events.
12244 *
12245 * @private
12246 */
12247 OO.ui.ComboBoxWidget.prototype.onInputEnter = function () {
12248 if ( !this.isDisabled() ) {
12249 this.menu.toggle( false );
12250 }
12251 };
12252
12253 /**
12254 * Handle menu choose events.
12255 *
12256 * @private
12257 * @param {OO.ui.OptionWidget} item Chosen item
12258 */
12259 OO.ui.ComboBoxWidget.prototype.onMenuChoose = function ( item ) {
12260 if ( item ) {
12261 this.input.setValue( item.getData() );
12262 }
12263 };
12264
12265 /**
12266 * Handle menu item change events.
12267 *
12268 * @private
12269 */
12270 OO.ui.ComboBoxWidget.prototype.onMenuItemsChange = function () {
12271 var match = this.menu.getItemFromData( this.input.getValue() );
12272 this.menu.selectItem( match );
12273 if ( this.menu.getHighlightedItem() ) {
12274 this.menu.highlightItem( match );
12275 }
12276 this.$element.toggleClass( 'oo-ui-comboBoxWidget-empty', this.menu.isEmpty() );
12277 };
12278
12279 /**
12280 * @inheritdoc
12281 */
12282 OO.ui.ComboBoxWidget.prototype.setDisabled = function ( disabled ) {
12283 // Parent method
12284 OO.ui.ComboBoxWidget.super.prototype.setDisabled.call( this, disabled );
12285
12286 if ( this.input ) {
12287 this.input.setDisabled( this.isDisabled() );
12288 }
12289 if ( this.menu ) {
12290 this.menu.setDisabled( this.isDisabled() );
12291 }
12292
12293 return this;
12294 };
12295
12296 /**
12297 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
12298 * be configured with a `label` option that is set to a string, a label node, or a function:
12299 *
12300 * - String: a plaintext string
12301 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
12302 * label that includes a link or special styling, such as a gray color or additional graphical elements.
12303 * - Function: a function that will produce a string in the future. Functions are used
12304 * in cases where the value of the label is not currently defined.
12305 *
12306 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
12307 * will come into focus when the label is clicked.
12308 *
12309 * @example
12310 * // Examples of LabelWidgets
12311 * var label1 = new OO.ui.LabelWidget( {
12312 * label: 'plaintext label'
12313 * } );
12314 * var label2 = new OO.ui.LabelWidget( {
12315 * label: $( '<a href="default.html">jQuery label</a>' )
12316 * } );
12317 * // Create a fieldset layout with fields for each example
12318 * var fieldset = new OO.ui.FieldsetLayout();
12319 * fieldset.addItems( [
12320 * new OO.ui.FieldLayout( label1 ),
12321 * new OO.ui.FieldLayout( label2 )
12322 * ] );
12323 * $( 'body' ).append( fieldset.$element );
12324 *
12325 *
12326 * @class
12327 * @extends OO.ui.Widget
12328 * @mixins OO.ui.LabelElement
12329 *
12330 * @constructor
12331 * @param {Object} [config] Configuration options
12332 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
12333 * Clicking the label will focus the specified input field.
12334 */
12335 OO.ui.LabelWidget = function OoUiLabelWidget( config ) {
12336 // Configuration initialization
12337 config = config || {};
12338
12339 // Parent constructor
12340 OO.ui.LabelWidget.super.call( this, config );
12341
12342 // Mixin constructors
12343 OO.ui.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) );
12344 OO.ui.TitledElement.call( this, config );
12345
12346 // Properties
12347 this.input = config.input;
12348
12349 // Events
12350 if ( this.input instanceof OO.ui.InputWidget ) {
12351 this.$element.on( 'click', this.onClick.bind( this ) );
12352 }
12353
12354 // Initialization
12355 this.$element.addClass( 'oo-ui-labelWidget' );
12356 };
12357
12358 /* Setup */
12359
12360 OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget );
12361 OO.mixinClass( OO.ui.LabelWidget, OO.ui.LabelElement );
12362 OO.mixinClass( OO.ui.LabelWidget, OO.ui.TitledElement );
12363
12364 /* Static Properties */
12365
12366 OO.ui.LabelWidget.static.tagName = 'span';
12367
12368 /* Methods */
12369
12370 /**
12371 * Handles label mouse click events.
12372 *
12373 * @private
12374 * @param {jQuery.Event} e Mouse click event
12375 */
12376 OO.ui.LabelWidget.prototype.onClick = function () {
12377 this.input.simulateLabelClick();
12378 return false;
12379 };
12380
12381 /**
12382 * OptionWidgets are special elements that can be selected and configured with data. The
12383 * data is often unique for each option, but it does not have to be. OptionWidgets are used
12384 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
12385 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
12386 *
12387 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12388 *
12389 * @class
12390 * @extends OO.ui.Widget
12391 * @mixins OO.ui.LabelElement
12392 * @mixins OO.ui.FlaggedElement
12393 *
12394 * @constructor
12395 * @param {Object} [config] Configuration options
12396 */
12397 OO.ui.OptionWidget = function OoUiOptionWidget( config ) {
12398 // Configuration initialization
12399 config = config || {};
12400
12401 // Parent constructor
12402 OO.ui.OptionWidget.super.call( this, config );
12403
12404 // Mixin constructors
12405 OO.ui.ItemWidget.call( this );
12406 OO.ui.LabelElement.call( this, config );
12407 OO.ui.FlaggedElement.call( this, config );
12408
12409 // Properties
12410 this.selected = false;
12411 this.highlighted = false;
12412 this.pressed = false;
12413
12414 // Initialization
12415 this.$element
12416 .data( 'oo-ui-optionWidget', this )
12417 .attr( 'role', 'option' )
12418 .addClass( 'oo-ui-optionWidget' )
12419 .append( this.$label );
12420 };
12421
12422 /* Setup */
12423
12424 OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget );
12425 OO.mixinClass( OO.ui.OptionWidget, OO.ui.ItemWidget );
12426 OO.mixinClass( OO.ui.OptionWidget, OO.ui.LabelElement );
12427 OO.mixinClass( OO.ui.OptionWidget, OO.ui.FlaggedElement );
12428
12429 /* Static Properties */
12430
12431 OO.ui.OptionWidget.static.selectable = true;
12432
12433 OO.ui.OptionWidget.static.highlightable = true;
12434
12435 OO.ui.OptionWidget.static.pressable = true;
12436
12437 OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false;
12438
12439 /* Methods */
12440
12441 /**
12442 * Check if the option can be selected.
12443 *
12444 * @return {boolean} Item is selectable
12445 */
12446 OO.ui.OptionWidget.prototype.isSelectable = function () {
12447 return this.constructor.static.selectable && !this.isDisabled();
12448 };
12449
12450 /**
12451 * Check if the option can be highlighted. A highlight indicates that the option
12452 * may be selected when a user presses enter or clicks. Disabled items cannot
12453 * be highlighted.
12454 *
12455 * @return {boolean} Item is highlightable
12456 */
12457 OO.ui.OptionWidget.prototype.isHighlightable = function () {
12458 return this.constructor.static.highlightable && !this.isDisabled();
12459 };
12460
12461 /**
12462 * Check if the option can be pressed. The pressed state occurs when a user mouses
12463 * down on an item, but has not yet let go of the mouse.
12464 *
12465 * @return {boolean} Item is pressable
12466 */
12467 OO.ui.OptionWidget.prototype.isPressable = function () {
12468 return this.constructor.static.pressable && !this.isDisabled();
12469 };
12470
12471 /**
12472 * Check if the option is selected.
12473 *
12474 * @return {boolean} Item is selected
12475 */
12476 OO.ui.OptionWidget.prototype.isSelected = function () {
12477 return this.selected;
12478 };
12479
12480 /**
12481 * Check if the option is highlighted. A highlight indicates that the
12482 * item may be selected when a user presses enter or clicks.
12483 *
12484 * @return {boolean} Item is highlighted
12485 */
12486 OO.ui.OptionWidget.prototype.isHighlighted = function () {
12487 return this.highlighted;
12488 };
12489
12490 /**
12491 * Check if the option is pressed. The pressed state occurs when a user mouses
12492 * down on an item, but has not yet let go of the mouse. The item may appear
12493 * selected, but it will not be selected until the user releases the mouse.
12494 *
12495 * @return {boolean} Item is pressed
12496 */
12497 OO.ui.OptionWidget.prototype.isPressed = function () {
12498 return this.pressed;
12499 };
12500
12501 /**
12502 * Set the option’s selected state. In general, all modifications to the selection
12503 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
12504 * method instead of this method.
12505 *
12506 * @param {boolean} [state=false] Select option
12507 * @chainable
12508 */
12509 OO.ui.OptionWidget.prototype.setSelected = function ( state ) {
12510 if ( this.constructor.static.selectable ) {
12511 this.selected = !!state;
12512 this.$element
12513 .toggleClass( 'oo-ui-optionWidget-selected', state )
12514 .attr( 'aria-selected', state.toString() );
12515 if ( state && this.constructor.static.scrollIntoViewOnSelect ) {
12516 this.scrollElementIntoView();
12517 }
12518 this.updateThemeClasses();
12519 }
12520 return this;
12521 };
12522
12523 /**
12524 * Set the option’s highlighted state. In general, all programmatic
12525 * modifications to the highlight should be handled by the
12526 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
12527 * method instead of this method.
12528 *
12529 * @param {boolean} [state=false] Highlight option
12530 * @chainable
12531 */
12532 OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) {
12533 if ( this.constructor.static.highlightable ) {
12534 this.highlighted = !!state;
12535 this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state );
12536 this.updateThemeClasses();
12537 }
12538 return this;
12539 };
12540
12541 /**
12542 * Set the option’s pressed state. In general, all
12543 * programmatic modifications to the pressed state should be handled by the
12544 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
12545 * method instead of this method.
12546 *
12547 * @param {boolean} [state=false] Press option
12548 * @chainable
12549 */
12550 OO.ui.OptionWidget.prototype.setPressed = function ( state ) {
12551 if ( this.constructor.static.pressable ) {
12552 this.pressed = !!state;
12553 this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state );
12554 this.updateThemeClasses();
12555 }
12556 return this;
12557 };
12558
12559 /**
12560 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
12561 * with an {@link OO.ui.IconElement icon} and/or {@link OO.ui.IndicatorElement indicator}.
12562 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
12563 * options. For more information about options and selects, please see the
12564 * [OOjs UI documentation on MediaWiki][1].
12565 *
12566 * @example
12567 * // Decorated options in a select widget
12568 * var select = new OO.ui.SelectWidget( {
12569 * items: [
12570 * new OO.ui.DecoratedOptionWidget( {
12571 * data: 'a',
12572 * label: 'Option with icon',
12573 * icon: 'help'
12574 * } ),
12575 * new OO.ui.DecoratedOptionWidget( {
12576 * data: 'b',
12577 * label: 'Option with indicator',
12578 * indicator: 'next'
12579 * } )
12580 * ]
12581 * } );
12582 * $( 'body' ).append( select.$element );
12583 *
12584 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
12585 *
12586 * @class
12587 * @extends OO.ui.OptionWidget
12588 * @mixins OO.ui.IconElement
12589 * @mixins OO.ui.IndicatorElement
12590 *
12591 * @constructor
12592 * @param {Object} [config] Configuration options
12593 */
12594 OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) {
12595 // Parent constructor
12596 OO.ui.DecoratedOptionWidget.super.call( this, config );
12597
12598 // Mixin constructors
12599 OO.ui.IconElement.call( this, config );
12600 OO.ui.IndicatorElement.call( this, config );
12601
12602 // Initialization
12603 this.$element
12604 .addClass( 'oo-ui-decoratedOptionWidget' )
12605 .prepend( this.$icon )
12606 .append( this.$indicator );
12607 };
12608
12609 /* Setup */
12610
12611 OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget );
12612 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IconElement );
12613 OO.mixinClass( OO.ui.OptionWidget, OO.ui.IndicatorElement );
12614
12615 /**
12616 * ButtonOptionWidget is a special type of {@link OO.ui.ButtonElement button element} that
12617 * can be selected and configured with data. The class is
12618 * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the
12619 * [OOjs UI documentation on MediaWiki] [1] for more information.
12620 *
12621 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_options
12622 *
12623 * @class
12624 * @extends OO.ui.DecoratedOptionWidget
12625 * @mixins OO.ui.ButtonElement
12626 * @mixins OO.ui.TabIndexedElement
12627 *
12628 * @constructor
12629 * @param {Object} [config] Configuration options
12630 */
12631 OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) {
12632 // Configuration initialization
12633 config = $.extend( { tabIndex: -1 }, config );
12634
12635 // Parent constructor
12636 OO.ui.ButtonOptionWidget.super.call( this, config );
12637
12638 // Mixin constructors
12639 OO.ui.ButtonElement.call( this, config );
12640 OO.ui.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) );
12641
12642 // Initialization
12643 this.$element.addClass( 'oo-ui-buttonOptionWidget' );
12644 this.$button.append( this.$element.contents() );
12645 this.$element.append( this.$button );
12646 };
12647
12648 /* Setup */
12649
12650 OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.DecoratedOptionWidget );
12651 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.ButtonElement );
12652 OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.TabIndexedElement );
12653
12654 /* Static Properties */
12655
12656 // Allow button mouse down events to pass through so they can be handled by the parent select widget
12657 OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false;
12658
12659 OO.ui.ButtonOptionWidget.static.highlightable = false;
12660
12661 /* Methods */
12662
12663 /**
12664 * @inheritdoc
12665 */
12666 OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) {
12667 OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state );
12668
12669 if ( this.constructor.static.selectable ) {
12670 this.setActive( state );
12671 }
12672
12673 return this;
12674 };
12675
12676 /**
12677 * RadioOptionWidget is an option widget that looks like a radio button.
12678 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
12679 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
12680 *
12681 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
12682 *
12683 * @class
12684 * @extends OO.ui.OptionWidget
12685 *
12686 * @constructor
12687 * @param {Object} [config] Configuration options
12688 */
12689 OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) {
12690 // Configuration initialization
12691 config = config || {};
12692
12693 // Properties (must be done before parent constructor which calls #setDisabled)
12694 this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } );
12695
12696 // Parent constructor
12697 OO.ui.RadioOptionWidget.super.call( this, config );
12698
12699 // Initialization
12700 this.$element
12701 .addClass( 'oo-ui-radioOptionWidget' )
12702 .prepend( this.radio.$element );
12703 };
12704
12705 /* Setup */
12706
12707 OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget );
12708
12709 /* Static Properties */
12710
12711 OO.ui.RadioOptionWidget.static.highlightable = false;
12712
12713 OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true;
12714
12715 OO.ui.RadioOptionWidget.static.pressable = false;
12716
12717 OO.ui.RadioOptionWidget.static.tagName = 'label';
12718
12719 /* Methods */
12720
12721 /**
12722 * @inheritdoc
12723 */
12724 OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) {
12725 OO.ui.RadioOptionWidget.super.prototype.setSelected.call( this, state );
12726
12727 this.radio.setSelected( state );
12728
12729 return this;
12730 };
12731
12732 /**
12733 * @inheritdoc
12734 */
12735 OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) {
12736 OO.ui.RadioOptionWidget.super.prototype.setDisabled.call( this, disabled );
12737
12738 this.radio.setDisabled( this.isDisabled() );
12739
12740 return this;
12741 };
12742
12743 /**
12744 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
12745 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
12746 * the [OOjs UI documentation on MediaWiki] [1] for more information.
12747 *
12748 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
12749 *
12750 * @class
12751 * @extends OO.ui.DecoratedOptionWidget
12752 *
12753 * @constructor
12754 * @param {Object} [config] Configuration options
12755 */
12756 OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) {
12757 // Configuration initialization
12758 config = $.extend( { icon: 'check' }, config );
12759
12760 // Parent constructor
12761 OO.ui.MenuOptionWidget.super.call( this, config );
12762
12763 // Initialization
12764 this.$element
12765 .attr( 'role', 'menuitem' )
12766 .addClass( 'oo-ui-menuOptionWidget' );
12767 };
12768
12769 /* Setup */
12770
12771 OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget );
12772
12773 /* Static Properties */
12774
12775 OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true;
12776
12777 /**
12778 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
12779 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
12780 *
12781 * @example
12782 * var myDropdown = new OO.ui.DropdownWidget( {
12783 * menu: {
12784 * items: [
12785 * new OO.ui.MenuSectionOptionWidget( {
12786 * label: 'Dogs'
12787 * } ),
12788 * new OO.ui.MenuOptionWidget( {
12789 * data: 'corgi',
12790 * label: 'Welsh Corgi'
12791 * } ),
12792 * new OO.ui.MenuOptionWidget( {
12793 * data: 'poodle',
12794 * label: 'Standard Poodle'
12795 * } ),
12796 * new OO.ui.MenuSectionOptionWidget( {
12797 * label: 'Cats'
12798 * } ),
12799 * new OO.ui.MenuOptionWidget( {
12800 * data: 'lion',
12801 * label: 'Lion'
12802 * } )
12803 * ]
12804 * }
12805 * } );
12806 * $( 'body' ).append( myDropdown.$element );
12807 *
12808 *
12809 * @class
12810 * @extends OO.ui.DecoratedOptionWidget
12811 *
12812 * @constructor
12813 * @param {Object} [config] Configuration options
12814 */
12815 OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) {
12816 // Parent constructor
12817 OO.ui.MenuSectionOptionWidget.super.call( this, config );
12818
12819 // Initialization
12820 this.$element.addClass( 'oo-ui-menuSectionOptionWidget' );
12821 };
12822
12823 /* Setup */
12824
12825 OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget );
12826
12827 /* Static Properties */
12828
12829 OO.ui.MenuSectionOptionWidget.static.selectable = false;
12830
12831 OO.ui.MenuSectionOptionWidget.static.highlightable = false;
12832
12833 /**
12834 * Items for an OO.ui.OutlineSelectWidget.
12835 *
12836 * @class
12837 * @extends OO.ui.DecoratedOptionWidget
12838 *
12839 * @constructor
12840 * @param {Object} [config] Configuration options
12841 * @cfg {number} [level] Indentation level
12842 * @cfg {boolean} [movable] Allow modification from outline controls
12843 */
12844 OO.ui.OutlineOptionWidget = function OoUiOutlineOptionWidget( config ) {
12845 // Configuration initialization
12846 config = config || {};
12847
12848 // Parent constructor
12849 OO.ui.OutlineOptionWidget.super.call( this, config );
12850
12851 // Properties
12852 this.level = 0;
12853 this.movable = !!config.movable;
12854 this.removable = !!config.removable;
12855
12856 // Initialization
12857 this.$element.addClass( 'oo-ui-outlineOptionWidget' );
12858 this.setLevel( config.level );
12859 };
12860
12861 /* Setup */
12862
12863 OO.inheritClass( OO.ui.OutlineOptionWidget, OO.ui.DecoratedOptionWidget );
12864
12865 /* Static Properties */
12866
12867 OO.ui.OutlineOptionWidget.static.highlightable = false;
12868
12869 OO.ui.OutlineOptionWidget.static.scrollIntoViewOnSelect = true;
12870
12871 OO.ui.OutlineOptionWidget.static.levelClass = 'oo-ui-outlineOptionWidget-level-';
12872
12873 OO.ui.OutlineOptionWidget.static.levels = 3;
12874
12875 /* Methods */
12876
12877 /**
12878 * Check if item is movable.
12879 *
12880 * Movability is used by outline controls.
12881 *
12882 * @return {boolean} Item is movable
12883 */
12884 OO.ui.OutlineOptionWidget.prototype.isMovable = function () {
12885 return this.movable;
12886 };
12887
12888 /**
12889 * Check if item is removable.
12890 *
12891 * Removability is used by outline controls.
12892 *
12893 * @return {boolean} Item is removable
12894 */
12895 OO.ui.OutlineOptionWidget.prototype.isRemovable = function () {
12896 return this.removable;
12897 };
12898
12899 /**
12900 * Get indentation level.
12901 *
12902 * @return {number} Indentation level
12903 */
12904 OO.ui.OutlineOptionWidget.prototype.getLevel = function () {
12905 return this.level;
12906 };
12907
12908 /**
12909 * Set movability.
12910 *
12911 * Movability is used by outline controls.
12912 *
12913 * @param {boolean} movable Item is movable
12914 * @chainable
12915 */
12916 OO.ui.OutlineOptionWidget.prototype.setMovable = function ( movable ) {
12917 this.movable = !!movable;
12918 this.updateThemeClasses();
12919 return this;
12920 };
12921
12922 /**
12923 * Set removability.
12924 *
12925 * Removability is used by outline controls.
12926 *
12927 * @param {boolean} movable Item is removable
12928 * @chainable
12929 */
12930 OO.ui.OutlineOptionWidget.prototype.setRemovable = function ( removable ) {
12931 this.removable = !!removable;
12932 this.updateThemeClasses();
12933 return this;
12934 };
12935
12936 /**
12937 * Set indentation level.
12938 *
12939 * @param {number} [level=0] Indentation level, in the range of [0,#maxLevel]
12940 * @chainable
12941 */
12942 OO.ui.OutlineOptionWidget.prototype.setLevel = function ( level ) {
12943 var levels = this.constructor.static.levels,
12944 levelClass = this.constructor.static.levelClass,
12945 i = levels;
12946
12947 this.level = level ? Math.max( 0, Math.min( levels - 1, level ) ) : 0;
12948 while ( i-- ) {
12949 if ( this.level === i ) {
12950 this.$element.addClass( levelClass + i );
12951 } else {
12952 this.$element.removeClass( levelClass + i );
12953 }
12954 }
12955 this.updateThemeClasses();
12956
12957 return this;
12958 };
12959
12960 /**
12961 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
12962 * By default, each popup has an anchor that points toward its origin.
12963 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
12964 *
12965 * @example
12966 * // A popup widget.
12967 * var popup = new OO.ui.PopupWidget( {
12968 * $content: $( '<p>Hi there!</p>' ),
12969 * padded: true,
12970 * width: 300
12971 * } );
12972 *
12973 * $( 'body' ).append( popup.$element );
12974 * // To display the popup, toggle the visibility to 'true'.
12975 * popup.toggle( true );
12976 *
12977 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
12978 *
12979 * @class
12980 * @extends OO.ui.Widget
12981 * @mixins OO.ui.LabelElement
12982 *
12983 * @constructor
12984 * @param {Object} [config] Configuration options
12985 * @cfg {number} [width=320] Width of popup in pixels
12986 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
12987 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
12988 * @cfg {string} [align='center'] Alignment of the popup: `center`, `left`, or `right`.
12989 * If the popup is right-aligned, the right edge of the popup is aligned to the anchor.
12990 * For left-aligned popups, the left edge is aligned to the anchor.
12991 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
12992 * See the [OOjs UI docs on MediaWiki][3] for an example.
12993 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
12994 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
12995 * @cfg {jQuery} [$content] Content to append to the popup's body
12996 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
12997 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
12998 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
12999 * for an example.
13000 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
13001 * @cfg {boolean} [head] Show a popup header that contains a #label (if specified) and close
13002 * button.
13003 * @cfg {boolean} [padded] Add padding to the popup's body
13004 */
13005 OO.ui.PopupWidget = function OoUiPopupWidget( config ) {
13006 // Configuration initialization
13007 config = config || {};
13008
13009 // Parent constructor
13010 OO.ui.PopupWidget.super.call( this, config );
13011
13012 // Properties (must be set before ClippableElement constructor call)
13013 this.$body = $( '<div>' );
13014
13015 // Mixin constructors
13016 OO.ui.LabelElement.call( this, config );
13017 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body } ) );
13018
13019 // Properties
13020 this.$popup = $( '<div>' );
13021 this.$head = $( '<div>' );
13022 this.$anchor = $( '<div>' );
13023 // If undefined, will be computed lazily in updateDimensions()
13024 this.$container = config.$container;
13025 this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10;
13026 this.autoClose = !!config.autoClose;
13027 this.$autoCloseIgnore = config.$autoCloseIgnore;
13028 this.transitionTimeout = null;
13029 this.anchor = null;
13030 this.width = config.width !== undefined ? config.width : 320;
13031 this.height = config.height !== undefined ? config.height : null;
13032 this.align = config.align || 'center';
13033 this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } );
13034 this.onMouseDownHandler = this.onMouseDown.bind( this );
13035 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
13036
13037 // Events
13038 this.closeButton.connect( this, { click: 'onCloseButtonClick' } );
13039
13040 // Initialization
13041 this.toggleAnchor( config.anchor === undefined || config.anchor );
13042 this.$body.addClass( 'oo-ui-popupWidget-body' );
13043 this.$anchor.addClass( 'oo-ui-popupWidget-anchor' );
13044 this.$head
13045 .addClass( 'oo-ui-popupWidget-head' )
13046 .append( this.$label, this.closeButton.$element );
13047 if ( !config.head ) {
13048 this.$head.addClass( 'oo-ui-element-hidden' );
13049 }
13050 this.$popup
13051 .addClass( 'oo-ui-popupWidget-popup' )
13052 .append( this.$head, this.$body );
13053 this.$element
13054 .addClass( 'oo-ui-popupWidget' )
13055 .append( this.$popup, this.$anchor );
13056 // Move content, which was added to #$element by OO.ui.Widget, to the body
13057 if ( config.$content instanceof jQuery ) {
13058 this.$body.append( config.$content );
13059 }
13060 if ( config.padded ) {
13061 this.$body.addClass( 'oo-ui-popupWidget-body-padded' );
13062 }
13063
13064 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
13065 // that reference properties not initialized at that time of parent class construction
13066 // TODO: Find a better way to handle post-constructor setup
13067 this.visible = false;
13068 this.$element.addClass( 'oo-ui-element-hidden' );
13069 };
13070
13071 /* Setup */
13072
13073 OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget );
13074 OO.mixinClass( OO.ui.PopupWidget, OO.ui.LabelElement );
13075 OO.mixinClass( OO.ui.PopupWidget, OO.ui.ClippableElement );
13076
13077 /* Methods */
13078
13079 /**
13080 * Handles mouse down events.
13081 *
13082 * @private
13083 * @param {MouseEvent} e Mouse down event
13084 */
13085 OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) {
13086 if (
13087 this.isVisible() &&
13088 !$.contains( this.$element[ 0 ], e.target ) &&
13089 ( !this.$autoCloseIgnore || !this.$autoCloseIgnore.has( e.target ).length )
13090 ) {
13091 this.toggle( false );
13092 }
13093 };
13094
13095 /**
13096 * Bind mouse down listener.
13097 *
13098 * @private
13099 */
13100 OO.ui.PopupWidget.prototype.bindMouseDownListener = function () {
13101 // Capture clicks outside popup
13102 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true );
13103 };
13104
13105 /**
13106 * Handles close button click events.
13107 *
13108 * @private
13109 */
13110 OO.ui.PopupWidget.prototype.onCloseButtonClick = function () {
13111 if ( this.isVisible() ) {
13112 this.toggle( false );
13113 }
13114 };
13115
13116 /**
13117 * Unbind mouse down listener.
13118 *
13119 * @private
13120 */
13121 OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () {
13122 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true );
13123 };
13124
13125 /**
13126 * Handles key down events.
13127 *
13128 * @private
13129 * @param {KeyboardEvent} e Key down event
13130 */
13131 OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) {
13132 if (
13133 e.which === OO.ui.Keys.ESCAPE &&
13134 this.isVisible()
13135 ) {
13136 this.toggle( false );
13137 e.preventDefault();
13138 e.stopPropagation();
13139 }
13140 };
13141
13142 /**
13143 * Bind key down listener.
13144 *
13145 * @private
13146 */
13147 OO.ui.PopupWidget.prototype.bindKeyDownListener = function () {
13148 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13149 };
13150
13151 /**
13152 * Unbind key down listener.
13153 *
13154 * @private
13155 */
13156 OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () {
13157 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true );
13158 };
13159
13160 /**
13161 * Show, hide, or toggle the visibility of the anchor.
13162 *
13163 * @param {boolean} [show] Show anchor, omit to toggle
13164 */
13165 OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) {
13166 show = show === undefined ? !this.anchored : !!show;
13167
13168 if ( this.anchored !== show ) {
13169 if ( show ) {
13170 this.$element.addClass( 'oo-ui-popupWidget-anchored' );
13171 } else {
13172 this.$element.removeClass( 'oo-ui-popupWidget-anchored' );
13173 }
13174 this.anchored = show;
13175 }
13176 };
13177
13178 /**
13179 * Check if the anchor is visible.
13180 *
13181 * @return {boolean} Anchor is visible
13182 */
13183 OO.ui.PopupWidget.prototype.hasAnchor = function () {
13184 return this.anchor;
13185 };
13186
13187 /**
13188 * @inheritdoc
13189 */
13190 OO.ui.PopupWidget.prototype.toggle = function ( show ) {
13191 show = show === undefined ? !this.isVisible() : !!show;
13192
13193 var change = show !== this.isVisible();
13194
13195 // Parent method
13196 OO.ui.PopupWidget.super.prototype.toggle.call( this, show );
13197
13198 if ( change ) {
13199 if ( show ) {
13200 if ( this.autoClose ) {
13201 this.bindMouseDownListener();
13202 this.bindKeyDownListener();
13203 }
13204 this.updateDimensions();
13205 this.toggleClipping( true );
13206 } else {
13207 this.toggleClipping( false );
13208 if ( this.autoClose ) {
13209 this.unbindMouseDownListener();
13210 this.unbindKeyDownListener();
13211 }
13212 }
13213 }
13214
13215 return this;
13216 };
13217
13218 /**
13219 * Set the size of the popup.
13220 *
13221 * Changing the size may also change the popup's position depending on the alignment.
13222 *
13223 * @param {number} width Width in pixels
13224 * @param {number} height Height in pixels
13225 * @param {boolean} [transition=false] Use a smooth transition
13226 * @chainable
13227 */
13228 OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) {
13229 this.width = width;
13230 this.height = height !== undefined ? height : null;
13231 if ( this.isVisible() ) {
13232 this.updateDimensions( transition );
13233 }
13234 };
13235
13236 /**
13237 * Update the size and position.
13238 *
13239 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
13240 * be called automatically.
13241 *
13242 * @param {boolean} [transition=false] Use a smooth transition
13243 * @chainable
13244 */
13245 OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) {
13246 var popupOffset, originOffset, containerLeft, containerWidth, containerRight,
13247 popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth,
13248 widget = this;
13249
13250 if ( !this.$container ) {
13251 // Lazy-initialize $container if not specified in constructor
13252 this.$container = $( this.getClosestScrollableElementContainer() );
13253 }
13254
13255 // Set height and width before measuring things, since it might cause our measurements
13256 // to change (e.g. due to scrollbars appearing or disappearing)
13257 this.$popup.css( {
13258 width: this.width,
13259 height: this.height !== null ? this.height : 'auto'
13260 } );
13261
13262 // Compute initial popupOffset based on alignment
13263 popupOffset = this.width * ( { left: 0, center: -0.5, right: -1 } )[ this.align ];
13264
13265 // Figure out if this will cause the popup to go beyond the edge of the container
13266 originOffset = this.$element.offset().left;
13267 containerLeft = this.$container.offset().left;
13268 containerWidth = this.$container.innerWidth();
13269 containerRight = containerLeft + containerWidth;
13270 popupLeft = popupOffset - this.containerPadding;
13271 popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding;
13272 overlapLeft = ( originOffset + popupLeft ) - containerLeft;
13273 overlapRight = containerRight - ( originOffset + popupRight );
13274
13275 // Adjust offset to make the popup not go beyond the edge, if needed
13276 if ( overlapRight < 0 ) {
13277 popupOffset += overlapRight;
13278 } else if ( overlapLeft < 0 ) {
13279 popupOffset -= overlapLeft;
13280 }
13281
13282 // Adjust offset to avoid anchor being rendered too close to the edge
13283 // $anchor.width() doesn't work with the pure CSS anchor (returns 0)
13284 // TODO: Find a measurement that works for CSS anchors and image anchors
13285 anchorWidth = this.$anchor[ 0 ].scrollWidth * 2;
13286 if ( popupOffset + this.width < anchorWidth ) {
13287 popupOffset = anchorWidth - this.width;
13288 } else if ( -popupOffset < anchorWidth ) {
13289 popupOffset = -anchorWidth;
13290 }
13291
13292 // Prevent transition from being interrupted
13293 clearTimeout( this.transitionTimeout );
13294 if ( transition ) {
13295 // Enable transition
13296 this.$element.addClass( 'oo-ui-popupWidget-transitioning' );
13297 }
13298
13299 // Position body relative to anchor
13300 this.$popup.css( 'margin-left', popupOffset );
13301
13302 if ( transition ) {
13303 // Prevent transitioning after transition is complete
13304 this.transitionTimeout = setTimeout( function () {
13305 widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13306 }, 200 );
13307 } else {
13308 // Prevent transitioning immediately
13309 this.$element.removeClass( 'oo-ui-popupWidget-transitioning' );
13310 }
13311
13312 // Reevaluate clipping state since we've relocated and resized the popup
13313 this.clip();
13314
13315 return this;
13316 };
13317
13318 /**
13319 * Progress bars visually display the status of an operation, such as a download,
13320 * and can be either determinate or indeterminate:
13321 *
13322 * - **determinate** process bars show the percent of an operation that is complete.
13323 *
13324 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
13325 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
13326 * not use percentages.
13327 *
13328 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
13329 *
13330 * @example
13331 * // Examples of determinate and indeterminate progress bars.
13332 * var progressBar1 = new OO.ui.ProgressBarWidget( {
13333 * progress: 33
13334 * } );
13335 * var progressBar2 = new OO.ui.ProgressBarWidget();
13336 *
13337 * // Create a FieldsetLayout to layout progress bars
13338 * var fieldset = new OO.ui.FieldsetLayout;
13339 * fieldset.addItems( [
13340 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
13341 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
13342 * ] );
13343 * $( 'body' ).append( fieldset.$element );
13344 *
13345 * @class
13346 * @extends OO.ui.Widget
13347 *
13348 * @constructor
13349 * @param {Object} [config] Configuration options
13350 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
13351 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
13352 * By default, the progress bar is indeterminate.
13353 */
13354 OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) {
13355 // Configuration initialization
13356 config = config || {};
13357
13358 // Parent constructor
13359 OO.ui.ProgressBarWidget.super.call( this, config );
13360
13361 // Properties
13362 this.$bar = $( '<div>' );
13363 this.progress = null;
13364
13365 // Initialization
13366 this.setProgress( config.progress !== undefined ? config.progress : false );
13367 this.$bar.addClass( 'oo-ui-progressBarWidget-bar' );
13368 this.$element
13369 .attr( {
13370 role: 'progressbar',
13371 'aria-valuemin': 0,
13372 'aria-valuemax': 100
13373 } )
13374 .addClass( 'oo-ui-progressBarWidget' )
13375 .append( this.$bar );
13376 };
13377
13378 /* Setup */
13379
13380 OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget );
13381
13382 /* Static Properties */
13383
13384 OO.ui.ProgressBarWidget.static.tagName = 'div';
13385
13386 /* Methods */
13387
13388 /**
13389 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
13390 *
13391 * @return {number|boolean} Progress percent
13392 */
13393 OO.ui.ProgressBarWidget.prototype.getProgress = function () {
13394 return this.progress;
13395 };
13396
13397 /**
13398 * Set the percent of the process completed or `false` for an indeterminate process.
13399 *
13400 * @param {number|boolean} progress Progress percent or `false` for indeterminate
13401 */
13402 OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) {
13403 this.progress = progress;
13404
13405 if ( progress !== false ) {
13406 this.$bar.css( 'width', this.progress + '%' );
13407 this.$element.attr( 'aria-valuenow', this.progress );
13408 } else {
13409 this.$bar.css( 'width', '' );
13410 this.$element.removeAttr( 'aria-valuenow' );
13411 }
13412 this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', !progress );
13413 };
13414
13415 /**
13416 * SearchWidgets combine a {@link OO.ui.TextInputWidget text input field}, where users can type a search query,
13417 * and a {@link OO.ui.TextInputMenuSelectWidget menu} of search results, which is displayed beneath the query
13418 * field. Unlike {@link OO.ui.LookupElement lookup menus}, search result menus are always visible to the user.
13419 * Users can choose an item from the menu or type a query into the text field to search for a matching result item.
13420 * In general, search widgets are used inside a separate {@link OO.ui.Dialog dialog} window.
13421 *
13422 * Each time the query is changed, the search result menu is cleared and repopulated. Please see
13423 * the [OOjs UI demos][1] for an example.
13424 *
13425 * [1]: https://tools.wmflabs.org/oojs-ui/oojs-ui/demos/#dialogs-mediawiki-vector-ltr
13426 *
13427 * @class
13428 * @extends OO.ui.Widget
13429 *
13430 * @constructor
13431 * @param {Object} [config] Configuration options
13432 * @cfg {string|jQuery} [placeholder] Placeholder text for query input
13433 * @cfg {string} [value] Initial query value
13434 */
13435 OO.ui.SearchWidget = function OoUiSearchWidget( config ) {
13436 // Configuration initialization
13437 config = config || {};
13438
13439 // Parent constructor
13440 OO.ui.SearchWidget.super.call( this, config );
13441
13442 // Properties
13443 this.query = new OO.ui.TextInputWidget( {
13444 icon: 'search',
13445 placeholder: config.placeholder,
13446 value: config.value
13447 } );
13448 this.results = new OO.ui.SelectWidget();
13449 this.$query = $( '<div>' );
13450 this.$results = $( '<div>' );
13451
13452 // Events
13453 this.query.connect( this, {
13454 change: 'onQueryChange',
13455 enter: 'onQueryEnter'
13456 } );
13457 this.results.connect( this, {
13458 highlight: 'onResultsHighlight',
13459 select: 'onResultsSelect'
13460 } );
13461 this.query.$input.on( 'keydown', this.onQueryKeydown.bind( this ) );
13462
13463 // Initialization
13464 this.$query
13465 .addClass( 'oo-ui-searchWidget-query' )
13466 .append( this.query.$element );
13467 this.$results
13468 .addClass( 'oo-ui-searchWidget-results' )
13469 .append( this.results.$element );
13470 this.$element
13471 .addClass( 'oo-ui-searchWidget' )
13472 .append( this.$results, this.$query );
13473 };
13474
13475 /* Setup */
13476
13477 OO.inheritClass( OO.ui.SearchWidget, OO.ui.Widget );
13478
13479 /* Events */
13480
13481 /**
13482 * A 'highlight' event is emitted when an item is highlighted. The highlight indicates which
13483 * item will be selected. When a user mouses over a menu item, it is highlighted. If a search
13484 * string is typed into the query field instead, the first menu item that matches the query
13485 * will be highlighted.
13486
13487 * @event highlight
13488 * @param {Object|null} item Item data or null if no item is highlighted
13489 */
13490
13491 /**
13492 * A 'select' event is emitted when an item is selected. A menu item is selected when it is clicked,
13493 * or when a user types a search query, a menu result is highlighted, and the user presses enter.
13494 *
13495 * @event select
13496 * @param {Object|null} item Item data or null if no item is selected
13497 */
13498
13499 /* Methods */
13500
13501 /**
13502 * Handle query key down events.
13503 *
13504 * @private
13505 * @param {jQuery.Event} e Key down event
13506 */
13507 OO.ui.SearchWidget.prototype.onQueryKeydown = function ( e ) {
13508 var highlightedItem, nextItem,
13509 dir = e.which === OO.ui.Keys.DOWN ? 1 : ( e.which === OO.ui.Keys.UP ? -1 : 0 );
13510
13511 if ( dir ) {
13512 highlightedItem = this.results.getHighlightedItem();
13513 if ( !highlightedItem ) {
13514 highlightedItem = this.results.getSelectedItem();
13515 }
13516 nextItem = this.results.getRelativeSelectableItem( highlightedItem, dir );
13517 this.results.highlightItem( nextItem );
13518 nextItem.scrollElementIntoView();
13519 }
13520 };
13521
13522 /**
13523 * Handle select widget select events.
13524 *
13525 * Clears existing results. Subclasses should repopulate items according to new query.
13526 *
13527 * @private
13528 * @param {string} value New value
13529 */
13530 OO.ui.SearchWidget.prototype.onQueryChange = function () {
13531 // Reset
13532 this.results.clearItems();
13533 };
13534
13535 /**
13536 * Handle select widget enter key events.
13537 *
13538 * Selects highlighted item.
13539 *
13540 * @private
13541 * @param {string} value New value
13542 */
13543 OO.ui.SearchWidget.prototype.onQueryEnter = function () {
13544 // Reset
13545 this.results.selectItem( this.results.getHighlightedItem() );
13546 };
13547
13548 /**
13549 * Handle select widget highlight events.
13550 *
13551 * @private
13552 * @param {OO.ui.OptionWidget} item Highlighted item
13553 * @fires highlight
13554 */
13555 OO.ui.SearchWidget.prototype.onResultsHighlight = function ( item ) {
13556 this.emit( 'highlight', item ? item.getData() : null );
13557 };
13558
13559 /**
13560 * Handle select widget select events.
13561 *
13562 * @private
13563 * @param {OO.ui.OptionWidget} item Selected item
13564 * @fires select
13565 */
13566 OO.ui.SearchWidget.prototype.onResultsSelect = function ( item ) {
13567 this.emit( 'select', item ? item.getData() : null );
13568 };
13569
13570 /**
13571 * Get the query input.
13572 *
13573 * @return {OO.ui.TextInputWidget} Query input
13574 */
13575 OO.ui.SearchWidget.prototype.getQuery = function () {
13576 return this.query;
13577 };
13578
13579 /**
13580 * Get the search results menu.
13581 *
13582 * @return {OO.ui.SelectWidget} Menu of search results
13583 */
13584 OO.ui.SearchWidget.prototype.getResults = function () {
13585 return this.results;
13586 };
13587
13588 /**
13589 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
13590 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
13591 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
13592 * menu selects}.
13593 *
13594 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
13595 * information, please see the [OOjs UI documentation on MediaWiki][1].
13596 *
13597 * @example
13598 * // Example of a select widget with three options
13599 * var select = new OO.ui.SelectWidget( {
13600 * items: [
13601 * new OO.ui.OptionWidget( {
13602 * data: 'a',
13603 * label: 'Option One',
13604 * } ),
13605 * new OO.ui.OptionWidget( {
13606 * data: 'b',
13607 * label: 'Option Two',
13608 * } ),
13609 * new OO.ui.OptionWidget( {
13610 * data: 'c',
13611 * label: 'Option Three',
13612 * } )
13613 * ]
13614 * } );
13615 * $( 'body' ).append( select.$element );
13616 *
13617 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13618 *
13619 * @class
13620 * @extends OO.ui.Widget
13621 * @mixins OO.ui.GroupElement
13622 *
13623 * @constructor
13624 * @param {Object} [config] Configuration options
13625 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
13626 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
13627 * the [OOjs UI documentation on MediaWiki] [2] for examples.
13628 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
13629 */
13630 OO.ui.SelectWidget = function OoUiSelectWidget( config ) {
13631 // Configuration initialization
13632 config = config || {};
13633
13634 // Parent constructor
13635 OO.ui.SelectWidget.super.call( this, config );
13636
13637 // Mixin constructors
13638 OO.ui.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) );
13639
13640 // Properties
13641 this.pressed = false;
13642 this.selecting = null;
13643 this.onMouseUpHandler = this.onMouseUp.bind( this );
13644 this.onMouseMoveHandler = this.onMouseMove.bind( this );
13645 this.onKeyDownHandler = this.onKeyDown.bind( this );
13646
13647 // Events
13648 this.$element.on( {
13649 mousedown: this.onMouseDown.bind( this ),
13650 mouseover: this.onMouseOver.bind( this ),
13651 mouseleave: this.onMouseLeave.bind( this )
13652 } );
13653
13654 // Initialization
13655 this.$element
13656 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
13657 .attr( 'role', 'listbox' );
13658 if ( Array.isArray( config.items ) ) {
13659 this.addItems( config.items );
13660 }
13661 };
13662
13663 /* Setup */
13664
13665 OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget );
13666
13667 // Need to mixin base class as well
13668 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupElement );
13669 OO.mixinClass( OO.ui.SelectWidget, OO.ui.GroupWidget );
13670
13671 /* Events */
13672
13673 /**
13674 * @event highlight
13675 *
13676 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
13677 *
13678 * @param {OO.ui.OptionWidget|null} item Highlighted item
13679 */
13680
13681 /**
13682 * @event press
13683 *
13684 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
13685 * pressed state of an option.
13686 *
13687 * @param {OO.ui.OptionWidget|null} item Pressed item
13688 */
13689
13690 /**
13691 * @event select
13692 *
13693 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
13694 *
13695 * @param {OO.ui.OptionWidget|null} item Selected item
13696 */
13697
13698 /**
13699 * @event choose
13700 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
13701 * @param {OO.ui.OptionWidget|null} item Chosen item
13702 */
13703
13704 /**
13705 * @event add
13706 *
13707 * An `add` event is emitted when options are added to the select with the #addItems method.
13708 *
13709 * @param {OO.ui.OptionWidget[]} items Added items
13710 * @param {number} index Index of insertion point
13711 */
13712
13713 /**
13714 * @event remove
13715 *
13716 * A `remove` event is emitted when options are removed from the select with the #clearItems
13717 * or #removeItems methods.
13718 *
13719 * @param {OO.ui.OptionWidget[]} items Removed items
13720 */
13721
13722 /* Methods */
13723
13724 /**
13725 * Handle mouse down events.
13726 *
13727 * @private
13728 * @param {jQuery.Event} e Mouse down event
13729 */
13730 OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) {
13731 var item;
13732
13733 if ( !this.isDisabled() && e.which === 1 ) {
13734 this.togglePressed( true );
13735 item = this.getTargetItem( e );
13736 if ( item && item.isSelectable() ) {
13737 this.pressItem( item );
13738 this.selecting = item;
13739 this.getElementDocument().addEventListener(
13740 'mouseup',
13741 this.onMouseUpHandler,
13742 true
13743 );
13744 this.getElementDocument().addEventListener(
13745 'mousemove',
13746 this.onMouseMoveHandler,
13747 true
13748 );
13749 }
13750 }
13751 return false;
13752 };
13753
13754 /**
13755 * Handle mouse up events.
13756 *
13757 * @private
13758 * @param {jQuery.Event} e Mouse up event
13759 */
13760 OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) {
13761 var item;
13762
13763 this.togglePressed( false );
13764 if ( !this.selecting ) {
13765 item = this.getTargetItem( e );
13766 if ( item && item.isSelectable() ) {
13767 this.selecting = item;
13768 }
13769 }
13770 if ( !this.isDisabled() && e.which === 1 && this.selecting ) {
13771 this.pressItem( null );
13772 this.chooseItem( this.selecting );
13773 this.selecting = null;
13774 }
13775
13776 this.getElementDocument().removeEventListener(
13777 'mouseup',
13778 this.onMouseUpHandler,
13779 true
13780 );
13781 this.getElementDocument().removeEventListener(
13782 'mousemove',
13783 this.onMouseMoveHandler,
13784 true
13785 );
13786
13787 return false;
13788 };
13789
13790 /**
13791 * Handle mouse move events.
13792 *
13793 * @private
13794 * @param {jQuery.Event} e Mouse move event
13795 */
13796 OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) {
13797 var item;
13798
13799 if ( !this.isDisabled() && this.pressed ) {
13800 item = this.getTargetItem( e );
13801 if ( item && item !== this.selecting && item.isSelectable() ) {
13802 this.pressItem( item );
13803 this.selecting = item;
13804 }
13805 }
13806 return false;
13807 };
13808
13809 /**
13810 * Handle mouse over events.
13811 *
13812 * @private
13813 * @param {jQuery.Event} e Mouse over event
13814 */
13815 OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) {
13816 var item;
13817
13818 if ( !this.isDisabled() ) {
13819 item = this.getTargetItem( e );
13820 this.highlightItem( item && item.isHighlightable() ? item : null );
13821 }
13822 return false;
13823 };
13824
13825 /**
13826 * Handle mouse leave events.
13827 *
13828 * @private
13829 * @param {jQuery.Event} e Mouse over event
13830 */
13831 OO.ui.SelectWidget.prototype.onMouseLeave = function () {
13832 if ( !this.isDisabled() ) {
13833 this.highlightItem( null );
13834 }
13835 return false;
13836 };
13837
13838 /**
13839 * Handle key down events.
13840 *
13841 * @protected
13842 * @param {jQuery.Event} e Key down event
13843 */
13844 OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) {
13845 var nextItem,
13846 handled = false,
13847 currentItem = this.getHighlightedItem() || this.getSelectedItem();
13848
13849 if ( !this.isDisabled() && this.isVisible() ) {
13850 switch ( e.keyCode ) {
13851 case OO.ui.Keys.ENTER:
13852 if ( currentItem && currentItem.constructor.static.highlightable ) {
13853 // Was only highlighted, now let's select it. No-op if already selected.
13854 this.chooseItem( currentItem );
13855 handled = true;
13856 }
13857 break;
13858 case OO.ui.Keys.UP:
13859 case OO.ui.Keys.LEFT:
13860 nextItem = this.getRelativeSelectableItem( currentItem, -1 );
13861 handled = true;
13862 break;
13863 case OO.ui.Keys.DOWN:
13864 case OO.ui.Keys.RIGHT:
13865 nextItem = this.getRelativeSelectableItem( currentItem, 1 );
13866 handled = true;
13867 break;
13868 case OO.ui.Keys.ESCAPE:
13869 case OO.ui.Keys.TAB:
13870 if ( currentItem && currentItem.constructor.static.highlightable ) {
13871 currentItem.setHighlighted( false );
13872 }
13873 this.unbindKeyDownListener();
13874 // Don't prevent tabbing away / defocusing
13875 handled = false;
13876 break;
13877 }
13878
13879 if ( nextItem ) {
13880 if ( nextItem.constructor.static.highlightable ) {
13881 this.highlightItem( nextItem );
13882 } else {
13883 this.chooseItem( nextItem );
13884 }
13885 nextItem.scrollElementIntoView();
13886 }
13887
13888 if ( handled ) {
13889 // Can't just return false, because e is not always a jQuery event
13890 e.preventDefault();
13891 e.stopPropagation();
13892 }
13893 }
13894 };
13895
13896 /**
13897 * Bind key down listener.
13898 *
13899 * @protected
13900 */
13901 OO.ui.SelectWidget.prototype.bindKeyDownListener = function () {
13902 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true );
13903 };
13904
13905 /**
13906 * Unbind key down listener.
13907 *
13908 * @protected
13909 */
13910 OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () {
13911 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true );
13912 };
13913
13914 /**
13915 * Get the closest item to a jQuery.Event.
13916 *
13917 * @private
13918 * @param {jQuery.Event} e
13919 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
13920 */
13921 OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) {
13922 var $item = $( e.target ).closest( '.oo-ui-optionWidget' );
13923 if ( $item.length ) {
13924 return $item.data( 'oo-ui-optionWidget' );
13925 }
13926 return null;
13927 };
13928
13929 /**
13930 * Get selected item.
13931 *
13932 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
13933 */
13934 OO.ui.SelectWidget.prototype.getSelectedItem = function () {
13935 var i, len;
13936
13937 for ( i = 0, len = this.items.length; i < len; i++ ) {
13938 if ( this.items[ i ].isSelected() ) {
13939 return this.items[ i ];
13940 }
13941 }
13942 return null;
13943 };
13944
13945 /**
13946 * Get highlighted item.
13947 *
13948 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
13949 */
13950 OO.ui.SelectWidget.prototype.getHighlightedItem = function () {
13951 var i, len;
13952
13953 for ( i = 0, len = this.items.length; i < len; i++ ) {
13954 if ( this.items[ i ].isHighlighted() ) {
13955 return this.items[ i ];
13956 }
13957 }
13958 return null;
13959 };
13960
13961 /**
13962 * Toggle pressed state.
13963 *
13964 * Press is a state that occurs when a user mouses down on an item, but
13965 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
13966 * until the user releases the mouse.
13967 *
13968 * @param {boolean} pressed An option is being pressed
13969 */
13970 OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) {
13971 if ( pressed === undefined ) {
13972 pressed = !this.pressed;
13973 }
13974 if ( pressed !== this.pressed ) {
13975 this.$element
13976 .toggleClass( 'oo-ui-selectWidget-pressed', pressed )
13977 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed );
13978 this.pressed = pressed;
13979 }
13980 };
13981
13982 /**
13983 * Highlight an option. If the `item` param is omitted, no options will be highlighted
13984 * and any existing highlight will be removed. The highlight is mutually exclusive.
13985 *
13986 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
13987 * @fires highlight
13988 * @chainable
13989 */
13990 OO.ui.SelectWidget.prototype.highlightItem = function ( item ) {
13991 var i, len, highlighted,
13992 changed = false;
13993
13994 for ( i = 0, len = this.items.length; i < len; i++ ) {
13995 highlighted = this.items[ i ] === item;
13996 if ( this.items[ i ].isHighlighted() !== highlighted ) {
13997 this.items[ i ].setHighlighted( highlighted );
13998 changed = true;
13999 }
14000 }
14001 if ( changed ) {
14002 this.emit( 'highlight', item );
14003 }
14004
14005 return this;
14006 };
14007
14008 /**
14009 * Programmatically select an option by its reference. If the `item` parameter is omitted,
14010 * all options will be deselected.
14011 *
14012 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
14013 * @fires select
14014 * @chainable
14015 */
14016 OO.ui.SelectWidget.prototype.selectItem = function ( item ) {
14017 var i, len, selected,
14018 changed = false;
14019
14020 for ( i = 0, len = this.items.length; i < len; i++ ) {
14021 selected = this.items[ i ] === item;
14022 if ( this.items[ i ].isSelected() !== selected ) {
14023 this.items[ i ].setSelected( selected );
14024 changed = true;
14025 }
14026 }
14027 if ( changed ) {
14028 this.emit( 'select', item );
14029 }
14030
14031 return this;
14032 };
14033
14034 /**
14035 * Press an item.
14036 *
14037 * Press is a state that occurs when a user mouses down on an item, but has not
14038 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
14039 * releases the mouse.
14040 *
14041 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
14042 * @fires press
14043 * @chainable
14044 */
14045 OO.ui.SelectWidget.prototype.pressItem = function ( item ) {
14046 var i, len, pressed,
14047 changed = false;
14048
14049 for ( i = 0, len = this.items.length; i < len; i++ ) {
14050 pressed = this.items[ i ] === item;
14051 if ( this.items[ i ].isPressed() !== pressed ) {
14052 this.items[ i ].setPressed( pressed );
14053 changed = true;
14054 }
14055 }
14056 if ( changed ) {
14057 this.emit( 'press', item );
14058 }
14059
14060 return this;
14061 };
14062
14063 /**
14064 * Choose an item.
14065 *
14066 * Note that ‘choose’ should never be modified programmatically. A user can choose
14067 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
14068 * use the #selectItem method.
14069 *
14070 * This method is identical to #selectItem, but may vary in subclasses that take additional action
14071 * when users choose an item with the keyboard or mouse.
14072 *
14073 * @param {OO.ui.OptionWidget} item Item to choose
14074 * @fires choose
14075 * @chainable
14076 */
14077 OO.ui.SelectWidget.prototype.chooseItem = function ( item ) {
14078 this.selectItem( item );
14079 this.emit( 'choose', item );
14080
14081 return this;
14082 };
14083
14084 /**
14085 * Get an option by its position relative to the specified item (or to the start of the option array,
14086 * if item is `null`). The direction in which to search through the option array is specified with a
14087 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
14088 * `null` if there are no options in the array.
14089 *
14090 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
14091 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
14092 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
14093 */
14094 OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction ) {
14095 var currentIndex, nextIndex, i,
14096 increase = direction > 0 ? 1 : -1,
14097 len = this.items.length;
14098
14099 if ( item instanceof OO.ui.OptionWidget ) {
14100 currentIndex = $.inArray( item, this.items );
14101 nextIndex = ( currentIndex + increase + len ) % len;
14102 } else {
14103 // If no item is selected and moving forward, start at the beginning.
14104 // If moving backward, start at the end.
14105 nextIndex = direction > 0 ? 0 : len - 1;
14106 }
14107
14108 for ( i = 0; i < len; i++ ) {
14109 item = this.items[ nextIndex ];
14110 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14111 return item;
14112 }
14113 nextIndex = ( nextIndex + increase + len ) % len;
14114 }
14115 return null;
14116 };
14117
14118 /**
14119 * Get the next selectable item or `null` if there are no selectable items.
14120 * Disabled options and menu-section markers and breaks are not selectable.
14121 *
14122 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
14123 */
14124 OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () {
14125 var i, len, item;
14126
14127 for ( i = 0, len = this.items.length; i < len; i++ ) {
14128 item = this.items[ i ];
14129 if ( item instanceof OO.ui.OptionWidget && item.isSelectable() ) {
14130 return item;
14131 }
14132 }
14133
14134 return null;
14135 };
14136
14137 /**
14138 * Add an array of options to the select. Optionally, an index number can be used to
14139 * specify an insertion point.
14140 *
14141 * @param {OO.ui.OptionWidget[]} items Items to add
14142 * @param {number} [index] Index to insert items after
14143 * @fires add
14144 * @chainable
14145 */
14146 OO.ui.SelectWidget.prototype.addItems = function ( items, index ) {
14147 // Mixin method
14148 OO.ui.GroupWidget.prototype.addItems.call( this, items, index );
14149
14150 // Always provide an index, even if it was omitted
14151 this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index );
14152
14153 return this;
14154 };
14155
14156 /**
14157 * Remove the specified array of options from the select. Options will be detached
14158 * from the DOM, not removed, so they can be reused later. To remove all options from
14159 * the select, you may wish to use the #clearItems method instead.
14160 *
14161 * @param {OO.ui.OptionWidget[]} items Items to remove
14162 * @fires remove
14163 * @chainable
14164 */
14165 OO.ui.SelectWidget.prototype.removeItems = function ( items ) {
14166 var i, len, item;
14167
14168 // Deselect items being removed
14169 for ( i = 0, len = items.length; i < len; i++ ) {
14170 item = items[ i ];
14171 if ( item.isSelected() ) {
14172 this.selectItem( null );
14173 }
14174 }
14175
14176 // Mixin method
14177 OO.ui.GroupWidget.prototype.removeItems.call( this, items );
14178
14179 this.emit( 'remove', items );
14180
14181 return this;
14182 };
14183
14184 /**
14185 * Clear all options from the select. Options will be detached from the DOM, not removed,
14186 * so that they can be reused later. To remove a subset of options from the select, use
14187 * the #removeItems method.
14188 *
14189 * @fires remove
14190 * @chainable
14191 */
14192 OO.ui.SelectWidget.prototype.clearItems = function () {
14193 var items = this.items.slice();
14194
14195 // Mixin method
14196 OO.ui.GroupWidget.prototype.clearItems.call( this );
14197
14198 // Clear selection
14199 this.selectItem( null );
14200
14201 this.emit( 'remove', items );
14202
14203 return this;
14204 };
14205
14206 /**
14207 * ButtonSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains
14208 * button options and is used together with
14209 * OO.ui.ButtonOptionWidget. The ButtonSelectWidget provides an interface for
14210 * highlighting, choosing, and selecting mutually exclusive options. Please see
14211 * the [OOjs UI documentation on MediaWiki] [1] for more information.
14212 *
14213 * @example
14214 * // Example: A ButtonSelectWidget that contains three ButtonOptionWidgets
14215 * var option1 = new OO.ui.ButtonOptionWidget( {
14216 * data: 1,
14217 * label: 'Option 1',
14218 * title: 'Button option 1'
14219 * } );
14220 *
14221 * var option2 = new OO.ui.ButtonOptionWidget( {
14222 * data: 2,
14223 * label: 'Option 2',
14224 * title: 'Button option 2'
14225 * } );
14226 *
14227 * var option3 = new OO.ui.ButtonOptionWidget( {
14228 * data: 3,
14229 * label: 'Option 3',
14230 * title: 'Button option 3'
14231 * } );
14232 *
14233 * var buttonSelect=new OO.ui.ButtonSelectWidget( {
14234 * items: [ option1, option2, option3 ]
14235 * } );
14236 * $( 'body' ).append( buttonSelect.$element );
14237 *
14238 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14239 *
14240 * @class
14241 * @extends OO.ui.SelectWidget
14242 * @mixins OO.ui.TabIndexedElement
14243 *
14244 * @constructor
14245 * @param {Object} [config] Configuration options
14246 */
14247 OO.ui.ButtonSelectWidget = function OoUiButtonSelectWidget( config ) {
14248 // Parent constructor
14249 OO.ui.ButtonSelectWidget.super.call( this, config );
14250
14251 // Mixin constructors
14252 OO.ui.TabIndexedElement.call( this, config );
14253
14254 // Events
14255 this.$element.on( {
14256 focus: this.bindKeyDownListener.bind( this ),
14257 blur: this.unbindKeyDownListener.bind( this )
14258 } );
14259
14260 // Initialization
14261 this.$element.addClass( 'oo-ui-buttonSelectWidget' );
14262 };
14263
14264 /* Setup */
14265
14266 OO.inheritClass( OO.ui.ButtonSelectWidget, OO.ui.SelectWidget );
14267 OO.mixinClass( OO.ui.ButtonSelectWidget, OO.ui.TabIndexedElement );
14268
14269 /**
14270 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
14271 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
14272 * an interface for adding, removing and selecting options.
14273 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14274 *
14275 * @example
14276 * // A RadioSelectWidget with RadioOptions.
14277 * var option1 = new OO.ui.RadioOptionWidget( {
14278 * data: 'a',
14279 * label: 'Selected radio option'
14280 * } );
14281 *
14282 * var option2 = new OO.ui.RadioOptionWidget( {
14283 * data: 'b',
14284 * label: 'Unselected radio option'
14285 * } );
14286 *
14287 * var radioSelect=new OO.ui.RadioSelectWidget( {
14288 * items: [ option1, option2 ]
14289 * } );
14290 *
14291 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
14292 * radioSelect.selectItem( option1 );
14293 *
14294 * $( 'body' ).append( radioSelect.$element );
14295 *
14296 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14297
14298 *
14299 * @class
14300 * @extends OO.ui.SelectWidget
14301 * @mixins OO.ui.TabIndexedElement
14302 *
14303 * @constructor
14304 * @param {Object} [config] Configuration options
14305 */
14306 OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) {
14307 // Parent constructor
14308 OO.ui.RadioSelectWidget.super.call( this, config );
14309
14310 // Mixin constructors
14311 OO.ui.TabIndexedElement.call( this, config );
14312
14313 // Events
14314 this.$element.on( {
14315 focus: this.bindKeyDownListener.bind( this ),
14316 blur: this.unbindKeyDownListener.bind( this )
14317 } );
14318
14319 // Initialization
14320 this.$element.addClass( 'oo-ui-radioSelectWidget' );
14321 };
14322
14323 /* Setup */
14324
14325 OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget );
14326 OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.TabIndexedElement );
14327
14328 /**
14329 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
14330 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
14331 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxWidget ComboBoxWidget},
14332 * and {@link OO.ui.LookupElement LookupElement} for examples of widgets that contain menus.
14333 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
14334 * and customized to be opened, closed, and displayed as needed.
14335 *
14336 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
14337 * mouse outside the menu.
14338 *
14339 * Menus also have support for keyboard interaction:
14340 *
14341 * - Enter/Return key: choose and select a menu option
14342 * - Up-arrow key: highlight the previous menu option
14343 * - Down-arrow key: highlight the next menu option
14344 * - Esc key: hide the menu
14345 *
14346 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
14347 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
14348 *
14349 * @class
14350 * @extends OO.ui.SelectWidget
14351 * @mixins OO.ui.ClippableElement
14352 *
14353 * @constructor
14354 * @param {Object} [config] Configuration options
14355 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
14356 * the text the user types. This config is used by {@link OO.ui.ComboBoxWidget ComboBoxWidget}
14357 * and {@link OO.ui.LookupElement LookupElement}
14358 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu’s active state. If the user clicks the mouse
14359 * anywhere on the page outside of this widget, the menu is hidden.
14360 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
14361 */
14362 OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) {
14363 // Configuration initialization
14364 config = config || {};
14365
14366 // Parent constructor
14367 OO.ui.MenuSelectWidget.super.call( this, config );
14368
14369 // Mixin constructors
14370 OO.ui.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) );
14371
14372 // Properties
14373 this.newItems = null;
14374 this.autoHide = config.autoHide === undefined || !!config.autoHide;
14375 this.$input = config.input ? config.input.$input : null;
14376 this.$widget = config.widget ? config.widget.$element : null;
14377 this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this );
14378
14379 // Initialization
14380 this.$element
14381 .addClass( 'oo-ui-menuSelectWidget' )
14382 .attr( 'role', 'menu' );
14383
14384 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
14385 // that reference properties not initialized at that time of parent class construction
14386 // TODO: Find a better way to handle post-constructor setup
14387 this.visible = false;
14388 this.$element.addClass( 'oo-ui-element-hidden' );
14389 };
14390
14391 /* Setup */
14392
14393 OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget );
14394 OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.ClippableElement );
14395
14396 /* Methods */
14397
14398 /**
14399 * Handles document mouse down events.
14400 *
14401 * @protected
14402 * @param {jQuery.Event} e Key down event
14403 */
14404 OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) {
14405 if (
14406 !OO.ui.contains( this.$element[ 0 ], e.target, true ) &&
14407 ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) )
14408 ) {
14409 this.toggle( false );
14410 }
14411 };
14412
14413 /**
14414 * @inheritdoc
14415 */
14416 OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) {
14417 var currentItem = this.getHighlightedItem() || this.getSelectedItem();
14418
14419 if ( !this.isDisabled() && this.isVisible() ) {
14420 switch ( e.keyCode ) {
14421 case OO.ui.Keys.LEFT:
14422 case OO.ui.Keys.RIGHT:
14423 // Do nothing if a text field is associated, arrow keys will be handled natively
14424 if ( !this.$input ) {
14425 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14426 }
14427 break;
14428 case OO.ui.Keys.ESCAPE:
14429 case OO.ui.Keys.TAB:
14430 if ( currentItem ) {
14431 currentItem.setHighlighted( false );
14432 }
14433 this.toggle( false );
14434 // Don't prevent tabbing away, prevent defocusing
14435 if ( e.keyCode === OO.ui.Keys.ESCAPE ) {
14436 e.preventDefault();
14437 e.stopPropagation();
14438 }
14439 break;
14440 default:
14441 OO.ui.MenuSelectWidget.super.prototype.onKeyDown.call( this, e );
14442 return;
14443 }
14444 }
14445 };
14446
14447 /**
14448 * @inheritdoc
14449 */
14450 OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () {
14451 if ( this.$input ) {
14452 this.$input.on( 'keydown', this.onKeyDownHandler );
14453 } else {
14454 OO.ui.MenuSelectWidget.super.prototype.bindKeyDownListener.call( this );
14455 }
14456 };
14457
14458 /**
14459 * @inheritdoc
14460 */
14461 OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () {
14462 if ( this.$input ) {
14463 this.$input.off( 'keydown', this.onKeyDownHandler );
14464 } else {
14465 OO.ui.MenuSelectWidget.super.prototype.unbindKeyDownListener.call( this );
14466 }
14467 };
14468
14469 /**
14470 * Choose an item.
14471 *
14472 * When a user chooses an item, the menu is closed.
14473 *
14474 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
14475 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
14476 * @param {OO.ui.OptionWidget} item Item to choose
14477 * @chainable
14478 */
14479 OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) {
14480 OO.ui.MenuSelectWidget.super.prototype.chooseItem.call( this, item );
14481 this.toggle( false );
14482 return this;
14483 };
14484
14485 /**
14486 * @inheritdoc
14487 */
14488 OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) {
14489 var i, len, item;
14490
14491 // Parent method
14492 OO.ui.MenuSelectWidget.super.prototype.addItems.call( this, items, index );
14493
14494 // Auto-initialize
14495 if ( !this.newItems ) {
14496 this.newItems = [];
14497 }
14498
14499 for ( i = 0, len = items.length; i < len; i++ ) {
14500 item = items[ i ];
14501 if ( this.isVisible() ) {
14502 // Defer fitting label until item has been attached
14503 item.fitLabel();
14504 } else {
14505 this.newItems.push( item );
14506 }
14507 }
14508
14509 // Reevaluate clipping
14510 this.clip();
14511
14512 return this;
14513 };
14514
14515 /**
14516 * @inheritdoc
14517 */
14518 OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) {
14519 // Parent method
14520 OO.ui.MenuSelectWidget.super.prototype.removeItems.call( this, items );
14521
14522 // Reevaluate clipping
14523 this.clip();
14524
14525 return this;
14526 };
14527
14528 /**
14529 * @inheritdoc
14530 */
14531 OO.ui.MenuSelectWidget.prototype.clearItems = function () {
14532 // Parent method
14533 OO.ui.MenuSelectWidget.super.prototype.clearItems.call( this );
14534
14535 // Reevaluate clipping
14536 this.clip();
14537
14538 return this;
14539 };
14540
14541 /**
14542 * @inheritdoc
14543 */
14544 OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) {
14545 visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length;
14546
14547 var i, len,
14548 change = visible !== this.isVisible();
14549
14550 // Parent method
14551 OO.ui.MenuSelectWidget.super.prototype.toggle.call( this, visible );
14552
14553 if ( change ) {
14554 if ( visible ) {
14555 this.bindKeyDownListener();
14556
14557 if ( this.newItems && this.newItems.length ) {
14558 for ( i = 0, len = this.newItems.length; i < len; i++ ) {
14559 this.newItems[ i ].fitLabel();
14560 }
14561 this.newItems = null;
14562 }
14563 this.toggleClipping( true );
14564
14565 // Auto-hide
14566 if ( this.autoHide ) {
14567 this.getElementDocument().addEventListener(
14568 'mousedown', this.onDocumentMouseDownHandler, true
14569 );
14570 }
14571 } else {
14572 this.unbindKeyDownListener();
14573 this.getElementDocument().removeEventListener(
14574 'mousedown', this.onDocumentMouseDownHandler, true
14575 );
14576 this.toggleClipping( false );
14577 }
14578 }
14579
14580 return this;
14581 };
14582
14583 /**
14584 * TextInputMenuSelectWidget is a menu that is specially designed to be positioned beneath
14585 * a {@link OO.ui.TextInputWidget text input} field. The menu's position is automatically
14586 * calculated and maintained when the menu is toggled or the window is resized.
14587 * See OO.ui.ComboBoxWidget for an example of a widget that uses this class.
14588 *
14589 * @class
14590 * @extends OO.ui.MenuSelectWidget
14591 *
14592 * @constructor
14593 * @param {OO.ui.TextInputWidget} inputWidget Text input widget to provide menu for
14594 * @param {Object} [config] Configuration options
14595 * @cfg {jQuery} [$container=input.$element] Element to render menu under
14596 */
14597 OO.ui.TextInputMenuSelectWidget = function OoUiTextInputMenuSelectWidget( inputWidget, config ) {
14598 // Allow passing positional parameters inside the config object
14599 if ( OO.isPlainObject( inputWidget ) && config === undefined ) {
14600 config = inputWidget;
14601 inputWidget = config.inputWidget;
14602 }
14603
14604 // Configuration initialization
14605 config = config || {};
14606
14607 // Parent constructor
14608 OO.ui.TextInputMenuSelectWidget.super.call( this, config );
14609
14610 // Properties
14611 this.inputWidget = inputWidget;
14612 this.$container = config.$container || this.inputWidget.$element;
14613 this.onWindowResizeHandler = this.onWindowResize.bind( this );
14614
14615 // Initialization
14616 this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' );
14617 };
14618
14619 /* Setup */
14620
14621 OO.inheritClass( OO.ui.TextInputMenuSelectWidget, OO.ui.MenuSelectWidget );
14622
14623 /* Methods */
14624
14625 /**
14626 * Handle window resize event.
14627 *
14628 * @private
14629 * @param {jQuery.Event} e Window resize event
14630 */
14631 OO.ui.TextInputMenuSelectWidget.prototype.onWindowResize = function () {
14632 this.position();
14633 };
14634
14635 /**
14636 * @inheritdoc
14637 */
14638 OO.ui.TextInputMenuSelectWidget.prototype.toggle = function ( visible ) {
14639 visible = visible === undefined ? !this.isVisible() : !!visible;
14640
14641 var change = visible !== this.isVisible();
14642
14643 if ( change && visible ) {
14644 // Make sure the width is set before the parent method runs.
14645 // After this we have to call this.position(); again to actually
14646 // position ourselves correctly.
14647 this.position();
14648 }
14649
14650 // Parent method
14651 OO.ui.TextInputMenuSelectWidget.super.prototype.toggle.call( this, visible );
14652
14653 if ( change ) {
14654 if ( this.isVisible() ) {
14655 this.position();
14656 $( this.getElementWindow() ).on( 'resize', this.onWindowResizeHandler );
14657 } else {
14658 $( this.getElementWindow() ).off( 'resize', this.onWindowResizeHandler );
14659 }
14660 }
14661
14662 return this;
14663 };
14664
14665 /**
14666 * Position the menu.
14667 *
14668 * @private
14669 * @chainable
14670 */
14671 OO.ui.TextInputMenuSelectWidget.prototype.position = function () {
14672 var $container = this.$container,
14673 pos = OO.ui.Element.static.getRelativePosition( $container, this.$element.offsetParent() );
14674
14675 // Position under input
14676 pos.top += $container.height();
14677 this.$element.css( pos );
14678
14679 // Set width
14680 this.setIdealSize( $container.width() );
14681 // We updated the position, so re-evaluate the clipping state
14682 this.clip();
14683
14684 return this;
14685 };
14686
14687 /**
14688 * OutlineSelectWidget is a structured list that contains {@link OO.ui.OutlineOptionWidget outline options}
14689 * A set of controls can be provided with an {@link OO.ui.OutlineControlsWidget outline controls} widget.
14690 *
14691 * ####Currently, this class is only used by {@link OO.ui.BookletLayout BookletLayouts}.####
14692 *
14693 * @class
14694 * @extends OO.ui.SelectWidget
14695 * @mixins OO.ui.TabIndexedElement
14696 *
14697 * @constructor
14698 * @param {Object} [config] Configuration options
14699 */
14700 OO.ui.OutlineSelectWidget = function OoUiOutlineSelectWidget( config ) {
14701 // Parent constructor
14702 OO.ui.OutlineSelectWidget.super.call( this, config );
14703
14704 // Mixin constructors
14705 OO.ui.TabIndexedElement.call( this, config );
14706
14707 // Events
14708 this.$element.on( {
14709 focus: this.bindKeyDownListener.bind( this ),
14710 blur: this.unbindKeyDownListener.bind( this )
14711 } );
14712
14713 // Initialization
14714 this.$element.addClass( 'oo-ui-outlineSelectWidget' );
14715 };
14716
14717 /* Setup */
14718
14719 OO.inheritClass( OO.ui.OutlineSelectWidget, OO.ui.SelectWidget );
14720 OO.mixinClass( OO.ui.OutlineSelectWidget, OO.ui.TabIndexedElement );
14721
14722 /**
14723 * ToggleSwitches are switches that slide on and off. Their state is represented by a Boolean
14724 * value (`true` for ‘on’, and `false` otherwise, the default). The ‘off’ state is represented
14725 * visually by a slider in the leftmost position.
14726 *
14727 * @example
14728 * // Toggle switches in the 'off' and 'on' position.
14729 * var toggleSwitch1 = new OO.ui.ToggleSwitchWidget();
14730 * var toggleSwitch2 = new OO.ui.ToggleSwitchWidget( {
14731 * value: true
14732 * } );
14733 *
14734 * // Create a FieldsetLayout to layout and label switches
14735 * var fieldset = new OO.ui.FieldsetLayout( {
14736 * label: 'Toggle switches'
14737 * } );
14738 * fieldset.addItems( [
14739 * new OO.ui.FieldLayout( toggleSwitch1, { label: 'Off', align: 'top' } ),
14740 * new OO.ui.FieldLayout( toggleSwitch2, { label: 'On', align: 'top' } )
14741 * ] );
14742 * $( 'body' ).append( fieldset.$element );
14743 *
14744 * @class
14745 * @extends OO.ui.Widget
14746 * @mixins OO.ui.ToggleWidget
14747 * @mixins OO.ui.TabIndexedElement
14748 *
14749 * @constructor
14750 * @param {Object} [config] Configuration options
14751 * @cfg {boolean} [value=false] The toggle switch’s initial on/off state.
14752 * By default, the toggle switch is in the 'off' position.
14753 */
14754 OO.ui.ToggleSwitchWidget = function OoUiToggleSwitchWidget( config ) {
14755 // Parent constructor
14756 OO.ui.ToggleSwitchWidget.super.call( this, config );
14757
14758 // Mixin constructors
14759 OO.ui.ToggleWidget.call( this, config );
14760 OO.ui.TabIndexedElement.call( this, config );
14761
14762 // Properties
14763 this.dragging = false;
14764 this.dragStart = null;
14765 this.sliding = false;
14766 this.$glow = $( '<span>' );
14767 this.$grip = $( '<span>' );
14768
14769 // Events
14770 this.$element.on( {
14771 click: this.onClick.bind( this ),
14772 keypress: this.onKeyPress.bind( this )
14773 } );
14774
14775 // Initialization
14776 this.$glow.addClass( 'oo-ui-toggleSwitchWidget-glow' );
14777 this.$grip.addClass( 'oo-ui-toggleSwitchWidget-grip' );
14778 this.$element
14779 .addClass( 'oo-ui-toggleSwitchWidget' )
14780 .attr( 'role', 'checkbox' )
14781 .append( this.$glow, this.$grip );
14782 };
14783
14784 /* Setup */
14785
14786 OO.inheritClass( OO.ui.ToggleSwitchWidget, OO.ui.Widget );
14787 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.ToggleWidget );
14788 OO.mixinClass( OO.ui.ToggleSwitchWidget, OO.ui.TabIndexedElement );
14789
14790 /* Methods */
14791
14792 /**
14793 * Handle mouse click events.
14794 *
14795 * @private
14796 * @param {jQuery.Event} e Mouse click event
14797 */
14798 OO.ui.ToggleSwitchWidget.prototype.onClick = function ( e ) {
14799 if ( !this.isDisabled() && e.which === 1 ) {
14800 this.setValue( !this.value );
14801 }
14802 return false;
14803 };
14804
14805 /**
14806 * Handle key press events.
14807 *
14808 * @private
14809 * @param {jQuery.Event} e Key press event
14810 */
14811 OO.ui.ToggleSwitchWidget.prototype.onKeyPress = function ( e ) {
14812 if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) {
14813 this.setValue( !this.value );
14814 return false;
14815 }
14816 };
14817
14818 }( OO ) );