-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathrendered_connection.ts
More file actions
692 lines (631 loc) · 22.3 KB
/
Copy pathrendered_connection.ts
File metadata and controls
692 lines (631 loc) · 22.3 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
/**
* @license
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Components for creating connections between blocks.
*
* @class
*/
// Former goog.module ID: Blockly.RenderedConnection
import type {Block} from './block.js';
import type {BlockSvg} from './block_svg.js';
import {config} from './config.js';
import {Connection} from './connection.js';
import type {ConnectionDB} from './connection_db.js';
import {ConnectionType} from './connection_type.js';
import * as ContextMenu from './contextmenu.js';
import {ContextMenuRegistry} from './contextmenu_registry.js';
import * as eventUtils from './events/utils.js';
import {IContextMenu} from './interfaces/i_contextmenu.js';
import type {IFocusableNode} from './interfaces/i_focusable_node.js';
import type {IFocusableTree} from './interfaces/i_focusable_tree.js';
import {hasBubble} from './interfaces/i_has_bubble.js';
import * as internalConstants from './internal_constants.js';
import {Coordinate} from './utils/coordinate.js';
import * as svgMath from './utils/svg_math.js';
import {WorkspaceSvg} from './workspace_svg.js';
/** Maximum randomness in workspace units for bumping a block. */
const BUMP_RANDOMNESS = 10;
/**
* Class for a connection between blocks that may be rendered on screen.
*/
export class RenderedConnection
extends Connection
implements IContextMenu, IFocusableNode
{
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
sourceBlock_!: BlockSvg;
private readonly db: ConnectionDB;
private readonly dbOpposite: ConnectionDB;
private readonly offsetInBlock: Coordinate;
private trackedState: TrackedState;
private highlighted: boolean = false;
/** Connection this connection connects to. Null if not connected. */
override targetConnection: RenderedConnection | null = null;
/**
* @param source The block establishing this connection.
* @param type The type of the connection.
*/
constructor(source: BlockSvg, type: number) {
super(source, type);
/**
* Connection database for connections of this type on the current
* workspace.
*/
this.db = source.workspace.connectionDBList[type];
/**
* Connection database for connections compatible with this type on the
* current workspace.
*/
this.dbOpposite =
source.workspace.connectionDBList[internalConstants.OPPOSITE_TYPE[type]];
/** Workspace units, (0, 0) is top left of block. */
this.offsetInBlock = new Coordinate(0, 0);
/** Describes the state of this connection's tracked-ness. */
this.trackedState = RenderedConnection.TrackedState.WILL_TRACK;
}
/**
* Dispose of this connection. Remove it from the database (if it is
* tracked) and call the super-function to deal with connected blocks.
*
* @internal
*/
override dispose() {
super.dispose();
if (this.trackedState === RenderedConnection.TrackedState.TRACKED) {
this.db.removeConnection(this, this.y);
}
this.sourceBlock_.pathObject.removeConnectionHighlight?.(this);
}
/**
* Get the source block for this connection.
*
* @returns The source block.
*/
override getSourceBlock(): BlockSvg {
return super.getSourceBlock() as BlockSvg;
}
/**
* Returns the block that this connection connects to.
*
* @returns The connected block or null if none is connected.
*/
override targetBlock(): BlockSvg | null {
return super.targetBlock() as BlockSvg;
}
/**
* Returns the distance between this connection and another connection in
* workspace units.
*
* @param otherConnection The other connection to measure the distance to.
* @returns The distance between connections, in workspace units.
*/
distanceFrom(otherConnection: Connection): number {
const xDiff = this.x - otherConnection.x;
const yDiff = this.y - otherConnection.y;
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
/**
* Move the block(s) belonging to the connection to a point where they don't
* visually interfere with the specified connection.
*
* @param superiorConnection The connection to move away from. The provided
* connection should be the superior connection and should not be
* connected to this connection.
* @param initiatedByThis Whether or not the block group that was manipulated
* recently causing bump checks is associated with the inferior
* connection. Defaults to false.
* @internal
*/
bumpAwayFrom(
superiorConnection: RenderedConnection,
initiatedByThis = false,
) {
if (this.sourceBlock_.workspace.isDragging()) {
// Don't move blocks around while the user is doing the same.
return;
}
let offsetX =
config.snapRadius + Math.floor(Math.random() * BUMP_RANDOMNESS);
let offsetY =
config.snapRadius + Math.floor(Math.random() * BUMP_RANDOMNESS);
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
const inferiorConnection = this;
const superiorRootBlock = superiorConnection.sourceBlock_.getRootBlock();
const inferiorRootBlock = inferiorConnection.sourceBlock_.getRootBlock();
if (superiorRootBlock.isInFlyout || inferiorRootBlock.isInFlyout) {
// Don't move blocks around in a flyout.
return;
}
let moveInferior = true;
if (!inferiorRootBlock.isMovable()) {
// Can't bump an immovable block away.
// Check to see if the other block is movable.
if (!superiorRootBlock.isMovable()) {
// Neither block is movable, abort operation.
return;
} else {
// Only the superior block group is movable.
moveInferior = false;
// The superior block group moves in the opposite direction.
offsetX = -offsetX;
offsetY = -offsetY;
}
} else if (superiorRootBlock.isMovable()) {
// Both block groups are movable. The one on the inferior side will be
// moved to make space for the superior one. However, it's possible that
// both groups of blocks have an inferior connection that bumps into a
// superior connection on the other group, which could result in both
// groups moving in the same direction and eventually bumping each other
// again. It would be better if one group of blocks could consistently
// move in an orthogonal direction from the other, so that they become
// separated in the end. We can designate one group the "initiator" if
// it's the one that was most recently manipulated, causing inputs to be
// checked for bumpable neighbors. As a useful heuristic, in the case
// where the inferior connection belongs to the initiator group, moving it
// in the orthogonal direction will separate the blocks better.
if (initiatedByThis) {
offsetY = -offsetY;
}
}
const staticConnection = moveInferior
? superiorConnection
: inferiorConnection;
const dynamicConnection = moveInferior
? inferiorConnection
: superiorConnection;
const dynamicRootBlock = moveInferior
? inferiorRootBlock
: superiorRootBlock;
// Raise it to the top for extra visibility.
if (dynamicRootBlock.RTL) {
offsetX = -offsetX;
}
const dx = staticConnection.x + offsetX - dynamicConnection.x;
const dy = staticConnection.y + offsetY - dynamicConnection.y;
dynamicRootBlock.moveBy(dx, dy, ['bump']);
}
/**
* Change the connection's coordinates.
*
* @param x New absolute x coordinate, in workspace coordinates.
* @param y New absolute y coordinate, in workspace coordinates.
* @returns True if the position of the connection in the connection db
* was updated.
*/
moveTo(x: number, y: number): boolean {
// TODO(#6922): Readd this optimization.
// const moved = this.x !== x || this.y !== y;
const moved = true;
let updated = false;
if (this.trackedState === RenderedConnection.TrackedState.WILL_TRACK) {
this.db.addConnection(this, y);
this.trackedState = RenderedConnection.TrackedState.TRACKED;
updated = true;
} else if (
this.trackedState === RenderedConnection.TrackedState.TRACKED &&
moved
) {
this.db.removeConnection(this, this.y);
this.db.addConnection(this, y);
updated = true;
}
this.x = x;
this.y = y;
return updated;
}
/**
* Change the connection's coordinates.
*
* @param dx Change to x coordinate, in workspace units.
* @param dy Change to y coordinate, in workspace units.
* @returns True if the position of the connection in the connection db
* was updated.
*/
moveBy(dx: number, dy: number): boolean {
return this.moveTo(this.x + dx, this.y + dy);
}
/**
* Move this connection to the location given by its offset within the block
* and the location of the block's top left corner.
*
* @param blockTL The location of the top left corner of the block, in
* workspace coordinates.
* @returns True if the position of the connection in the connection db
* was updated.
*/
moveToOffset(blockTL: Coordinate): boolean {
return this.moveTo(
blockTL.x + this.offsetInBlock.x,
blockTL.y + this.offsetInBlock.y,
);
}
/**
* Set the offset of this connection relative to the top left of its block.
*
* @param x The new relative x, in workspace units.
* @param y The new relative y, in workspace units.
*/
setOffsetInBlock(x: number, y: number) {
this.offsetInBlock.x = x;
this.offsetInBlock.y = y;
}
/**
* Get the offset of this connection relative to the top left of its block.
*
* @returns The offset of the connection.
*/
getOffsetInBlock(): Coordinate {
return this.offsetInBlock;
}
/**
* Moves the blocks on either side of this connection right next to
* each other, based on their local offsets, not global positions.
*
* @internal
*/
tightenEfficiently() {
const target = this.targetConnection;
const block = this.targetBlock();
if (!target || !block) return;
const offset = Coordinate.difference(
this.offsetInBlock,
target.offsetInBlock,
);
block.translate(offset.x, offset.y);
}
/**
* Find the closest compatible connection to this connection.
* All parameters are in workspace units.
*
* @param maxLimit The maximum radius to another connection.
* @param dxy Offset between this connection's location in the database and
* the current location (as a result of dragging).
* @returns Contains two properties: 'connection' which is either another
* connection or null, and 'radius' which is the distance.
*/
closest(
maxLimit: number,
dxy: Coordinate,
): {connection: RenderedConnection | null; radius: number} {
return this.dbOpposite.searchForClosest(this, maxLimit, dxy);
}
/** Add highlighting around this connection. */
highlight() {
this.highlighted = true;
// Note that this needs to be done synchronously (vs. queuing a render pass)
// since only a displayed element can be focused, and this focusable node is
// implemented to make itself visible immediately prior to receiving DOM
// focus. It's expected that the connection's position should already be
// correct by this point (otherwise it will be corrected in a subsequent
// draw pass).
const highlightSvg = this.findHighlightSvg();
if (highlightSvg) {
highlightSvg.style.display = '';
highlightSvg.parentElement?.appendChild(highlightSvg);
}
}
/** Remove the highlighting around this connection. */
unhighlight() {
this.highlighted = false;
// Note that this is done synchronously for parity with highlight().
const highlightSvg = this.findHighlightSvg();
if (highlightSvg) {
highlightSvg.style.display = 'none';
}
}
/** Returns true if this connection is highlighted, false otherwise. */
isHighlighted(): boolean {
return this.highlighted;
}
/**
* Set whether this connections is tracked in the database or not.
*
* @param doTracking If true, start tracking. If false, stop tracking.
* @internal
*/
setTracking(doTracking: boolean) {
if (
(doTracking &&
this.trackedState === RenderedConnection.TrackedState.TRACKED) ||
(!doTracking &&
this.trackedState === RenderedConnection.TrackedState.UNTRACKED)
) {
return;
}
if (this.sourceBlock_.isInFlyout) {
// Don't bother maintaining a database of connections in a flyout.
return;
}
if (doTracking) {
this.db.addConnection(this, this.y);
this.trackedState = RenderedConnection.TrackedState.TRACKED;
return;
}
if (this.trackedState === RenderedConnection.TrackedState.TRACKED) {
this.db.removeConnection(this, this.y);
}
this.trackedState = RenderedConnection.TrackedState.UNTRACKED;
}
/**
* Stop tracking this connection, as well as all down-stream connections on
* any block attached to this connection. This happens when a block is
* collapsed.
*
* Also closes down-stream icons/bubbles.
*
* @internal
*/
stopTrackingAll() {
this.setTracking(false);
if (this.targetConnection) {
const blocks = this.targetBlock()!.getDescendants(false);
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
// Stop tracking connections of all children.
const connections = block.getConnections_(true);
for (let j = 0; j < connections.length; j++) {
connections[j].setTracking(false);
}
// Close all bubbles of all children.
for (const icon of block.getIcons()) {
if (hasBubble(icon)) icon.setBubbleVisible(false);
}
}
}
}
/**
* Start tracking this connection, as well as all down-stream connections on
* any block attached to this connection. This happens when a block is
* expanded.
*
* @returns List of blocks to render.
*/
startTrackingAll(): Block[] {
this.setTracking(true);
// All blocks that are not tracked must start tracking before any
// rendering takes place, since rendering requires knowing the dimensions
// of lower blocks. Also, since rendering a block renders all its parents,
// we only need to render the leaf nodes.
let renderList: Block[] = [];
if (
this.type !== ConnectionType.INPUT_VALUE &&
this.type !== ConnectionType.NEXT_STATEMENT
) {
// Only spider down.
return renderList;
}
const block = this.targetBlock();
if (block) {
let connections;
if (block.isCollapsed()) {
// This block should only be partially revealed since it is collapsed.
connections = [];
if (block.outputConnection) connections.push(block.outputConnection);
if (block.nextConnection) connections.push(block.nextConnection);
if (block.previousConnection)
connections.push(block.previousConnection);
} else {
// Show all connections of this block.
connections = block.getConnections_(true);
}
for (let i = 0; i < connections.length; i++) {
renderList.push(...connections[i].startTrackingAll());
}
if (!renderList.length) {
// Leaf block.
renderList = [block];
}
}
return renderList;
}
/**
* Behaviour after a connection attempt fails.
* Bumps this connection away from the other connection. Called when an
* attempted connection fails.
*
* @param superiorConnection Connection that this connection failed to connect
* to. The provided connection should be the superior connection.
* @internal
*/
override onFailedConnect(superiorConnection: Connection) {
const block = this.getSourceBlock();
if (eventUtils.getRecordUndo()) {
const group = eventUtils.getGroup();
setTimeout(
function (this: RenderedConnection) {
if (!block.isDisposed() && !block.getParent()) {
eventUtils.setGroup(group);
this.bumpAwayFrom(superiorConnection as RenderedConnection);
eventUtils.setGroup(false);
}
}.bind(this),
config.bumpDelay,
);
}
}
/**
* Disconnect two blocks that are connected by this connection.
*
* @param setParent Whether to set the parent of the disconnected block or
* not, defaults to true.
* If you do not set the parent, ensure that a subsequent action does,
* otherwise the view and model will be out of sync.
*/
override disconnectInternal(setParent = true) {
const {parentConnection, childConnection} =
this.getParentAndChildConnections();
if (!parentConnection || !childConnection) return;
const existingGroup = eventUtils.getGroup();
if (!existingGroup) eventUtils.setGroup(true);
const parent = parentConnection.getSourceBlock() as BlockSvg;
const child = childConnection.getSourceBlock() as BlockSvg;
super.disconnectInternal(setParent);
parent.queueRender();
child.updateDisabled();
child.queueRender();
// Reset visibility, since the child is now a top block.
child.getSvgRoot().style.display = 'block';
eventUtils.setGroup(existingGroup);
}
/**
* Respawn the shadow block if there was one connected to the this connection.
* Render/rerender blocks as needed.
*/
protected override respawnShadow_() {
super.respawnShadow_();
const blockShadow = this.targetBlock();
if (!blockShadow) {
return;
}
blockShadow.initSvg();
blockShadow.queueRender();
}
/**
* Find all nearby compatible connections to this connection.
* Type checking does not apply, since this function is used for bumping.
*
* @param maxLimit The maximum radius to another connection, in workspace
* units.
* @returns List of connections.
* @internal
*/
override neighbours(maxLimit: number): RenderedConnection[] {
return this.dbOpposite.getNeighbours(this, maxLimit);
}
/**
* Connect two connections together. This is the connection on the superior
* block. Rerender blocks as needed.
*
* @param childConnection Connection on inferior block.
*/
protected override connect_(childConnection: Connection) {
super.connect_(childConnection);
const renderedChildConnection = childConnection as RenderedConnection;
const parentBlock = this.getSourceBlock();
const childBlock = renderedChildConnection.getSourceBlock();
parentBlock.updateDisabled();
childBlock.updateDisabled();
childBlock.queueRender();
// The input the child block is connected to (if any).
const parentInput = parentBlock.getInputWithBlock(childBlock);
if (parentInput) {
const visible = parentInput.isVisible();
childBlock.getSvgRoot().style.display = visible ? 'block' : 'none';
}
}
/**
* Function to be called when this connection's compatible types have changed.
*/
protected override onCheckChanged_() {
// The new value type may not be compatible with the existing connection.
if (
this.isConnected() &&
(!this.targetConnection ||
!this.getConnectionChecker().canConnect(
this,
this.targetConnection,
false,
))
) {
const child = this.isSuperior() ? this.targetBlock() : this.sourceBlock_;
child!.unplug();
}
}
/**
* Change a connection's compatibility.
* Rerender blocks as needed.
*
* @param check Compatible value type or list of value types. Null if all
* types are compatible.
* @returns The connection being modified (to allow chaining).
*/
override setCheck(check: string | string[] | null): RenderedConnection {
super.setCheck(check);
this.sourceBlock_.queueRender();
return this;
}
/**
* Handles showing the context menu when it is opened on a connection.
* Note that typically the context menu can't be opened with the mouse
* on a connection, because you can't select a connection. But keyboard
* users may open the context menu with a keyboard shortcut.
*
* @param e Event that triggered the opening of the context menu.
*/
showContextMenu(e: Event): void {
const menuOptions = ContextMenuRegistry.registry.getContextMenuOptions(
{focusedNode: this},
e,
);
if (!menuOptions.length) return;
const block = this.getSourceBlock();
const workspace = block.workspace;
let location;
if (e instanceof PointerEvent) {
location = new Coordinate(e.clientX, e.clientY);
} else {
const connectionWSCoords = new Coordinate(this.x, this.y);
const connectionScreenCoords = svgMath.wsToScreenCoordinates(
workspace,
connectionWSCoords,
);
location = connectionScreenCoords.translate(block.RTL ? -5 : 5, 5);
}
ContextMenu.show(e, menuOptions, block.RTL, workspace, location);
}
/** See IFocusableNode.getFocusableElement. */
getFocusableElement(): HTMLElement | SVGElement {
const highlightSvg = this.findHighlightSvg();
if (highlightSvg) return highlightSvg;
throw new Error('No highlight SVG found corresponding to this connection.');
}
/** See IFocusableNode.getFocusableTree. */
getFocusableTree(): IFocusableTree {
return this.getSourceBlock().workspace as WorkspaceSvg;
}
/** See IFocusableNode.onNodeFocus. */
onNodeFocus(): void {
this.highlight();
this.getSourceBlock().workspace.scrollBoundsIntoView(
this.getSourceBlock().getBoundingRectangleWithoutChildren(),
);
}
/** See IFocusableNode.onNodeBlur. */
onNodeBlur(): void {
this.unhighlight();
}
/** See IFocusableNode.canBeFocused. */
canBeFocused(): boolean {
return true;
}
private findHighlightSvg(): SVGPathElement | null {
// This cast is valid as TypeScript's definition is wrong. See:
// https://github.com/microsoft/TypeScript/issues/60996.
return document.getElementById(this.id) as
| unknown
| null as SVGPathElement | null;
}
}
export namespace RenderedConnection {
/**
* Enum for different kinds of tracked states.
*
* WILL_TRACK means that this connection will add itself to
* the db on the next moveTo call it receives.
*
* UNTRACKED means that this connection will not add
* itself to the database until setTracking(true) is explicitly called.
*
* TRACKED means that this connection is currently being tracked.
*/
export enum TrackedState {
WILL_TRACK = -1,
UNTRACKED = 0,
TRACKED = 1,
}
}
export type TrackedState = RenderedConnection.TrackedState;
export const TrackedState = RenderedConnection.TrackedState;