-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathblock_svg.ts
More file actions
1861 lines (1666 loc) · 53.7 KB
/
block_svg.ts
File metadata and controls
1861 lines (1666 loc) · 53.7 KB
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 2012 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Methods for graphically rendering a block as SVG.
*
* @class
*/
// Former goog.module ID: Blockly.BlockSvg
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_selected.js';
import {Block} from './block.js';
import * as blockAnimations from './block_animations.js';
import * as browserEvents from './browser_events.js';
import {BlockCopyData, BlockPaster} from './clipboard/block_paster.js';
import * as common from './common.js';
import {config} from './config.js';
import type {Connection} from './connection.js';
import {ConnectionType} from './connection_type.js';
import * as constants from './constants.js';
import * as ContextMenu from './contextmenu.js';
import {
ContextMenuOption,
ContextMenuRegistry,
LegacyContextMenuOption,
} from './contextmenu_registry.js';
import {BlockDragStrategy} from './dragging/block_drag_strategy.js';
import type {BlockMove} from './events/events_block_move.js';
import {EventType} from './events/type.js';
import * as eventUtils from './events/utils.js';
import {FieldLabel} from './field_label.js';
import {getFocusManager} from './focus_manager.js';
import {IconType} from './icons/icon_types.js';
import {MutatorIcon} from './icons/mutator_icon.js';
import {WarningIcon} from './icons/warning_icon.js';
import type {Input} from './inputs/input.js';
import type {IBoundedElement} from './interfaces/i_bounded_element.js';
import {IContextMenu} from './interfaces/i_contextmenu.js';
import type {ICopyable} from './interfaces/i_copyable.js';
import {IDeletable} from './interfaces/i_deletable.js';
import type {IDragStrategy, IDraggable} from './interfaces/i_draggable.js';
import type {IFocusableNode} from './interfaces/i_focusable_node.js';
import type {IFocusableTree} from './interfaces/i_focusable_tree.js';
import {IIcon} from './interfaces/i_icon.js';
import * as internalConstants from './internal_constants.js';
import {Msg} from './msg.js';
import * as renderManagement from './render_management.js';
import {RenderedConnection} from './rendered_connection.js';
import type {IPathObject} from './renderers/common/i_path_object.js';
import * as blocks from './serialization/blocks.js';
import type {BlockStyle} from './theme.js';
import * as Tooltip from './tooltip.js';
import {idGenerator} from './utils.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import {Rect} from './utils/rect.js';
import {Svg} from './utils/svg.js';
import * as svgMath from './utils/svg_math.js';
import {FlyoutItemInfo} from './utils/toolbox.js';
import type {Workspace} from './workspace.js';
import type {WorkspaceSvg} from './workspace_svg.js';
/**
* Class for a block's SVG representation.
* Not normally called directly, workspace.newBlock() is preferred.
*/
export class BlockSvg
extends Block
implements
IBoundedElement,
IContextMenu,
ICopyable<BlockCopyData>,
IDraggable,
IDeletable,
IFocusableNode
{
/**
* Constant for identifying rows that are to be rendered inline.
* Don't collide with Blockly.inputTypes.
*/
static readonly INLINE = -1;
/**
* ID to give the "collapsed warnings" warning. Allows us to remove the
* "collapsed warnings" warning without removing any warnings that belong to
* the block.
*/
static readonly COLLAPSED_WARNING_ID = 'TEMP_COLLAPSED_WARNING_';
override decompose?: (p1: Workspace) => BlockSvg;
// override compose?: ((p1: BlockSvg) => void)|null;
/**
* An optional method which saves a record of blocks connected to
* this block so they can be later restored after this block is
* recoomposed (reconfigured). Typically records the connected
* blocks on properties on blocks in the mutator flyout, so that
* rearranging those component blocks will automatically rearrange
* the corresponding connected blocks on this block after this block
* is recomposed.
*
* To keep the saved connection information up-to-date, MutatorIcon
* arranges for an event listener to call this method any time the
* mutator flyout is open and a change occurs on this block's
* workspace.
*
* @param rootBlock The root block in the mutator flyout.
*/
saveConnections?: (rootBlock: BlockSvg) => void;
customContextMenu?: (
p1: Array<ContextMenuOption | LegacyContextMenuOption>,
) => void;
/**
* Height of this block, not including any statement blocks above or below.
* Height is in workspace units.
*/
height = 0;
/**
* Width of this block, including any connected value blocks.
* Width is in workspace units.
*/
width = 0;
/**
* Width of this block, not including any connected value blocks.
* Width is in workspace units.
*
* @internal
*/
childlessWidth = 0;
/**
* Map from IDs for warnings text to PIDs of functions to apply them.
* Used to be able to maintain multiple warnings.
*/
private warningTextDb = new Map<string, ReturnType<typeof setTimeout>>();
/** Block's mutator icon (if any). */
mutator: MutatorIcon | null = null;
private svgGroup: SVGGElement;
style: BlockStyle;
/** @internal */
pathObject: IPathObject;
/** Is this block a BlockSVG? */
override readonly rendered = true;
private visuallyDisabled = false;
override workspace: WorkspaceSvg;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
override outputConnection!: RenderedConnection;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
override nextConnection!: RenderedConnection;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
override previousConnection!: RenderedConnection;
private translation = '';
/** Whether this block is currently being dragged. */
private dragging = false;
/**
* The location of the top left of this block (in workspace coordinates)
* relative to either its parent block, or the workspace origin if it has no
* parent.
*
* @internal
*/
relativeCoords = new Coordinate(0, 0);
private dragStrategy: IDragStrategy = new BlockDragStrategy(this);
/**
* @param workspace The block's workspace.
* @param prototypeName Name of the language object containing type-specific
* functions for this block.
* @param opt_id Optional ID. Use this ID if provided, otherwise create a new
* ID.
*/
constructor(workspace: WorkspaceSvg, prototypeName: string, opt_id?: string) {
super(workspace, prototypeName, opt_id);
if (!workspace.rendered) {
throw TypeError('Cannot create a rendered block in a headless workspace');
}
this.workspace = workspace;
this.svgGroup = dom.createSvgElement(Svg.G, {});
if (prototypeName) {
dom.addClass(this.svgGroup, prototypeName);
}
/** A block style object. */
this.style = workspace.getRenderer().getConstants().getBlockStyle(null);
/** The renderer's path object. */
this.pathObject = workspace
.getRenderer()
.makePathObject(this.svgGroup, this.style);
const svgPath = this.pathObject.svgPath;
(svgPath as any).tooltip = this;
Tooltip.bindMouseEvents(svgPath);
// Expose this block's ID on its top-level SVG group.
this.svgGroup.setAttribute('data-id', this.id);
// The page-wide unique ID of this Block used for focusing.
svgPath.id = idGenerator.getNextUniqueId();
this.doInit_();
}
/**
* Create and initialize the SVG representation of the block.
* May be called more than once.
*/
initSvg() {
if (this.initialized) return;
for (const input of this.inputList) {
input.init();
}
for (const icon of this.getIcons()) {
icon.initView(this.createIconPointerDownListener(icon));
icon.updateEditable();
}
this.applyColour();
this.pathObject.updateMovable(this.isMovable() || this.isInFlyout);
const svg = this.getSvgRoot();
if (svg) {
browserEvents.conditionalBind(svg, 'pointerdown', this, this.onMouseDown);
}
if (!svg.parentNode) {
this.workspace.getCanvas().appendChild(svg);
}
this.initialized = true;
}
/**
* Get the secondary colour of a block.
*
* @returns #RRGGBB string.
*/
getColourSecondary(): string {
return this.style.colourSecondary;
}
/**
* Get the tertiary colour of a block.
*
* @returns #RRGGBB string.
*/
getColourTertiary(): string {
return this.style.colourTertiary;
}
/** Selects this block. Highlights the block visually. */
select() {
this.addSelect();
common.fireSelectedEvent(this);
}
/** Unselects this block. Unhighlights the block visually. */
unselect() {
this.removeSelect();
common.fireSelectedEvent(null);
}
/**
* Sets the parent of this block to be a new block or null.
*
* @param newParent New parent block.
* @internal
*/
override setParent(newParent: this | null) {
const oldParent = this.parentBlock_;
if (newParent === oldParent) {
return;
}
dom.startTextWidthCache();
super.setParent(newParent);
dom.stopTextWidthCache();
const svgRoot = this.getSvgRoot();
// Bail early if workspace is clearing, or we aren't rendered.
// We won't need to reattach ourselves anywhere.
if (this.workspace.isClearing || !svgRoot) {
return;
}
const oldXY = this.getRelativeToSurfaceXY();
const focusedNode = getFocusManager().getFocusedNode();
const restoreFocus = this.getSvgRoot().contains(
focusedNode?.getFocusableElement() ?? null,
);
if (newParent) {
(newParent as BlockSvg).getSvgRoot().appendChild(svgRoot);
// appendChild() clears focus state, so re-focus the previously focused
// node in case it was this block and would otherwise lose its focus. Once
// Element.moveBefore() has better browser support, it should be used
// instead.
if (restoreFocus && focusedNode) {
getFocusManager().focusNode(focusedNode);
}
} else if (oldParent) {
// If we are losing a parent, we want to move our DOM element to the
// root of the workspace. Try to insert it before any top-level
// block being dragged, but note that blocks can have the
// blocklyDragging class even if they're not top blocks (especially
// at start and end of a drag).
const draggingBlockElement = this.workspace
.getCanvas()
.querySelector('.blocklyDragging');
const draggingParentElement = draggingBlockElement?.parentElement as
| SVGElement
| null
| undefined;
const canvas = this.workspace.getCanvas();
if (draggingParentElement === canvas) {
canvas.insertBefore(svgRoot, draggingBlockElement);
} else {
canvas.appendChild(svgRoot);
// appendChild() clears focus state, so re-focus the previously focused
// node in case it was this block and would otherwise lose its focus. Once
// Element.moveBefore() has better browser support, it should be used
// instead.
if (restoreFocus && focusedNode) {
getFocusManager().focusNode(focusedNode);
}
}
this.translate(oldXY.x, oldXY.y);
}
this.applyColour();
}
/**
* Return the coordinates of the top-left corner of this block relative to the
* drawing surface's origin (0,0), in workspace units.
* If the block is on the workspace, (0, 0) is the origin of the workspace
* coordinate system.
* This does not change with workspace scale.
*
* @returns Object with .x and .y properties in workspace coordinates.
*/
override getRelativeToSurfaceXY(): Coordinate {
const layerManger = this.workspace.getLayerManager();
if (!layerManger) {
throw new Error(
'Cannot calculate position because the workspace has not been appended',
);
}
let x = 0;
let y = 0;
let element: SVGElement = this.getSvgRoot();
if (element) {
do {
// Loop through this block and every parent.
const xy = svgMath.getRelativeXY(element);
x += xy.x;
y += xy.y;
element = element.parentNode as SVGElement;
} while (element && !layerManger.hasLayer(element));
}
return new Coordinate(x, y);
}
/**
* Move a block by a relative offset.
*
* @param dx Horizontal offset in workspace units.
* @param dy Vertical offset in workspace units.
* @param reason Why is this move happening? 'drag', 'bump', 'snap', ...
*/
override moveBy(dx: number, dy: number, reason?: string[]) {
if (this.parentBlock_) {
throw Error('Block has parent');
}
const eventsEnabled = eventUtils.isEnabled();
let event: BlockMove | null = null;
if (eventsEnabled) {
event = new (eventUtils.get(EventType.BLOCK_MOVE)!)(this) as BlockMove;
if (reason) event.setReason(reason);
}
const delta = new Coordinate(dx, dy);
const currLoc = this.getRelativeToSurfaceXY();
const newLoc = Coordinate.sum(currLoc, delta);
this.translate(newLoc.x, newLoc.y);
this.updateComponentLocations(newLoc);
if (eventsEnabled && event) {
event!.recordNew();
eventUtils.fire(event);
}
this.workspace.resizeContents();
}
/**
* Transforms a block by setting the translation on the transform attribute
* of the block's SVG.
*
* @param x The x coordinate of the translation in workspace units.
* @param y The y coordinate of the translation in workspace units.
*/
translate(x: number, y: number) {
this.translation = `translate(${x}, ${y})`;
this.relativeCoords = new Coordinate(x, y);
this.getSvgRoot().setAttribute('transform', this.getTranslation());
}
/**
* Returns the SVG translation of this block.
*
* @internal
*/
getTranslation(): string {
return this.translation;
}
/**
* Move a block to a position.
*
* @param xy The position to move to in workspace units.
* @param reason Why is this move happening? 'drag', 'bump', 'snap', ...
*/
moveTo(xy: Coordinate, reason?: string[]) {
const curXY = this.getRelativeToSurfaceXY();
this.moveBy(xy.x - curXY.x, xy.y - curXY.y, reason);
}
/**
* Move this block during a drag.
* This block must be a top-level block.
*
* @param newLoc The location to translate to, in workspace coordinates.
* @internal
*/
moveDuringDrag(newLoc: Coordinate) {
this.translate(newLoc.x, newLoc.y);
this.getSvgRoot().setAttribute('transform', this.getTranslation());
this.updateComponentLocations(newLoc);
}
/** Snap this block to the nearest grid point. */
snapToGrid() {
if (this.isDeadOrDying()) return;
if (this.getParent()) return;
if (this.isInFlyout) return;
const grid = this.workspace.getGrid();
if (!grid?.shouldSnap()) return;
const currentXY = this.getRelativeToSurfaceXY();
const alignedXY = grid.alignXY(currentXY);
if (alignedXY !== currentXY) {
this.moveTo(alignedXY, ['snap']);
}
}
/**
* Returns the coordinates of a bounding box describing the dimensions of this
* block and any blocks stacked below it.
* Coordinate system: workspace coordinates.
*
* @returns Object with coordinates of the bounding box.
*/
getBoundingRectangle(): Rect {
return this.getBoundingRectangleWithDimensions(this.getHeightWidth());
}
/**
* Returns the coordinates of a bounding box describing the dimensions of this
* block alone.
* Coordinate system: workspace coordinates.
*
* @returns Object with coordinates of the bounding box.
*/
getBoundingRectangleWithoutChildren(): Rect {
return this.getBoundingRectangleWithDimensions({
height: this.height,
width: this.childlessWidth,
});
}
private getBoundingRectangleWithDimensions(blockBounds: {
height: number;
width: number;
}) {
const blockXY = this.getRelativeToSurfaceXY();
let left;
let right;
if (this.RTL) {
left = blockXY.x - blockBounds.width;
right = blockXY.x;
} else {
left = blockXY.x;
right = blockXY.x + blockBounds.width;
}
return new Rect(blockXY.y, blockXY.y + blockBounds.height, left, right);
}
/**
* Notify every input on this block to mark its fields as dirty.
* A dirty field is a field that needs to be re-rendered.
*/
markDirty() {
this.pathObject.constants = this.workspace.getRenderer().getConstants();
for (let i = 0, input; (input = this.inputList[i]); i++) {
input.markDirty();
}
}
/**
* Set whether the block is collapsed or not.
*
* @param collapsed True if collapsed.
*/
override setCollapsed(collapsed: boolean) {
if (this.collapsed_ === collapsed) {
return;
}
super.setCollapsed(collapsed);
this.updateCollapsed();
}
/**
* Traverses child blocks to see if any of them have a warning.
*
* @returns true if any child has a warning, false otherwise.
*/
private childHasWarning(): boolean {
const children = this.getChildren(false);
for (const child of children) {
if (child.getIcon(WarningIcon.TYPE) || child.childHasWarning()) {
return true;
}
}
return false;
}
/**
* Makes sure that when the block is collapsed, it is rendered correctly
* for that state.
*/
private updateCollapsed() {
const collapsed = this.isCollapsed();
const collapsedInputName = constants.COLLAPSED_INPUT_NAME;
const collapsedFieldName = constants.COLLAPSED_FIELD_NAME;
for (let i = 0, input; (input = this.inputList[i]); i++) {
if (input.name !== collapsedInputName) {
input.setVisible(!collapsed);
}
}
for (const icon of this.getIcons()) {
icon.updateCollapsed();
}
if (!collapsed) {
this.updateDisabled();
this.removeInput(collapsedInputName);
dom.removeClass(this.svgGroup, 'blocklyCollapsed');
this.setWarningText(null, BlockSvg.COLLAPSED_WARNING_ID);
return;
}
dom.addClass(this.svgGroup, 'blocklyCollapsed');
if (this.childHasWarning()) {
this.setWarningText(
Msg['COLLAPSED_WARNINGS_WARNING'],
BlockSvg.COLLAPSED_WARNING_ID,
);
}
const text = this.toString(internalConstants.COLLAPSE_CHARS);
const field = this.getField(collapsedFieldName);
if (field) {
field.setValue(text);
return;
}
const input =
this.getInput(collapsedInputName) ||
this.appendDummyInput(collapsedInputName);
input.appendField(new FieldLabel(text), collapsedFieldName);
}
/**
* Handle a pointerdown on an SVG block.
*
* @param e Pointer down event.
*/
private onMouseDown(e: PointerEvent) {
if (this.workspace.isReadOnly()) return;
const gesture = this.workspace.getGesture(e);
if (gesture) {
gesture.handleBlockStart(e, this);
}
}
/**
* Load the block's help page in a new window.
*
* @internal
*/
showHelp() {
const url =
typeof this.helpUrl === 'function' ? this.helpUrl() : this.helpUrl;
if (url) {
window.open(url);
}
}
/**
* Generate the context menu for this block.
*
* @returns Context menu options or null if no menu.
*/
protected generateContextMenu(
e: Event,
): Array<ContextMenuOption | LegacyContextMenuOption> | null {
if (this.workspace.isReadOnly() || !this.contextMenu) {
return null;
}
const menuOptions = ContextMenuRegistry.registry.getContextMenuOptions(
{block: this, focusedNode: this},
e,
);
// Allow the block to add or modify menuOptions.
if (this.customContextMenu) {
this.customContextMenu(menuOptions);
}
return menuOptions;
}
/**
* Gets the location in which to show the context menu for this block.
* Use the location of a click if the block was clicked, or a location
* based on the block's fields otherwise.
*/
protected calculateContextMenuLocation(e: Event): Coordinate {
// Open the menu where the user clicked, if they clicked
if (e instanceof PointerEvent) {
return new Coordinate(e.clientX, e.clientY);
}
// Otherwise, calculate a location.
// Get the location of the top-left corner of the block in
// screen coordinates.
const blockCoords = svgMath.wsToScreenCoordinates(
this.workspace,
this.getRelativeToSurfaceXY(),
);
// Prefer a y position below the first field in the block.
const fieldBoundingClientRect = this.inputList
.filter((input) => input.isVisible())
.flatMap((input) => input.fieldRow)
.find((f) => f.isVisible())
?.getSvgRoot()
?.getBoundingClientRect();
const y =
fieldBoundingClientRect && fieldBoundingClientRect.height
? fieldBoundingClientRect.y + fieldBoundingClientRect.height
: blockCoords.y + this.height;
return new Coordinate(
this.RTL ? blockCoords.x - 5 : blockCoords.x + 5,
y + 5,
);
}
/**
* Show the context menu for this block.
*
* @param e Mouse event.
* @internal
*/
showContextMenu(e: Event) {
const menuOptions = this.generateContextMenu(e);
const location = this.calculateContextMenuLocation(e);
if (menuOptions && menuOptions.length) {
ContextMenu.show(e, menuOptions, this.RTL, this.workspace, location);
ContextMenu.setCurrentBlock(this);
}
}
/**
* Updates the locations of any parts of the block that need to know where
* they are (e.g. connections, icons).
*
* @param blockOrigin The top-left of this block in workspace coordinates.
* @internal
*/
updateComponentLocations(blockOrigin: Coordinate) {
if (!this.dragging) this.updateConnectionLocations(blockOrigin);
this.updateIconLocations(blockOrigin);
this.updateFieldLocations(blockOrigin);
for (const child of this.getChildren(false)) {
child.updateComponentLocations(
Coordinate.sum(blockOrigin, child.relativeCoords),
);
}
}
private updateConnectionLocations(blockOrigin: Coordinate) {
for (const conn of this.getConnections_(false)) {
conn.moveToOffset(blockOrigin);
}
}
private updateIconLocations(blockOrigin: Coordinate) {
for (const icon of this.getIcons()) {
icon.onLocationChange(blockOrigin);
}
}
private updateFieldLocations(blockOrigin: Coordinate) {
for (const input of this.inputList) {
for (const field of input.fieldRow) {
field.onLocationChange(blockOrigin);
}
}
}
/**
* Add a CSS class to the SVG group of this block.
*
* @param className
*/
addClass(className: string) {
dom.addClass(this.svgGroup, className);
}
/**
* Remove a CSS class from the SVG group of this block.
*
* @param className
*/
removeClass(className: string) {
dom.removeClass(this.svgGroup, className);
}
/**
* Recursively adds or removes the dragging class to this node and its
* children.
*
* @param adding True if adding, false if removing.
* @internal
*/
setDragging(adding: boolean) {
this.dragging = adding;
if (adding) {
this.translation = '';
common.draggingConnections.push(...this.getConnections_(true));
this.addClass('blocklyDragging');
} else {
common.draggingConnections.length = 0;
this.removeClass('blocklyDragging');
}
// Recurse through all blocks attached under this one.
for (let i = 0; i < this.childBlocks_.length; i++) {
(this.childBlocks_[i] as BlockSvg).setDragging(adding);
}
}
/**
* Set whether this block is movable or not.
*
* @param movable True if movable.
*/
override setMovable(movable: boolean) {
super.setMovable(movable);
this.pathObject.updateMovable(movable);
}
/**
* Set whether this block is editable or not.
*
* @param editable True if editable.
*/
override setEditable(editable: boolean) {
super.setEditable(editable);
if (editable) {
dom.removeClass(this.svgGroup, 'blocklyNotEditable');
} else {
dom.addClass(this.svgGroup, 'blocklyNotEditable');
}
const icons = this.getIcons();
for (let i = 0; i < icons.length; i++) {
icons[i].updateEditable();
}
}
/**
* Sets whether this block is a shadow block or not.
* This method is internal and should not be called by users of Blockly. To
* create shadow blocks programmatically call connection.setShadowState
*
* @param shadow True if a shadow.
* @internal
*/
override setShadow(shadow: boolean) {
super.setShadow(shadow);
this.applyColour();
}
/**
* Set whether this block is an insertion marker block or not.
* Once set this cannot be unset.
*
* @param insertionMarker True if an insertion marker.
* @internal
*/
override setInsertionMarker(insertionMarker: boolean) {
if (this.isInsertionMarker_ === insertionMarker) {
return; // No change.
}
this.isInsertionMarker_ = insertionMarker;
if (this.isInsertionMarker_) {
this.setColour(
this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR,
);
this.pathObject.updateInsertionMarker(true);
}
}
/**
* Return the root node of the SVG or null if none exists.
*
* @returns The root SVG node (probably a group).
*/
getSvgRoot(): SVGGElement {
return this.svgGroup;
}
/**
* Dispose of this block.
*
* @param healStack If true, then try to heal any gap by connecting the next
* statement with the previous statement. Otherwise, dispose of all
* children of this block.
* @param animate If true, show a disposal animation and sound.
*/
override dispose(healStack?: boolean, animate?: boolean) {
this.disposing = true;
Tooltip.dispose();
ContextMenu.hide();
// If this block (or a descendant) was focused, focus its parent or
// workspace instead.
const focusManager = getFocusManager();
if (
this.getSvgRoot().contains(
focusManager.getFocusedNode()?.getFocusableElement() ?? null,
)
) {
let parent: BlockSvg | undefined | null = this.getParent();
if (!parent) {
// In some cases, blocks are disconnected from their parents before
// being deleted. Attempt to infer if there was a parent by checking
// for a connection within a radius of 0. Even if this wasn't a parent,
// it must be adjacent to this block and so is as good an option as any
// to focus after deleting.
const connection = this.outputConnection ?? this.previousConnection;
if (connection) {
const targetConnection = connection.closest(
0,
new Coordinate(0, 0),
).connection;
parent = targetConnection?.getSourceBlock();
}
}
if (parent) {
focusManager.focusNode(parent);
} else {
setTimeout(() => focusManager.focusTree(this.workspace), 0);
}
}
if (animate) {
this.unplug(healStack);
blockAnimations.disposeUiEffect(this);
}
super.dispose(!!healStack);
dom.removeNode(this.svgGroup);
}
/**
* Disposes of this block without doing things required by the top block.
* E.g. does trigger UI effects, remove nodes, etc.
*/
override disposeInternal() {
this.disposing = true;
super.disposeInternal();
if (getFocusManager().getFocusedNode() === this) {
this.workspace.cancelCurrentGesture();
}
[...this.warningTextDb.values()].forEach((n) => clearTimeout(n));
this.warningTextDb.clear();
this.getIcons().forEach((i) => i.dispose());
}
/**
* Delete a block and hide chaff when doing so. The block will not be deleted
* if it's in a flyout. This is called from the context menu and keyboard
* shortcuts as the full delete action. If you are disposing of a block from
* the workspace and don't need to perform flyout checks, handle event
* grouping, or hide chaff, then use `block.dispose()` directly.
*/
checkAndDelete() {
if (this.workspace.isFlyout) {
return;
}
eventUtils.setGroup(true);
this.workspace.hideChaff();
if (this.outputConnection) {
// Do not attempt to heal rows
// (https://github.com/google/blockly/issues/4832)
this.dispose(false, true);
} else {
this.dispose(/* heal */ true, true);
}
eventUtils.setGroup(false);
}
/**
* Encode a block for copying.
*
* @param addNextBlocks If true, copy subsequent blocks attached to this one
* as well.
*
* @returns Copy metadata, or null if the block is an insertion marker.
*/
toCopyData(addNextBlocks = false): BlockCopyData | null {
if (this.isInsertionMarker_) {
return null;
}
return {
paster: BlockPaster.TYPE,
blockState: blocks.save(this, {
addCoordinates: true,
addNextBlocks,
saveIds: false,
}) as blocks.State,
typeCounts: common.getBlockTypeCounts(this, true),
};
}
/**
* Updates the colour of the block to match the block's state.
*
* @internal
*/
applyColour() {
this.pathObject.applyColour?.(this);
const icons = this.getIcons();
for (let i = 0; i < icons.length; i++) {
icons[i].applyColour();
}
for (const field of this.getFields()) {
field.applyColour();
}
}
/**
* Updates the colour of the block (and children) to match the current
* disabled state.
*
* @internal
*/
updateDisabled() {
const disabled = !this.isEnabled() || this.getInheritedDisabled();