-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathworkspace_svg.ts
2456 lines (2224 loc) · 74.1 KB
/
workspace_svg.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2014 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Object representing a workspace rendered as SVG.
*
* @class
*/
// Former goog.module ID: Blockly.WorkspaceSvg
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_block_create.js';
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_theme_change.js';
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_viewport.js';
import type {Block} from './block.js';
import type {BlockSvg} from './block_svg.js';
import type {BlocklyOptions} from './blockly_options.js';
import * as browserEvents from './browser_events.js';
import {RenderedWorkspaceComment} from './comments/rendered_workspace_comment.js';
import {WorkspaceComment} from './comments/workspace_comment.js';
import * as common from './common.js';
import {ComponentManager} from './component_manager.js';
import {ConnectionDB} from './connection_db.js';
import * as ContextMenu from './contextmenu.js';
import {
ContextMenuOption,
ContextMenuRegistry,
} from './contextmenu_registry.js';
import * as dropDownDiv from './dropdowndiv.js';
import {EventType} from './events/type.js';
import * as eventUtils from './events/utils.js';
import type {FlyoutButton} from './flyout_button.js';
import {Gesture} from './gesture.js';
import {Grid} from './grid.js';
import type {IASTNodeLocationSvg} from './interfaces/i_ast_node_location_svg.js';
import type {IBoundedElement} from './interfaces/i_bounded_element.js';
import type {IDragTarget} from './interfaces/i_drag_target.js';
import type {IFlyout} from './interfaces/i_flyout.js';
import type {IMetricsManager} from './interfaces/i_metrics_manager.js';
import type {IToolbox} from './interfaces/i_toolbox.js';
import type {Cursor} from './keyboard_nav/cursor.js';
import type {Marker} from './keyboard_nav/marker.js';
import {LayerManager} from './layer_manager.js';
import {MarkerManager} from './marker_manager.js';
import {Options} from './options.js';
import * as Procedures from './procedures.js';
import * as registry from './registry.js';
import * as renderManagement from './render_management.js';
import * as blockRendering from './renderers/common/block_rendering.js';
import type {Renderer} from './renderers/common/renderer.js';
import type {ScrollbarPair} from './scrollbar_pair.js';
import type {Theme} from './theme.js';
import {Classic} from './theme/classic.js';
import {ThemeManager} from './theme_manager.js';
import * as Tooltip from './tooltip.js';
import type {Trashcan} from './trashcan.js';
import * as arrayUtils from './utils/array.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as drag from './utils/drag.js';
import type {Metrics} from './utils/metrics.js';
import {Rect} from './utils/rect.js';
import {Size} from './utils/size.js';
import {Svg} from './utils/svg.js';
import * as svgMath from './utils/svg_math.js';
import * as toolbox from './utils/toolbox.js';
import * as userAgent from './utils/useragent.js';
import type {VariableModel} from './variable_model.js';
import * as Variables from './variables.js';
import * as VariablesDynamic from './variables_dynamic.js';
import * as WidgetDiv from './widgetdiv.js';
import {Workspace} from './workspace.js';
import {WorkspaceAudio} from './workspace_audio.js';
import {ZoomControls} from './zoom_controls.js';
/** Margin around the top/bottom/left/right after a zoomToFit call. */
const ZOOM_TO_FIT_MARGIN = 20;
/**
* Class for a workspace. This is an onscreen area with optional trashcan,
* scrollbars, bubbles, and dragging.
*/
export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
/**
* A wrapper function called when a resize event occurs.
* You can pass the result to `eventHandling.unbind`.
*/
private resizeHandlerWrapper: browserEvents.Data | null = null;
/**
* The render status of an SVG workspace.
* Returns `false` for headless workspaces and true for instances of
* `WorkspaceSvg`.
*/
override rendered = true;
/**
* Whether the workspace is visible. False if the workspace has been hidden
* by calling `setVisible(false)`.
*/
private visible = true;
/**
* Whether this workspace has resizes enabled.
* Disable during batch operations for a performance improvement.
*/
private resizesEnabled = true;
/**
* Current horizontal scrolling offset in pixel units, relative to the
* workspace origin.
*
* It is useful to think about a view, and a canvas moving beneath that
* view. As the canvas moves right, this value becomes more positive, and
* the view is now "seeing" the left side of the canvas. As the canvas moves
* left, this value becomes more negative, and the view is now "seeing" the
* right side of the canvas.
*
* The confusing thing about this value is that it does not, and must not
* include the absoluteLeft offset. This is because it is used to calculate
* the viewLeft value.
*
* The viewLeft is relative to the workspace origin (although in pixel
* units). The workspace origin is the top-left corner of the workspace (at
* least when it is enabled). It is shifted from the top-left of the
* blocklyDiv so as not to be beneath the toolbox.
*
* When the workspace is enabled the viewLeft and workspace origin are at
* the same X location. As the canvas slides towards the right beneath the
* view this value (scrollX) becomes more positive, and the viewLeft becomes
* more negative relative to the workspace origin (imagine the workspace
* origin as a dot on the canvas sliding to the right as the canvas moves).
*
* So if the scrollX were to include the absoluteLeft this would in a way
* "unshift" the workspace origin. This means that the viewLeft would be
* representing the left edge of the blocklyDiv, rather than the left edge
* of the workspace.
*/
scrollX = 0;
/**
* Current vertical scrolling offset in pixel units, relative to the
* workspace origin.
*
* It is useful to think about a view, and a canvas moving beneath that
* view. As the canvas moves down, this value becomes more positive, and the
* view is now "seeing" the upper part of the canvas. As the canvas moves
* up, this value becomes more negative, and the view is "seeing" the lower
* part of the canvas.
*
* This confusing thing about this value is that it does not, and must not
* include the absoluteTop offset. This is because it is used to calculate
* the viewTop value.
*
* The viewTop is relative to the workspace origin (although in pixel
* units). The workspace origin is the top-left corner of the workspace (at
* least when it is enabled). It is shifted from the top-left of the
* blocklyDiv so as not to be beneath the toolbox.
*
* When the workspace is enabled the viewTop and workspace origin are at the
* same Y location. As the canvas slides towards the bottom this value
* (scrollY) becomes more positive, and the viewTop becomes more negative
* relative to the workspace origin (image in the workspace origin as a dot
* on the canvas sliding downwards as the canvas moves).
*
* So if the scrollY were to include the absoluteTop this would in a way
* "unshift" the workspace origin. This means that the viewTop would be
* representing the top edge of the blocklyDiv, rather than the top edge of
* the workspace.
*/
scrollY = 0;
/** Horizontal scroll value when scrolling started in pixel units. */
startScrollX = 0;
/** Vertical scroll value when scrolling started in pixel units. */
startScrollY = 0;
/** Current scale. */
scale = 1;
/** Cached scale value. Used to detect changes in viewport. */
private oldScale = 1;
/** Cached viewport top value. Used to detect changes in viewport. */
private oldTop = 0;
/** Cached viewport left value. Used to detect changes in viewport. */
private oldLeft = 0;
/** The workspace's trashcan (if any). */
trashcan: Trashcan | null = null;
/** This workspace's scrollbars, if they exist. */
scrollbar: ScrollbarPair | null = null;
/**
* Fixed flyout providing blocks which may be dragged into this workspace.
*/
private flyout: IFlyout | null = null;
/**
* Category-based toolbox providing blocks which may be dragged into this
* workspace.
*/
private toolbox: IToolbox | null = null;
/**
* The current gesture in progress on this workspace, if any.
*
* @internal
*/
currentGesture_: Gesture | null = null;
/**
* The first parent div with 'injectionDiv' in the name, or null if not set.
* Access this with getInjectionDiv.
*/
private injectionDiv: Element | null = null;
/**
* Last known position of the page scroll.
* This is used to determine whether we have recalculated screen coordinate
* stuff since the page scrolled.
*/
private lastRecordedPageScroll: Coordinate | null = null;
/**
* Developers may define this function to add custom menu options to the
* workspace's context menu or edit the workspace-created set of menu
* options.
*
* @param options List of menu options to add to.
* @param e The right-click event that triggered the context menu.
*/
configureContextMenu:
| ((menuOptions: ContextMenuOption[], e: Event) => void)
| null = null;
/**
* A dummy wheel event listener used as a workaround for a Safari scrolling issue.
* Set in createDom and used for removal in dispose to ensure proper cleanup.
*/
private dummyWheelListener: (() => void) | null = null;
/**
* In a flyout, the target workspace where blocks should be placed after a
* drag. Otherwise null.
*
* @internal
*/
targetWorkspace: WorkspaceSvg | null = null;
/** Inverted screen CTM, for use in mouseToSvg. */
private inverseScreenCTM: SVGMatrix | null = null;
/** Inverted screen CTM is dirty, recalculate it. */
private inverseScreenCTMDirty = true;
private metricsManager: IMetricsManager;
/** @internal */
getMetrics: () => Metrics;
/** @internal */
setMetrics: (p1: {x?: number; y?: number}) => void;
private readonly componentManager: ComponentManager;
/**
* List of currently highlighted blocks. Block highlighting is often used
* to visually mark blocks currently being executed.
*/
private readonly highlightedBlocks: BlockSvg[] = [];
private audioManager: WorkspaceAudio;
private grid: Grid | null;
private markerManager: MarkerManager;
/**
* Map from function names to callbacks, for deciding what to do when a
* custom toolbox category is opened.
*/
private toolboxCategoryCallbacks = new Map<
string,
(p1: WorkspaceSvg) => toolbox.FlyoutDefinition
>();
/**
* Map from function names to callbacks, for deciding what to do when a
* button is clicked.
*/
private flyoutButtonCallbacks = new Map<string, (p1: FlyoutButton) => void>();
protected themeManager_: ThemeManager;
private readonly renderer: Renderer;
/** Cached parent SVG. */
private cachedParentSvg: SVGElement | null = null;
/** True if keyboard accessibility mode is on, false otherwise. */
keyboardAccessibilityMode = false;
/** The list of top-level bounded elements on the workspace. */
private topBoundedElements: IBoundedElement[] = [];
/** The recorded drag targets. */
private dragTargetAreas: Array<{component: IDragTarget; clientRect: Rect}> =
[];
private readonly cachedParentSvgSize: Size;
private layerManager: LayerManager | null = null;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
svgGroup_!: SVGElement;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
svgBackground_!: SVGElement;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
svgBlockCanvas_!: SVGElement;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
svgBubbleCanvas_!: SVGElement;
zoomControls_: ZoomControls | null = null;
/**
* @param options Dictionary of options.
*/
constructor(options: Options) {
super(options);
const MetricsManagerClass = registry.getClassFromOptions(
registry.Type.METRICS_MANAGER,
options,
true,
);
/** Object in charge of calculating metrics for the workspace. */
this.metricsManager = new MetricsManagerClass!(this);
/** Method to get all the metrics that have to do with a workspace. */
this.getMetrics =
options.getMetrics ||
this.metricsManager.getMetrics.bind(this.metricsManager);
/** Translates the workspace. */
this.setMetrics =
options.setMetrics || WorkspaceSvg.setTopLevelWorkspaceMetrics;
this.componentManager = new ComponentManager();
this.connectionDBList = ConnectionDB.init(this.connectionChecker);
/**
* Object in charge of loading, storing, and playing audio for a workspace.
*/
this.audioManager = new WorkspaceAudio(
options.parentWorkspace as WorkspaceSvg,
);
/** This workspace's grid object or null. */
this.grid = this.options.gridPattern
? new Grid(this.options.gridPattern, options.gridOptions)
: null;
/** Manager in charge of markers and cursors. */
this.markerManager = new MarkerManager(this);
if (Variables && Variables.flyoutCategory) {
this.registerToolboxCategoryCallback(
Variables.CATEGORY_NAME,
Variables.flyoutCategory,
);
}
if (VariablesDynamic && VariablesDynamic.flyoutCategory) {
this.registerToolboxCategoryCallback(
VariablesDynamic.CATEGORY_NAME,
VariablesDynamic.flyoutCategory,
);
}
if (Procedures && Procedures.flyoutCategory) {
this.registerToolboxCategoryCallback(
Procedures.CATEGORY_NAME,
Procedures.flyoutCategory,
);
this.addChangeListener(Procedures.mutatorOpenListener);
}
/** Object in charge of storing and updating the workspace theme. */
this.themeManager_ = this.options.parentWorkspace
? this.options.parentWorkspace.getThemeManager()
: new ThemeManager(this, this.options.theme || Classic);
this.themeManager_.subscribeWorkspace(this);
/** The block renderer used for rendering blocks on this workspace. */
this.renderer = blockRendering.init(
this.options.renderer || 'geras',
this.getTheme(),
this.options.rendererOverrides ?? undefined,
);
/**
* The cached size of the parent svg element.
* Used to compute svg metrics.
*/
this.cachedParentSvgSize = new Size(0, 0);
}
/**
* Get the marker manager for this workspace.
*
* @returns The marker manager.
*/
getMarkerManager(): MarkerManager {
return this.markerManager;
}
/**
* Gets the metrics manager for this workspace.
*
* @returns The metrics manager.
*/
getMetricsManager(): IMetricsManager {
return this.metricsManager;
}
/**
* Sets the metrics manager for the workspace.
*
* @param metricsManager The metrics manager.
* @internal
*/
setMetricsManager(metricsManager: IMetricsManager) {
this.metricsManager = metricsManager;
this.getMetrics = this.metricsManager.getMetrics.bind(this.metricsManager);
}
/**
* Gets the component manager for this workspace.
*
* @returns The component manager.
*/
getComponentManager(): ComponentManager {
return this.componentManager;
}
/**
* Add the cursor SVG to this workspaces SVG group.
*
* @param cursorSvg The SVG root of the cursor to be added to the workspace
* SVG group.
* @internal
*/
setCursorSvg(cursorSvg: SVGElement) {
this.markerManager.setCursorSvg(cursorSvg);
}
/**
* Add the marker SVG to this workspaces SVG group.
*
* @param markerSvg The SVG root of the marker to be added to the workspace
* SVG group.
* @internal
*/
setMarkerSvg(markerSvg: SVGElement) {
this.markerManager.setMarkerSvg(markerSvg);
}
/**
* Get the marker with the given ID.
*
* @param id The ID of the marker.
* @returns The marker with the given ID or null if no marker with the given
* ID exists.
* @internal
*/
getMarker(id: string): Marker | null {
if (this.markerManager) {
return this.markerManager.getMarker(id);
}
return null;
}
/**
* The cursor for this workspace.
*
* @returns The cursor for the workspace.
*/
getCursor(): Cursor | null {
if (this.markerManager) {
return this.markerManager.getCursor();
}
return null;
}
/**
* Get the block renderer attached to this workspace.
*
* @returns The renderer attached to this workspace.
*/
getRenderer(): Renderer {
return this.renderer;
}
/**
* Get the theme manager for this workspace.
*
* @returns The theme manager for this workspace.
* @internal
*/
getThemeManager(): ThemeManager {
return this.themeManager_;
}
/**
* Get the workspace theme object.
*
* @returns The workspace theme object.
*/
getTheme(): Theme {
return this.themeManager_.getTheme();
}
/**
* Set the workspace theme object.
* If no theme is passed, default to the `Classic` theme.
*
* @param theme The workspace theme object.
*/
setTheme(theme: Theme) {
if (!theme) {
theme = Classic as Theme;
}
this.themeManager_.setTheme(theme);
}
/**
* Refresh all blocks on the workspace after a theme update.
*/
refreshTheme() {
if (this.svgGroup_) {
this.renderer.refreshDom(this.svgGroup_, this.getTheme());
}
// Update all blocks in workspace that have a style name.
this.updateBlockStyles(
this.getAllBlocks(false).filter((block) => !!block.getStyleName()),
);
// Update current toolbox selection.
this.refreshToolboxSelection();
if (this.toolbox) {
this.toolbox.refreshTheme();
}
// Re-render if workspace is visible
if (this.isVisible()) {
this.setVisible(true);
}
const event = new (eventUtils.get(EventType.THEME_CHANGE))(
this.getTheme().name,
this.id,
);
eventUtils.fire(event);
}
/**
* Updates all the blocks with new style.
*
* @param blocks List of blocks to update the style on.
*/
private updateBlockStyles(blocks: Block[]) {
for (let i = 0, block; (block = blocks[i]); i++) {
const blockStyleName = block.getStyleName();
if (blockStyleName) {
const blockSvg = block as BlockSvg;
blockSvg.setStyle(blockStyleName);
}
}
}
/**
* Getter for the inverted screen CTM.
*
* @returns The matrix to use in mouseToSvg
*/
getInverseScreenCTM(): SVGMatrix | null {
// Defer getting the screen CTM until we actually need it, this should
// avoid forced reflows from any calls to updateInverseScreenCTM.
if (this.inverseScreenCTMDirty) {
const ctm = this.getParentSvg().getScreenCTM();
if (ctm) {
this.inverseScreenCTM = ctm.inverse();
this.inverseScreenCTMDirty = false;
}
}
return this.inverseScreenCTM;
}
/** Mark the inverse screen CTM as dirty. */
updateInverseScreenCTM() {
this.inverseScreenCTMDirty = true;
}
/**
* Getter for isVisible
*
* @returns Whether the workspace is visible.
* False if the workspace has been hidden by calling `setVisible(false)`.
*/
isVisible(): boolean {
return this.visible;
}
/**
* Return the absolute coordinates of the top-left corner of this element,
* scales that after canvas SVG element, if it's a descendant.
* The origin (0,0) is the top-left corner of the Blockly SVG.
*
* @param element SVG element to find the coordinates of.
* @returns Object with .x and .y properties.
* @internal
*/
getSvgXY(element: SVGElement): Coordinate {
let x = 0;
let y = 0;
let scale = 1;
if (
this.getCanvas().contains(element) ||
this.getBubbleCanvas().contains(element)
) {
// Before the SVG canvas, scale the coordinates.
scale = this.scale;
}
do {
// Loop through this block and every parent.
const xy = svgMath.getRelativeXY(element);
if (element === this.getCanvas() || element === this.getBubbleCanvas()) {
// After the SVG canvas, don't scale the coordinates.
scale = 1;
}
x += xy.x * scale;
y += xy.y * scale;
element = element.parentNode as SVGElement;
} while (
element &&
element !== this.getParentSvg() &&
element !== this.getInjectionDiv()
);
return new Coordinate(x, y);
}
/**
* Gets the size of the workspace's parent SVG element.
*
* @returns The cached width and height of the workspace's parent SVG element.
* @internal
*/
getCachedParentSvgSize(): Size {
const size = this.cachedParentSvgSize;
return new Size(size.width, size.height);
}
/**
* Return the position of the workspace origin relative to the injection div
* origin in pixels.
* The workspace origin is where a block would render at position (0, 0).
* It is not the upper left corner of the workspace SVG.
*
* @returns Offset in pixels.
* @internal
*/
getOriginOffsetInPixels(): Coordinate {
return svgMath.getInjectionDivXY(this.getCanvas());
}
/**
* Return the injection div that is a parent of this workspace.
* Walks the DOM the first time it's called, then returns a cached value.
* Note: We assume this is only called after the workspace has been injected
* into the DOM.
*
* @returns The first parent div with 'injectionDiv' in the name.
* @internal
*/
getInjectionDiv(): Element {
// NB: it would be better to pass this in at createDom, but is more likely
// to break existing uses of Blockly.
if (!this.injectionDiv) {
let element: Element = this.svgGroup_;
while (element) {
const classes = element.getAttribute('class') || '';
if ((' ' + classes + ' ').includes(' injectionDiv ')) {
this.injectionDiv = element;
break;
}
element = element.parentNode as Element;
}
}
return this.injectionDiv!;
}
/**
* Returns the SVG group for the workspace.
*
* @returns The SVG group for the workspace.
*/
getSvgGroup(): Element {
return this.svgGroup_;
}
/**
* Get the SVG block canvas for the workspace.
*
* @returns The SVG group for the workspace.
* @internal
*/
getBlockCanvas(): SVGElement | null {
return this.getCanvas();
}
/**
* Save resize handler data so we can delete it later in dispose.
*
* @param handler Data that can be passed to eventHandling.unbind.
*/
setResizeHandlerWrapper(handler: browserEvents.Data) {
this.resizeHandlerWrapper = handler;
}
/**
* Create the workspace DOM elements.
*
* @param opt_backgroundClass Either 'blocklyMainBackground' or
* 'blocklyMutatorBackground'.
* @returns The workspace's SVG group.
*/
createDom(opt_backgroundClass?: string, injectionDiv?: Element): Element {
if (!this.injectionDiv) {
this.injectionDiv = injectionDiv ?? null;
}
/**
* <g class="blocklyWorkspace">
* <rect class="blocklyMainBackground" height="100%" width="100%"></rect>
* [Trashcan and/or flyout may go here]
* <g class="blocklyBlockCanvas"></g>
* <g class="blocklyBubbleCanvas"></g>
* </g>
*/
this.svgGroup_ = dom.createSvgElement(Svg.G, {'class': 'blocklyWorkspace'});
// Note that a <g> alone does not receive mouse events--it must have a
// valid target inside it. If no background class is specified, as in the
// flyout, the workspace will not receive mouse events.
if (opt_backgroundClass) {
this.svgBackground_ = dom.createSvgElement(
Svg.RECT,
{'height': '100%', 'width': '100%', 'class': opt_backgroundClass},
this.svgGroup_,
);
if (opt_backgroundClass === 'blocklyMainBackground' && this.grid) {
this.svgBackground_.style.fill =
'url(#' + this.grid.getPatternId() + ')';
} else {
this.themeManager_.subscribe(
this.svgBackground_,
'workspaceBackgroundColour',
'fill',
);
}
}
this.layerManager = new LayerManager(this);
// Assign the canvases for backwards compatibility.
this.svgBlockCanvas_ = this.layerManager.getBlockLayer();
this.svgBubbleCanvas_ = this.layerManager.getBubbleLayer();
if (!this.isFlyout) {
browserEvents.conditionalBind(
this.svgGroup_,
'pointerdown',
this,
this.onMouseDown,
false,
);
// This no-op works around https://bugs.webkit.org/show_bug.cgi?id=226683,
// which otherwise prevents zoom/scroll events from being observed in
// Safari. Once that bug is fixed it should be removed.
this.dummyWheelListener = () => {};
document.body.addEventListener('wheel', this.dummyWheelListener);
browserEvents.conditionalBind(
this.svgGroup_,
'wheel',
this,
this.onMouseWheel,
);
}
// Determine if there needs to be a category tree, or a simple list of
// blocks. This cannot be changed later, since the UI is very different.
if (this.options.hasCategories) {
const ToolboxClass = registry.getClassFromOptions(
registry.Type.TOOLBOX,
this.options,
true,
);
this.toolbox = new ToolboxClass!(this);
}
if (this.grid) {
this.grid.update(this.scale);
}
this.recordDragTargets();
const CursorClass = registry.getClassFromOptions(
registry.Type.CURSOR,
this.options,
);
if (CursorClass) this.markerManager.setCursor(new CursorClass());
this.renderer.createDom(this.svgGroup_, this.getTheme());
return this.svgGroup_;
}
/**
* Dispose of this workspace.
* Unlink from all DOM elements to prevent memory leaks.
*/
override dispose() {
// Stop rerendering.
this.rendered = false;
if (this.currentGesture_) {
this.currentGesture_.cancel();
}
if (this.svgGroup_) {
dom.removeNode(this.svgGroup_);
}
if (this.toolbox) {
this.toolbox.dispose();
this.toolbox = null;
}
if (this.flyout) {
this.flyout.dispose();
this.flyout = null;
}
if (this.trashcan) {
this.trashcan.dispose();
this.trashcan = null;
}
if (this.scrollbar) {
this.scrollbar.dispose();
this.scrollbar = null;
}
if (this.zoomControls_) {
this.zoomControls_.dispose();
}
if (this.audioManager) {
this.audioManager.dispose();
}
if (this.grid) {
this.grid = null;
}
this.renderer.dispose();
if (this.markerManager) {
this.markerManager.dispose();
}
super.dispose();
// Dispose of theme manager after all blocks and mutators are disposed of.
if (this.themeManager_) {
this.themeManager_.unsubscribeWorkspace(this);
this.themeManager_.unsubscribe(this.svgBackground_);
if (!this.options.parentWorkspace) {
this.themeManager_.dispose();
}
}
this.connectionDBList.length = 0;
this.toolboxCategoryCallbacks.clear();
this.flyoutButtonCallbacks.clear();
if (!this.options.parentWorkspace) {
// Top-most workspace. Dispose of the div that the
// SVG is injected into (i.e. injectionDiv).
const parentSvg = this.getParentSvg();
if (parentSvg && parentSvg.parentNode) {
dom.removeNode(parentSvg.parentNode);
}
}
if (this.resizeHandlerWrapper) {
browserEvents.unbind(this.resizeHandlerWrapper);
this.resizeHandlerWrapper = null;
}
// Remove the dummy wheel listener
if (this.dummyWheelListener) {
document.body.removeEventListener('wheel', this.dummyWheelListener);
this.dummyWheelListener = null;
}
}
/**
* Add a trashcan.
*
* @internal
*/
addTrashcan() {
this.trashcan = WorkspaceSvg.newTrashcan(this);
const svgTrashcan = this.trashcan.createDom();
this.svgGroup_.insertBefore(svgTrashcan, this.getCanvas());
}
/**
* @param _workspace
* @internal
*/
static newTrashcan(_workspace: WorkspaceSvg): Trashcan {
throw new Error(
'The implementation of newTrashcan should be ' +
'monkey-patched in by blockly.ts',
);
}
/**
* Add zoom controls.
*
* @internal
*/
addZoomControls() {
this.zoomControls_ = new ZoomControls(this);
const svgZoomControls = this.zoomControls_.createDom();
this.svgGroup_.appendChild(svgZoomControls);
}
/**
* Add a flyout element in an element with the given tag name.
*
* @param tagName What type of tag the flyout belongs in.
* @returns The element containing the flyout DOM.
* @internal
*/
addFlyout(tagName: string | Svg<SVGSVGElement> | Svg<SVGGElement>): Element {
const workspaceOptions = new Options({
'parentWorkspace': this,
'rtl': this.RTL,
'oneBasedIndex': this.options.oneBasedIndex,
'horizontalLayout': this.horizontalLayout,
'renderer': this.options.renderer,
'rendererOverrides': this.options.rendererOverrides,
'move': {
'scrollbars': true,
},
} as BlocklyOptions);
workspaceOptions.toolboxPosition = this.options.toolboxPosition;
if (this.horizontalLayout) {
const HorizontalFlyout = registry.getClassFromOptions(
registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX,
this.options,
true,
);
this.flyout = new HorizontalFlyout!(workspaceOptions);
} else {
const VerticalFlyout = registry.getClassFromOptions(
registry.Type.FLYOUTS_VERTICAL_TOOLBOX,
this.options,
true,
);
this.flyout = new VerticalFlyout!(workspaceOptions);
}
this.flyout.autoClose = false;
this.flyout.getWorkspace().setVisible(true);
// Return the element so that callers can place it in their desired
// spot in the DOM. For example, mutator flyouts do not go in the same
// place as main workspace flyouts.
return this.flyout.createDom(tagName);
}
/**
* Getter for the flyout associated with this workspace. This flyout may be
* owned by either the toolbox or the workspace, depending on toolbox
* configuration. It will be null if there is no flyout.
*
* @param opt_own Whether to only return the workspace's own flyout.
* @returns The flyout on this workspace.
*/
getFlyout(opt_own?: boolean): IFlyout | null {
if (this.flyout || opt_own) {
return this.flyout;
}
if (this.toolbox) {
return this.toolbox.getFlyout();
}
return null;