Debian Codegraph @

extensions/VisualEditor/lib/ve/src/init/ve.init.Target.js

raw symbols SCIP
1 /*!
2 * VisualEditor Initialization Target class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Generic Initialization target.
9 *
10 * @class
11 * @abstract
12 * @extends OO.ui.Element
13 * @mixes OO.EventEmitter
14 *
15 * @constructor
16 * @param {Object} [config] Configuration options
17 * @param {Object} [config.toolbarConfig={}] Configuration options for the toolbar
18 * @param {Object} [config.toolbarGroups] Toolbar groups, defaults to this.constructor.static.toolbarGroups
19 * @param {Object} [config.actionGroups] Toolbar groups, defaults to this.constructor.static.actionGroups
20 * @param {string[]} [config.modes] Available editing modes. Defaults to static.modes
21 * @param {string} [config.defaultMode] Default mode for new surfaces. Must be in this.modes and defaults to first item.
22 * @param {boolean} [register=true] Register the target at ve.init.target
23 */
24 ve.init.Target = function VeInitTarget( config ) {
25 config = config || {};
26
27 // Parent constructor
28 ve.init.Target.super.call( this, config );
29
30 // Mixin constructors
31 OO.EventEmitter.call( this );
32
33 // Register
34 if ( config.register !== false ) {
35 ve.init.target = this;
36 }
37
38 // Properties
39 this.surfaces = [];
40 this.surface = null;
41 this.toolbar = null;
42 this.toolbarConfig = config.toolbarConfig || {};
43 this.toolbarGroups = config.toolbarGroups || this.constructor.static.toolbarGroups;
44 this.actionGroups = config.actionGroups || this.constructor.static.actionGroups;
45 this.$scrollContainer = this.getScrollContainer();
46 this.$scrollListener = this.$scrollContainer.is( 'html, body' ) ?
47 $( OO.ui.Element.static.getWindow( this.$scrollContainer[ 0 ] ) ) :
48 this.$scrollContainer;
49
50 this.toolbarScrollOffset = 0;
51 this.activeToolbars = 0;
52 this.wasSurfaceActive = null;
53 this.teardownPromise = null;
54
55 this.modes = config.modes || this.constructor.static.modes;
56 this.setDefaultMode( config.defaultMode );
57
58 this.setupTriggerListeners();
59
60 // Initialization
61 this.$element.addClass( 've-init-target' );
62
63 if ( ve.init.platform.constructor.static.isIos() ) {
64 this.$element.addClass( 've-init-target-ios' );
65 }
66
67 // Events
68 this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this );
69 this.onDocumentKeyUpHandler = this.onDocumentKeyUp.bind( this );
70 this.onDocumentVisibilityChangeHandler = this.onDocumentVisibilityChange.bind( this );
71 this.onTargetKeyDownHandler = this.onTargetKeyDown.bind( this );
72 this.onContainerScrollHandler = this.onContainerScroll.bind( this );
73 this.bindHandlers();
74 };
75
76 /* Inheritance */
77
78 OO.inheritClass( ve.init.Target, OO.ui.Element );
79
80 OO.mixinClass( ve.init.Target, OO.EventEmitter );
81
82 /* Events */
83
84 /**
85 * Must be fired after the surface is initialized
86 *
87 * @event ve.init.Target#surfaceReady
88 */
89
90 /* Static Properties */
91
92 /**
93 * Editing modes available in the target.
94 *
95 * Must contain at least one mode. Overridden if the #modes config option is used.
96 *
97 * @static
98 * @property {string[]}
99 * @inheritable
100 */
101 ve.init.Target.static.modes = [ 'visual' ];
102
103 /**
104 * Toolbar definition, passed to ve.ui.Toolbar#setup
105 *
106 * @static
107 * @property {Array}
108 * @inheritable
109 */
110 ve.init.Target.static.toolbarGroups = [
111 {
112 name: 'history',
113 include: [ { group: 'history' } ]
114 },
115 {
116 name: 'format',
117 header: OO.ui.deferMsg( 'visualeditor-toolbar-paragraph-format' ),
118 title: OO.ui.deferMsg( 'visualeditor-toolbar-format-tooltip' ),
119 type: 'menu',
120 include: [ { group: 'format' } ],
121 promote: [ 'paragraph' ],
122 demote: [ 'preformatted', 'blockquote' ]
123 },
124 {
125 name: 'style',
126 include: [ 'bold', 'italic', 'moreTextStyle' ]
127 },
128 {
129 name: 'link',
130 include: [ 'link' ]
131 },
132 {
133 name: 'structure',
134 header: OO.ui.deferMsg( 'visualeditor-toolbar-structure' ),
135 title: OO.ui.deferMsg( 'visualeditor-toolbar-structure' ),
136 label: OO.ui.deferMsg( 'visualeditor-toolbar-structure' ),
137 invisibleLabel: true,
138 type: 'list',
139 icon: 'listBullet',
140 include: [ { group: 'structure' } ],
141 demote: [ 'outdent', 'indent' ]
142 },
143 {
144 name: 'insert',
145 header: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ),
146 title: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ),
147 label: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ),
148 invisibleLabel: true,
149 type: 'list',
150 icon: 'add',
151 include: '*'
152 },
153 {
154 name: 'specialCharacter',
155 include: [ 'specialCharacter' ]
156 },
157 {
158 name: 'pageMenu',
159 type: 'list',
160 align: 'after',
161 icon: 'menu',
162 indicator: null,
163 header: OO.ui.deferMsg( 'visualeditor-pagemenu-tooltip' ),
164 title: OO.ui.deferMsg( 'visualeditor-pagemenu-tooltip' ),
165 label: OO.ui.deferMsg( 'visualeditor-pagemenu-tooltip' ),
166 invisibleLabel: true,
167 include: [ { group: 'utility' }, { group: 'help' } ]
168 }
169 // ve-mw puts help in a separate group and so uses the
170 // visualeditor-help-tool message.
171 // TODO: Consider downstreaming this message.
172 ];
173
174 /**
175 * Toolbar definition for the actions side of the toolbar
176 *
177 * @deprecated Use align:'after' in the regular toolbarGroups instead.
178 * @static
179 * @property {Array}
180 * @inheritable
181 */
182 ve.init.Target.static.actionGroups = [];
183
184 /**
185 * List of commands which can be triggered anywhere from within the document
186 *
187 * @type {string[]}
188 */
189 ve.init.Target.static.documentCommands = [];
190
191 /**
192 * List of commands which can be triggered from within the target element
193 *
194 * @type {string[]}
195 */
196 ve.init.Target.static.targetCommands = [ 'commandHelp', 'findAndReplace', 'findNext', 'findPrevious' ];
197
198 /**
199 * List of commands to include in the target
200 *
201 * Null means all commands in the registry are used (excluding excludeCommands)
202 *
203 * @type {string[]|null}
204 */
205 ve.init.Target.static.includeCommands = null;
206
207 /**
208 * List of commands to exclude from the target entirely
209 *
210 * @type {string[]}
211 */
212 ve.init.Target.static.excludeCommands = [];
213
214 /**
215 * Surface import rules
216 *
217 * One set for external (non-VE) paste sources and one for all paste sources.
218 *
219 * Most rules are handled in ve.dm.ElementLinearData#sanitize, but htmlBlacklist
220 * is handled in ve.ce.Surface#afterPaste.
221 *
222 * @type {Object}
223 */
224 ve.init.Target.static.importRules = {
225 external: {
226 blacklist: {
227 // Annotations
228 // TODO: This also removes harmless things like <span style="font-weight: bold;">
229 // which would otherwise get converted to a bold annotation
230 'textStyle/span': true,
231 'textStyle/font': true,
232 // Nodes
233 alienInline: true,
234 alienBlock: true,
235 alienTableCell: true,
236 comment: true,
237 div: true
238 },
239 // Selectors to filter. Runs before model type blacklist above.
240 htmlBlacklist: {
241 // remove: { '.selectorToRemove': true }
242 unwrap: {
243 fieldset: true,
244 legend: true,
245 // Unsupported sectioning tags
246 main: true,
247 nav: true,
248 aside: true,
249 // HTML headings are already bold by default. Some skins may use non-bold
250 // heaidngs, but more likely we will end up with useless bold annotations.
251 'h1 b, h2 b, h3 b, h4 b, h5 b, h6 b': true,
252 'h1 strong, h2 strong, h3 strong, h4 strong, h5 strong, h6 strong': true
253 }
254 },
255 nodeSanitization: true
256 },
257 all: null
258 };
259
260 /* Static methods */
261
262 /**
263 * Create a document model from an HTML document.
264 *
265 * @param {HTMLDocument|string} doc HTML document or source text
266 * @param {string} mode Editing mode
267 * @param {Object} options Conversion options
268 * @return {ve.dm.Document} Document model
269 */
270 ve.init.Target.static.createModelFromDom = function ( doc, mode, options ) {
271 if ( mode === 'source' ) {
272 return ve.dm.sourceConverter.getModelFromSourceText( doc, options );
273 } else {
274 return ve.dm.converter.getModelFromDom( doc, options );
275 }
276 };
277
278 /**
279 * Parse document string into an HTML document
280 *
281 * @param {string} documentString Document. Note that this must really be a whole document
282 * with a single root tag.
283 * @param {string} mode Editing mode
284 * @return {HTMLDocument|string} HTML document, or document string (source mode)
285 */
286 ve.init.Target.static.parseDocument = function ( documentString, mode ) {
287 if ( mode === 'source' ) {
288 return documentString;
289 }
290 return ve.createDocumentFromHtml( documentString );
291 };
292
293 // Deprecated alias
294 ve.init.Target.prototype.parseDocument = function () {
295 return this.constructor.static.parseDocument.apply( this.constructor.static, arguments );
296 };
297
298 /* Methods */
299
300 /**
301 * Set default editing mode for new surfaces
302 *
303 * @param {string} defaultMode Editing mode, see static.modes
304 */
305 ve.init.Target.prototype.setDefaultMode = function ( defaultMode ) {
306 // Mode is not available
307 if ( !this.isModeAvailable( defaultMode ) ) {
308 if ( !this.defaultMode ) {
309 // Use default mode if nothing has been set
310 defaultMode = this.modes[ 0 ];
311 } else {
312 // Fail if we already have a valid mode
313 return;
314 }
315 }
316 if ( defaultMode !== this.defaultMode ) {
317 if ( this.defaultMode ) {
318 // Documented below
319 // eslint-disable-next-line mediawiki/class-doc
320 this.$element.removeClass( 've-init-target-' + this.defaultMode );
321 }
322 // The following classes are used here:
323 // * ve-init-target-visual
324 // * ve-init-target-[modename]
325 this.$element.addClass( 've-init-target-' + defaultMode );
326 this.defaultMode = defaultMode;
327 }
328 };
329
330 /**
331 * Get default editing mode for new surfaces
332 *
333 * @return {string} Editing mode
334 */
335 ve.init.Target.prototype.getDefaultMode = function () {
336 return this.defaultMode;
337 };
338
339 /**
340 * Check if a specific editing mode is available
341 *
342 * @param {string} mode Editing mode
343 * @return {boolean} Editing mode is available
344 */
345 ve.init.Target.prototype.isModeAvailable = function ( mode ) {
346 return this.modes.indexOf( mode ) !== -1;
347 };
348
349 /**
350 * Bind event handlers to target and document
351 */
352 ve.init.Target.prototype.bindHandlers = function () {
353 $( this.getElementDocument() ).on( {
354 keydown: this.onDocumentKeyDownHandler,
355 keyup: this.onDocumentKeyUpHandler,
356 visibilitychange: this.onDocumentVisibilityChangeHandler
357 } );
358 this.$element.on( 'keydown', this.onTargetKeyDownHandler );
359 this.$scrollListener[ 0 ].addEventListener( 'scroll', this.onContainerScrollHandler, { passive: true } );
360 };
361
362 /**
363 * Unbind event handlers on target and document
364 */
365 ve.init.Target.prototype.unbindHandlers = function () {
366 $( this.getElementDocument() ).off( {
367 keydown: this.onDocumentKeyDownHandler,
368 keyup: this.onDocumentKeyUpHandler,
369 visibilitychange: this.onDocumentVisibilityChangeHandler
370 } );
371 this.$element.off( 'keydown', this.onTargetKeyDownHandler );
372 this.$scrollListener[ 0 ].removeEventListener( 'scroll', this.onContainerScrollHandler );
373 };
374
375 /**
376 * Teardown the target, removing all surfaces, toolbars and handlers
377 *
378 * @return {jQuery.Promise} Promise which resolves when the target has been torn down
379 */
380 ve.init.Target.prototype.teardown = function () {
381 if ( !this.teardownPromise ) {
382 this.unbindHandlers();
383 // Wait for the toolbar to teardown before clearing surfaces,
384 // as it may want to transition away
385 this.teardownPromise = this.teardownToolbar().then( this.clearSurfaces.bind( this ) );
386 }
387 return this.teardownPromise;
388 };
389
390 /**
391 * Destroy the target
392 *
393 * @return {jQuery.Promise} Promise which resolves when the target has been destroyed
394 */
395 ve.init.Target.prototype.destroy = function () {
396 return this.teardown().then( () => {
397 this.$element.remove();
398 if ( ve.init.target === this ) {
399 ve.init.target = null;
400 }
401 } );
402 };
403
404 /**
405 * Set up trigger listeners
406 */
407 ve.init.Target.prototype.setupTriggerListeners = function () {
408 const surfaceOrSurfaceConfig = this.getSurface() || this.getSurfaceConfig();
409 this.documentTriggerListener = new ve.TriggerListener( this.constructor.static.documentCommands, surfaceOrSurfaceConfig.commandRegistry );
410 this.targetTriggerListener = new ve.TriggerListener( this.constructor.static.targetCommands, surfaceOrSurfaceConfig.commandRegistry );
411 };
412
413 /**
414 * Get the target's scroll container
415 *
416 * @return {jQuery} The target's scroll container
417 */
418 ve.init.Target.prototype.getScrollContainer = function () {
419 return $( OO.ui.Element.static.getClosestScrollableContainer( document.body ) );
420 };
421
422 /**
423 * Handle scroll container scroll events
424 */
425 ve.init.Target.prototype.onContainerScroll = function () {
426 // Don't use getter as it creates the toolbar
427 const toolbar = this.toolbar;
428
429 if ( toolbar && toolbar.isFloatable() ) {
430 const wasFloating = toolbar.isFloating();
431 const scrollTop = this.$scrollContainer.scrollTop();
432
433 if ( scrollTop + this.toolbarScrollOffset > toolbar.getElementOffset().top ) {
434 toolbar.float();
435 } else {
436 toolbar.unfloat();
437 }
438
439 if ( toolbar.isFloating() !== wasFloating ) {
440 // HACK: Re-position any active toolgroup popups. We can't rely on normal event handler order
441 // because we're mixing jQuery and non-jQuery events. T205924#4657203
442 toolbar.getItems().forEach( ( toolgroup ) => {
443 if ( toolgroup instanceof OO.ui.PopupToolGroup && toolgroup.isActive() ) {
444 toolgroup.position();
445 }
446 } );
447 }
448 }
449 };
450
451 /**
452 * Handle key down events on the document
453 *
454 * @param {jQuery.Event} e Key down event
455 */
456 ve.init.Target.prototype.onDocumentKeyDown = function ( e ) {
457 const trigger = new ve.ui.Trigger( e );
458 if ( trigger.isComplete() ) {
459 const command = this.documentTriggerListener.getCommandByTrigger( trigger.toString() );
460 const surface = this.getSurface();
461 if ( surface && command && command.execute( surface, undefined, 'trigger' ) ) {
462 e.preventDefault();
463 }
464 }
465 // Allows elements to re-style for ctrl+click behaviour, e.g. ve.ce.LinkAnnotation
466 this.$element.toggleClass( 've-init-target-ctrl-meta-down', e.ctrlKey || e.metaKey );
467 };
468
469 /**
470 * Handle key up events on the document
471 *
472 * @param {jQuery.Event} e Key up event
473 */
474 ve.init.Target.prototype.onDocumentKeyUp = function ( e ) {
475 this.$element.toggleClass( 've-init-target-ctrl-meta-down', e.ctrlKey || e.metaKey );
476 };
477
478 /**
479 * Handle visibility change events on the document
480 *
481 * @param {jQuery.Event} e Visibility change event
482 */
483 ve.init.Target.prototype.onDocumentVisibilityChange = function () {
484 // keyup event will be missed if you ctrl+tab away from the page
485 this.$element.removeClass( 've-init-target-ctrl-meta-down' );
486 };
487
488 /**
489 * Handle key down events on the target
490 *
491 * @param {jQuery.Event} e Key down event
492 */
493 ve.init.Target.prototype.onTargetKeyDown = function ( e ) {
494 const trigger = new ve.ui.Trigger( e );
495 if ( trigger.isComplete() ) {
496 const command = this.targetTriggerListener.getCommandByTrigger( trigger.toString() );
497 const surface = this.getSurface();
498 if ( surface && command && command.execute( surface, undefined, 'trigger' ) ) {
499 e.preventDefault();
500 }
501 }
502 };
503
504 /**
505 * Handle toolbar resize events
506 */
507 ve.init.Target.prototype.onToolbarResize = function () {
508 if ( !this.getSurface() ) {
509 return;
510 }
511 this.getSurface().setPadding( {
512 top: this.getToolbar().getHeight() + this.toolbarScrollOffset
513 } );
514 };
515
516 /**
517 * Create a target widget.
518 *
519 * @param {Object} [config] Configuration options
520 * @return {ve.ui.TargetWidget}
521 */
522 ve.init.Target.prototype.createTargetWidget = function ( config ) {
523 return new ve.ui.TargetWidget( ve.extendObject( {
524 toolbarGroups: this.toolbarGroups
525 }, config ) );
526 };
527
528 /**
529 * Create a surface.
530 *
531 * @param {ve.dm.Document|ve.dm.Surface} dmDocOrSurface Document model or surface model
532 * @param {Object} [config] Configuration options
533 * @return {ve.ui.Surface}
534 */
535 ve.init.Target.prototype.createSurface = function ( dmDocOrSurface, config ) {
536 return new ve.ui.Surface( this, dmDocOrSurface, this.getSurfaceConfig( config ) );
537 };
538
539 /**
540 * Get surface configuration options
541 *
542 * @param {Object} config Configuration option overrides
543 * @return {Object} Surface configuration options
544 */
545 ve.init.Target.prototype.getSurfaceConfig = function ( config ) {
546 return ve.extendObject( {
547 $scrollContainer: this.$scrollContainer,
548 $scrollListener: this.$scrollListener,
549 commandRegistry: ve.ui.commandRegistry,
550 sequenceRegistry: ve.ui.sequenceRegistry,
551 dataTransferHandlerFactory: ve.ui.dataTransferHandlerFactory,
552 includeCommands: this.constructor.static.includeCommands,
553 excludeCommands: OO.simpleArrayUnion(
554 this.constructor.static.excludeCommands,
555 this.constructor.static.documentCommands,
556 this.constructor.static.targetCommands
557 ),
558 importRules: this.constructor.static.importRules
559 }, config );
560 };
561
562 /**
563 * Add a surface to the target
564 *
565 * @param {ve.dm.Document|ve.dm.Surface} dmDocOrSurface Document model or surface model
566 * @param {Object} [config] Configuration options
567 * @return {ve.ui.Surface}
568 */
569 ve.init.Target.prototype.addSurface = function ( dmDocOrSurface, config ) {
570 const surface = this.createSurface( dmDocOrSurface, ve.extendObject( { mode: this.getDefaultMode() }, config ) );
571 this.surfaces.push( surface );
572 surface.getView().connect( this, {
573 focus: this.onSurfaceViewFocus.bind( this, surface )
574 } );
575 // Sub-classes should initialize the surface when possible, then fire 'surfaceReady'
576 return surface;
577 };
578
579 /**
580 * Destroy and remove all surfaces from the target
581 */
582 ve.init.Target.prototype.clearSurfaces = function () {
583 // We're about to destroy this.surface, so unset it for sanity
584 // Otherwise, getSurface() could return a destroyed surface
585 this.surface = null;
586 while ( this.surfaces.length ) {
587 this.surfaces.pop().destroy();
588 }
589 };
590
591 /**
592 * Handle focus events from a surface's view
593 *
594 * @param {ve.ui.Surface} surface Surface firing the event
595 */
596 ve.init.Target.prototype.onSurfaceViewFocus = function ( surface ) {
597 this.setSurface( surface );
598 };
599
600 /**
601 * Set the target's active surface
602 *
603 * @param {ve.ui.Surface} surface
604 */
605 ve.init.Target.prototype.setSurface = function ( surface ) {
606 if ( OO.ui.isMobile() ) {
607 // Allow popup tool groups's menus to display on top of the mobile context, which is attached
608 // to the global overlay (T307849)
609 this.toolbarConfig.$overlay = surface.getGlobalOverlay().$element;
610 // There is already a toolbar (e.g. when switching), swap out the overlay:
611 // TODO: Add a setOverlay method to Toolbar, or create a new toolbar
612 if ( this.toolbar ) {
613 this.toolbar.$overlay = this.toolbarConfig.$overlay;
614 this.toolbar.$overlay.append( this.toolbar.$popups );
615 }
616 }
617
618 if ( this.surfaces.indexOf( surface ) === -1 ) {
619 throw new Error( 'Active surface must have been added first' );
620 }
621 if ( surface !== this.surface ) {
622 this.surface = surface;
623 this.setupToolbar( surface );
624 }
625 };
626
627 /**
628 * Get the target's active surface, if it exists
629 *
630 * @return {ve.ui.Surface|null}
631 */
632 ve.init.Target.prototype.getSurface = function () {
633 return this.surface;
634 };
635
636 /**
637 * Get the target's toolbar
638 *
639 * @return {ve.ui.TargetToolbar} Toolbar
640 */
641 ve.init.Target.prototype.getToolbar = function () {
642 if ( !this.toolbar ) {
643 this.toolbar = new ve.ui.PositionedTargetToolbar( this, this.toolbarConfig );
644 }
645 return this.toolbar;
646 };
647
648 /**
649 * Get the actions toolbar
650 *
651 * @deprecated
652 * @return {ve.ui.TargetToolbar} Actions toolbar (same as the normal toolbar)
653 */
654 ve.init.Target.prototype.getActions = function () {
655 OO.ui.warnDeprecation( 'Target#getActions: Use #getToolbar instead ' +
656 '(actions toolbar has been merged into the normal toolbar)' );
657 if ( !this.actionsToolbar ) {
658 this.actionsToolbar = this.getToolbar();
659 }
660 return this.actionsToolbar;
661 };
662
663 /**
664 * Set up the toolbar, attaching it to a surface.
665 *
666 * @param {ve.ui.Surface} surface
667 */
668 ve.init.Target.prototype.setupToolbar = function ( surface ) {
669 const toolbar = this.getToolbar();
670 if ( this.actionGroups.length ) {
671 // Backwards-compatibility
672 if ( !this.actionsToolbar ) {
673 this.actionsToolbar = this.getToolbar();
674 }
675 }
676
677 toolbar.connect( this, {
678 resize: 'onToolbarResize',
679 active: 'onToolbarActive'
680 } );
681
682 if ( surface.nullSelectionOnBlur ) {
683 toolbar.$element
684 .on( 'focusin', () => {
685 // When the focus moves to the toolbar, deactivate the surface but keep the selection (even if
686 // nullSelectionOnBlur is true), to allow tools to act on that selection.
687 surface.getView().deactivate( /* showAsActivated= */ true );
688 } )
689 .on( 'focusout', ( e ) => {
690 const newFocusedElement = e.relatedTarget;
691 if ( !OO.ui.contains( [ toolbar.$element[ 0 ], toolbar.$overlay[ 0 ] ], newFocusedElement, true ) ) {
692 // When the focus moves out of the toolbar:
693 if ( OO.ui.contains( surface.getView().$element[ 0 ], newFocusedElement, true ) ) {
694 // When the focus moves out of the toolbar, and it moves back into the surface,
695 // make sure the previous selection is restored.
696 const previousSelection = surface.getModel().getSelection();
697 surface.getView().activate();
698 if ( !previousSelection.isNull() ) {
699 surface.getModel().setSelection( previousSelection );
700 }
701 } else {
702 // When the focus moves out of the toolbar, and it doesn't move back into the surface,
703 // blur the surface explicitly to restore the expected nullSelectionOnBlur behavior.
704 // The surface was deactivated, so it doesn't react to the focus change itself.
705 surface.getView().blur();
706 }
707 }
708 } );
709 }
710
711 this.actionGroups.forEach( ( group ) => {
712 group.align = 'after';
713 } );
714 const groups = [ ...this.toolbarGroups, ...this.actionGroups ];
715
716 toolbar.setup( groups, surface );
717 this.attachToolbar();
718 requestAnimationFrame( this.onContainerScrollHandler );
719 };
720
721 /**
722 * Deactivate the surface. Maybe save some properties that should be restored when it's activated.
723 *
724 * @protected
725 */
726 ve.init.Target.prototype.deactivateSurfaceForToolbar = function () {
727 const view = this.getSurface().getView();
728 // Surface may already be deactivated (e.g. link inspector is open)
729 this.wasSurfaceActive = !view.deactivated;
730 if ( this.wasSurfaceActive ) {
731 view.deactivate();
732 }
733 };
734
735 /**
736 * Activate the surface. Restore any properties saved in #deactivate.
737 *
738 * @protected
739 */
740 ve.init.Target.prototype.activateSurfaceForToolbar = function () {
741 const view = this.getSurface().getView();
742 // For non-collapsed mobile selections, don't reactivate
743 if ( this.wasSurfaceActive && !( OO.ui.isMobile() && !view.getModel().getSelection().isCollapsed() ) ) {
744 view.activate();
745 }
746 };
747
748 /**
749 * Handle active events from the toolbar
750 *
751 * @param {boolean} active The toolbar is active
752 */
753 ve.init.Target.prototype.onToolbarActive = function ( active ) {
754 // Deactivate the surface when the toolbar is active (T109529, T201329)
755 if ( active ) {
756 this.activeToolbars++;
757 if ( this.activeToolbars === 1 ) {
758 this.deactivateSurfaceForToolbar();
759 }
760 } else {
761 this.activeToolbars--;
762 if ( !this.activeToolbars ) {
763 this.activateSurfaceForToolbar();
764 }
765 }
766 };
767
768 /**
769 * Teardown the toolbar
770 *
771 * @return {jQuery.Promise} Promise which resolves when the toolbar has been torn down
772 */
773 ve.init.Target.prototype.teardownToolbar = function () {
774 if ( this.toolbar ) {
775 this.toolbar.destroy();
776 this.toolbar = null;
777 }
778 if ( this.actionsToolbar ) {
779 this.actionsToolbar = null;
780 }
781 return ve.createDeferred().resolve().promise();
782 };
783
784 /**
785 * Attach the toolbar to the DOM
786 */
787 ve.init.Target.prototype.attachToolbar = function () {
788 const toolbar = this.getToolbar();
789 toolbar.$element.insertBefore( toolbar.getSurface().$element );
790 toolbar.initialize();
791 };