-
Notifications
You must be signed in to change notification settings - Fork 26
/
block.js
2948 lines (2712 loc) · 86.2 KB
/
block.js
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
/**
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview The class representing one block.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Block');
goog.require('Blockly.BlockSvg');
goog.require('Blockly.BlockSvgFramed');
goog.require('Blockly.BlockSvgFunctional');
goog.require('Blockly.Blocks');
goog.require('Blockly.Connection');
goog.require('Blockly.ContextMenu');
goog.require('Blockly.Input');
goog.require('Blockly.Msg');
goog.require('Blockly.Mutator');
goog.require('Blockly.Warning');
goog.require('Blockly.BlockSpace');
goog.require('Blockly.Xml');
goog.require('goog.asserts');
goog.require('goog.string');
/**
* Unique ID counter for created blocks.
* @private
*/
Blockly.uidCounter_ = 0;
/**
* Class for one block.
* @param {!Blockly.BlockSpace} blockSpace The new block's blockSpace.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @constructor
*/
Blockly.Block = function(blockSpace, prototypeName, htmlId) {
this.id = ++Blockly.uidCounter_;
this.htmlId = htmlId;
this.outputConnection = null;
this.nextConnection = null;
this.previousConnection = null;
this.inputList = [];
this.inputsInline = false;
this.rendered = false;
this.disabled = false;
this.tooltip = '';
this.contextMenu = true;
this.parentBlock_ = null;
this.childBlocks_ = [];
this.deletable_ = true;
this.movable_ = true;
this.editable_ = true;
this.userVisible_ = true;
this.nextConnectionDisabled_ = false;
this.collapsed_ = false;
this.dragging_ = false;
// Used to hide function blocks when not in modal workspace. This property
// is not serialized/deserialized.
this.currentlyHidden_ = false;
/**
* Whether this block is allowed to disconnect from its parent block.
* @private {boolean}
*/
this.canDisconnectFromParent_ = true;
/**
* The label which can be clicked to edit this block. This field is
* currently set only for functional_call blocks.
* @type {Blockly.FieldIcon}
*/
this.editLabel_ = null;
/**
* @type {!Blockly.BlockSpace}
*/
this.blockSpace = blockSpace;
this.isInFlyout = blockSpace.isFlyout;
this.colourSaturation_ = 0.45;
this.colourValue_ = 0.65;
this.fillPattern_ = null;
this.blockSvgClass_ = Blockly.BlockSvg;
this.customOptions_ = {};
/**
* Optional method to run just prior to disposing this block
* @type {?Function}
*/
this.beforeDispose = null;
this.setRenderBlockSpace(blockSpace);
// Copy the type-specific functions and data from the prototype.
if (prototypeName) {
this.type = prototypeName;
var prototype = Blockly.Blocks[prototypeName];
if (!prototype) {
Blockly.fireUiEvent(window, 'unknownBlock', {name: prototypeName});
prototype = Blockly.Blocks.unknown;
this.appendDummyInput().appendTitle('unknown: ' + prototypeName);
console.warn(
'Warning: "' + prototypeName + '" is an unknown language block.'
);
}
goog.mixin(this, prototype);
}
// Call an initialization function, if it exists.
if (goog.isFunction(this.init)) {
this.init();
}
if (
this.shouldHideIfInMainBlockSpace &&
this.shouldHideIfInMainBlockSpace() &&
this.blockSpace === Blockly.mainBlockSpace
) {
this.setCurrentlyHidden(true);
}
this.handleBlockLimitChanges();
/** @type {goog.events.EventTarget} */
this.blockEvents = new goog.events.EventTarget();
};
/**
* @enum {string}
*/
Blockly.Block.EVENTS = {
AFTER_DISPOSED: 'afterDisposed',
AFTER_DROPPED: 'afterDropped'
};
/**
* Pointer to SVG representation of the block.
* @type {Blockly.BlockSvg}
* @private
*/
Blockly.Block.prototype.svg_ = null;
/**
* Block's mutator icon (if any).
* @type {?Blockly.Mutator}
*/
Blockly.Block.prototype.mutator = null;
/**
* Block's warning icon (if any).
* @type {?Blockly.Warning}
*/
Blockly.Block.prototype.warning = null;
/**
* Callback function called after initialization
* (typically defined by subclasses)
* @type {?function()}
*/
Blockly.Block.prototype.init = null;
/**
* Callback function called after initialization
* (typically defined by subclasses)
* @type {?function()}
*/
Blockly.Block.prototype.onchange = null;
/**
* Update limit UI on block count changes.
*/
Blockly.Block.prototype.handleBlockLimitChanges = function() {
if (this.blockSpace && this.blockSpace.blockSpaceEditor) {
// Normally we want to show block limits in the flyout, but while editing
// blocks (e.g. in the Toolbox Blocks Editor), we'd like to show them in
// the main block space.
var shouldShowBlockLimits = Blockly.editBlocks
? !this.isInFlyout
: this.isInFlyout;
if (shouldShowBlockLimits) {
this.blockSpace.blockSpaceEditor.blockLimits.events.listen(
'change',
this.onBlockLimitChange.bind(this)
);
}
}
};
Blockly.Block.prototype.onBlockLimitChange = function(eventObject) {
if (eventObject.type !== this.type) {
return;
}
if (!this.svg_) {
return;
}
// When editing blocks, show full count. Otherwise, show remaining #.
var displayCount = Blockly.editBlocks
? eventObject.limit
: eventObject.remaining;
this.svg_.updateLimit(displayCount);
};
/**
* @param {Blockly.BlockSpace} blockSpace target blockspace to begin rendering on
*/
Blockly.Block.prototype.setRenderBlockSpace = function(blockSpace) {
this.blockSpace = blockSpace;
this.blockSpace.addTopBlock(this);
// Bind an onchange function if one exists (typically set by block subclasses)
if (goog.isFunction(this.onchange)) {
Blockly.bindEvent_(
this.blockSpace.getCanvas(),
'blocklyBlockSpaceChange',
this,
this.onchange
);
}
};
/**
* Returns a list of mutator and warning icons.
* @return {!Array} List of icons.
*/
Blockly.Block.prototype.getIcons = function() {
var icons = [];
if (this.mutator) {
icons.push(this.mutator);
}
if (this.warning) {
icons.push(this.warning);
}
return icons;
};
/**
* Create and initialize the SVG representation of the block.
*/
Blockly.Block.prototype.initSvg = function() {
this.svg_ = new this.blockSvgClass_(this, this.customOptions_);
this.svg_.init();
if (!this.blockSpace.isReadOnly()) {
Blockly.bindEvent_(
this.svg_.getRootElement(),
'mousedown',
this,
this.onMouseDown_
);
Blockly.bindEvent_(
this.svg_.getRootElement(),
'focus',
this,
this.select.bind(this, false)
);
}
this.setCurrentlyHidden(this.currentlyHidden_);
this.moveToFrontOfMainCanvas_();
this.setIsUnused();
if (this.miniFlyoutBlocks) {
this.miniFlyout = new Blockly.HorizontalFlyout(
this.blockSpace.blockSpaceEditor
);
this.miniFlyout.targetBlockSpace_ = this.blockSpace;
var dom = this.miniFlyout.createDom(true);
this.svg_.getRootElement().appendChild(dom);
this.miniFlyout.show(this.miniFlyoutBlocks);
this.miniFlyout.softHide();
}
};
/**
* Create a mini-flyout with the given set of blocks.
*/
Blockly.Block.prototype.initMiniFlyout = function(blockString) {
var root = Blockly.Xml.textToDom(blockString);
// Use childNodes, not children, for IE compatibility
var childNodes = root.childNodes;
var blockList = [];
for (var i = 0; i < childNodes.length; i++) {
var node = childNodes[i];
if (node.nodeName === 'block') {
blockList.push(node);
}
}
this.miniFlyoutBlocks = blockList;
};
/**
* Return the root node of the SVG or null if none exists.
* @return {Element} The root SVG node (probably a group).
*/
Blockly.Block.prototype.getSvgRoot = function() {
return this.svg_ && this.svg_.getRootElement();
};
Blockly.Block.DRAG_MODE_NOT_DRAGGING = 0;
Blockly.Block.DRAG_MODE_INSIDE_STICKY_RADIUS = 1;
Blockly.Block.DRAG_MODE_FREELY_DRAGGING = 2;
/**
* Is the mouse dragging a block?
* 0 - No drag operation.
* 1 - Still inside the sticky DRAG_RADIUS.
* 2 - Freely draggable.
* @private
*/
Blockly.Block.dragMode_ = Blockly.Block.DRAG_MODE_NOT_DRAGGING;
Blockly.Block.isDragging = function() {
return Blockly.Block.dragMode_ !== Blockly.Block.DRAG_MODE_NOT_DRAGGING;
};
Blockly.Block.isFreelyDragging = function() {
return Blockly.Block.dragMode_ === Blockly.Block.DRAG_MODE_FREELY_DRAGGING;
};
/**
* Pretend that we've already started dragging a block. This ensures that any
* methods called between now and onMouseDown behave as though a block is being
* dragged, e.g. skipping neighbour bumping.
*/
Blockly.Block.startDragging = function() {
Blockly.Block.dragMode_ = Blockly.Block.DRAG_MODE_INSIDE_STICKY_RADIUS;
};
/**
* Wrapper function called when a mouseUp occurs during a drag operation.
* @type {BindData}
* @private
*/
Blockly.Block.onMouseUpWrapper_ = null;
/**
* Wrapper function called when a mouseMove occurs during a drag operation.
* @type {BindData}
* @private
*/
Blockly.Block.onMouseMoveWrapper_ = null;
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
Blockly.Block.terminateDrag_ = function() {
if (Blockly.Block.onMouseUpWrapper_) {
Blockly.unbindEvent_(Blockly.Block.onMouseUpWrapper_);
Blockly.Block.onMouseUpWrapper_ = null;
}
if (Blockly.Block.onMouseMoveWrapper_) {
Blockly.unbindEvent_(Blockly.Block.onMouseMoveWrapper_);
Blockly.Block.onMouseMoveWrapper_ = null;
}
var selected = Blockly.selected;
if (Blockly.Block.isFreelyDragging()) {
// Terminate a drag operation.
if (selected) {
selected.blockSpace.clearPickedUpBlockOrigin();
selected.blockSpace.stopAutoScrolling();
// Update the connection locations.
var xy = selected.getRelativeToSurfaceXY();
var dx = xy.x - selected.startDragX;
var dy = xy.y - selected.startDragY;
selected.moveConnections_(dx, dy);
delete selected.draggedBubbles_;
selected.setDragging_(false);
selected.moveToFrontOfMainCanvas_();
selected.render();
window.setTimeout(
selected.bumpNeighbours.bind(selected),
Blockly.BUMP_DELAY
);
selected.blockSpace.blockSpaceEditor.bumpBlocksIntoBlockSpace();
selected.blockSpace.scrollIntoView(selected);
// Fire an event to allow scrollbars to resize.
Blockly.fireUiEvent(window, 'resize');
}
}
// When we have a selected block, we should use its editor to run
// the cursor change so that the editor's SVG gets a cursor change
// as well.
if (selected) {
selected.blockSpace.fireChangeEvent();
selected.blockSpace.blockSpaceEditor.setCursor(Blockly.Css.Cursor.OPEN);
}
Blockly.Block.dragMode_ = Blockly.Block.DRAG_MODE_NOT_DRAGGING;
if (selected) {
selected.blockEvents.dispatchEvent(Blockly.Block.EVENTS.AFTER_DROPPED);
}
};
/**
* Select this block. Highlight it visually.
*/
Blockly.Block.prototype.select = function(spotlight) {
if (!this.svg_) {
throw 'Block is not rendered.';
}
if (Blockly.selected) {
// Unselect any previously selected block.
Blockly.selected.unselect();
}
Blockly.selected = this;
this.svg_.addSelect(!this.parentBlock_);
if (spotlight) {
this.svg_.addSpotlight();
}
Blockly.fireUiEvent(this.blockSpace.getCanvas(), 'blocklySelectChange');
};
/**
* Unselect this block. Remove its highlighting.
*/
Blockly.Block.prototype.unselect = function() {
if (Blockly.selected !== this) {
return;
}
if (!this.svg_) {
throw 'Block is not rendered.';
}
Blockly.BlockSpaceEditor.terminateDrag_();
Blockly.selected = null;
this.svg_.removeSelect();
this.svg_.removeSpotlight();
Blockly.fireUiEvent(this.blockSpace.getCanvas(), 'blocklySelectChange');
};
/**
* Whether this block can be copied, cut, and pasted.
* Can be overridden by individual block types.
* @returns {boolean}
*/
Blockly.Block.prototype.isCopyable = function() {
return true;
};
/**
* Dispose of this block.
* @param {boolean} 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 {boolean} animate If true, show a disposal animation and sound.
*/
Blockly.Block.prototype.dispose = function(healStack, animate) {
if (goog.isFunction(this.beforeDispose)) {
this.beforeDispose();
}
// Switch off rerendering.
this.rendered = false;
this.unplug(healStack);
if (animate && this.svg_) {
this.svg_.disposeUiEffect();
}
var updateBlockSpaceCallback = goog.bind(
this.blockSpace.updateScrollableSize,
this.blockSpace
);
// This block is now at the top of the blockSpace.
// Remove this block from the blockSpace's list of top-most blocks.
this.blockSpace.removeTopBlock(this);
this.blockSpace = null;
// Just deleting this block from the DOM would result in a memory leak as
// well as corruption of the connection database. Therefore we must
// methodically step through the blocks and carefully disassemble them.
if (Blockly.selected == this) {
Blockly.selected = null;
// If there's a drag in-progress, unlink the mouse events.
Blockly.BlockSpaceEditor.terminateDrag_();
}
// If this block has a context menu open, close it.
if (Blockly.ContextMenu.currentBlock == this) {
Blockly.ContextMenu.hide();
}
// First, dispose of all my children.
var x;
for (x = this.childBlocks_.length - 1; x >= 0; x--) {
this.childBlocks_[x].dispose(false);
}
// Then dispose of myself.
var icons = this.getIcons();
for (x = 0; x < icons.length; x++) {
icons[x].dispose();
}
// Dispose of all inputs and their titles.
var input;
for (x = 0; x < this.inputList.length; x++) {
input = this.inputList[x];
input.dispose();
}
this.inputList = [];
// Dispose of any remaining connections (next/previous/output).
var connections = this.getConnections_(true);
for (x = 0; x < connections.length; x++) {
var connection = connections[x];
if (connection.targetConnection) {
connection.disconnect();
}
connections[x].dispose();
}
// Dispose of the SVG and break circular references.
if (this.svg_) {
this.svg_.dispose();
this.svg_ = null;
}
this.blockEvents.dispatchEvent(Blockly.Block.EVENTS.AFTER_DISPOSED);
updateBlockSpaceCallback();
};
/**
* Unplug this block from its superior block. If this block is a statement,
* optionally reconnect the block underneath with the block on top.
* @param {boolean} healStack Disconnect child statement and reconnect stack.
* @param {boolean} bump Move the unplugged block sideways a short distance.
*/
Blockly.Block.prototype.unplug = function(healStack, bump) {
bump = bump && !!this.getParent();
if (this.outputConnection) {
if (this.outputConnection.targetConnection) {
// Disconnect from any superior block.
this.setParent(null);
}
} else {
var previousTarget = null;
if (this.previousConnection && this.previousConnection.targetConnection) {
// Remember the connection that any next statements need to connect to.
previousTarget = this.previousConnection.targetConnection;
// Detach this block from the parent's tree.
this.setParent(null);
}
if (
healStack &&
this.nextConnection &&
this.nextConnection.targetConnection
) {
// Disconnect the next statement.
var nextTarget = this.nextConnection.targetConnection;
var nextBlock = this.nextConnection.targetBlock();
nextBlock.setParent(null);
if (previousTarget) {
// Attach the next statement to the previous statement.
previousTarget.connect(nextTarget);
}
}
}
if (bump) {
// Bump the block sideways.
var dx = Blockly.SNAP_RADIUS * (Blockly.RTL ? -1 : 1);
var dy = Blockly.SNAP_RADIUS * 2;
this.moveBy(dx, dy);
}
};
/**
* Return the coordinates of the top-left corner of this block relative to the
* drawing surface's origin (0,0).
* @return {!Object} Object with .x and .y properties.
*/
Blockly.Block.prototype.getRelativeToSurfaceXY = function() {
var x = 0;
var y = 0;
var elementIsRootCanvas = false;
if (this.svg_) {
var element = this.svg_.getRootElement();
do {
// Loop through this block and every parent.
var xy = Blockly.getRelativeXY(element);
x += xy.x;
y += xy.y;
element = element.parentNode;
elementIsRootCanvas =
element == this.blockSpace.getCanvas() ||
element == this.blockSpace.getDragCanvas();
} while (element && !elementIsRootCanvas);
}
return {x: x, y: y};
};
/**
* Move a block to a specific location on the drawing surface.
* @param {number} x Horizontal location.
* @param {number} y Vertical location.
*/
Blockly.Block.prototype.moveTo = function(x, y) {
var oldXY = this.getRelativeToSurfaceXY();
this.svg_
.getRootElement()
.setAttribute('transform', 'translate(' + x + ', ' + y + ')');
this.moveConnections_(x - oldXY.x, y - oldXY.y);
};
/**
* Move a block by a relative offset.
* @param {number} dx Horizontal offset.
* @param {number} dy Vertical offset.
*/
Blockly.Block.prototype.moveBy = function(dx, dy) {
var xy = this.getRelativeToSurfaceXY();
this.svg_
.getRootElement()
.setAttribute(
'transform',
'translate(' + (xy.x + dx) + ', ' + (xy.y + dy) + ')'
);
this.moveConnections_(dx, dy);
};
/**
* Gets box dimensions of block
* @returns {goog.math.Box}
*/
Blockly.Block.prototype.getBox = function() {
var heightWidth = this.getHeightWidth();
var xy = this.getRelativeToSurfaceXY();
// Account for left notch
if (this.outputConnection) {
xy.x -= Blockly.BlockSvg.TAB_WIDTH;
}
return new goog.math.Box(
xy.y,
xy.x + heightWidth.width,
xy.y + heightWidth.height,
xy.x
);
};
/**
* Returns the padding of the SVG or null if none exists
* @return {Object} object with padding values for top, bottom, left, and right
*/
Blockly.Block.prototype.getSvgPadding = function() {
return this.svg_ && this.svg_.getPadding();
};
/**
* Returns a bounding box describing the dimensions of this block.
* @return {!Object} Object with height and width properties.
*/
Blockly.Block.prototype.getHeightWidth = function() {
var bBox;
try {
var ie10OrOlder = Blockly.ieVersion() && Blockly.ieVersion() <= 10;
var initialStyle;
if (ie10OrOlder) {
// Required to set display to inline during calculation in IE <= 10
initialStyle = this.getSvgRoot().style.display;
this.getSvgRoot().style.display = 'inline';
}
bBox = goog.object.clone(this.getSvgRoot().getBBox());
if (ie10OrOlder) {
// Reset to original display value
this.getSvgRoot().style.display = initialStyle;
}
} catch (e) {
// Firefox has trouble with hidden elements (Bug 528969).
return {height: 0, width: 0};
}
var expectedBBoxY = 0;
if (Blockly.BROKEN_CONTROL_POINTS) {
/* HACK:
WebKit bug 67298 causes control points to be included in the reported
bounding box. The render functions (below) add two 5px spacer control
points that we need to subtract.
*/
bBox.height -= 10;
if (this.nextConnection) {
// Bottom control point partially masked by lower tab.
bBox.height += 4;
}
/**
* We would expect bBox.y to be 0, but with broken control points,
* we'll expect it to be -5 (since we added an extra control point for
* measurement).
*/
expectedBBoxY = -5;
}
if (bBox.height > 0) {
// Subtract one from the height due to the shadow.
bBox.height -= 1;
}
/**
* When <text> or other child content's boundaries extend beyond tops of
* blocks (e.g. due to IE MSDN issue #791152), bBox.y ends up being < 0.
* Here we add bBox.y (which is otherwise typically 0) to the height to
* discount the above-block content distance.
*/
var bboxYDifference = bBox.y - expectedBBoxY;
var heightWithoutContentAboveTop = bBox.height + bboxYDifference;
bBox.height = Math.max(0, heightWithoutContentAboveTop);
return bBox;
};
/**
* Handle a mouse-down on an SVG block.
* @param {!Event} e Mouse down event.
* @private
*/
Blockly.Block.prototype.onMouseDown_ = function(e) {
// Stop the browser from scrolling/zooming the page
e.preventDefault();
// If we're clicking on an input target, don't do anything with the event
// at the block level
var targetClass = e.target.getAttribute && e.target.getAttribute('class');
if (targetClass === 'inputClickTarget') {
e.stopPropagation();
return;
}
// ...but this prevents blurring of inputs, so do it manually
document.activeElement &&
document.activeElement.blur &&
document.activeElement.blur();
if (this.isInFlyout) {
return;
}
// Update Blockly's knowledge of its own location.
this.blockSpace.blockSpaceEditor.svgResize();
Blockly.BlockSpaceEditor.terminateDrag_();
this.select();
this.blockSpace.blockSpaceEditor.hideChaff();
if (Blockly.isRightButton(e)) {
// Right-click.
// Only show context menus for level editors
if (Blockly.editBlocks) {
this.showContextMenu_(e);
}
} else if (
this.blockSpace.isMovementLocked() ||
!this.isMovable() ||
!this.canDisconnectFromParent()
) {
// Allow unmovable blocks to be selected and context menued, but not
// dragged. Let this event bubble up to document, so the blockSpace may be
// dragged instead.
return;
} else {
// Left-click (or middle click)
// If the block should duplicate on drag, duplicate the block, pass the click event
// to the duplicated block, and return from this block's click event
if (this.shouldCopyOnDrag()) {
var dup = this.duplicate_();
dup.setParentForCopyOnDrag(null);
dup.onMouseDown_(e);
return;
}
Blockly.removeAllRanges();
this.setIsUnused(false);
this.blockSpace.blockSpaceEditor.setCursor(Blockly.Css.Cursor.CLOSED);
// Look up the current translation and record it.
var xy = this.getRelativeToSurfaceXY();
this.startDragX = xy.x;
this.startDragY = xy.y;
// If we were given the start drag location, use that.
if (e.startDragMouseX_ !== undefined && e.startDragMouseY_ !== undefined) {
this.startDragMouseX = e.startDragMouseX_;
this.startDragMouseY = e.startDragMouseY_;
e.startDragMouseX_ = undefined;
e.startDragMouseY_ = undefined;
} else {
// Record the current mouse position.
this.startDragMouseX = e.clientX;
this.startDragMouseY = e.clientY;
}
Blockly.Block.dragMode_ = Blockly.Block.DRAG_MODE_INSIDE_STICKY_RADIUS;
Blockly.Block.onMouseUpWrapper_ = Blockly.bindEvent_(
document,
'mouseup',
this,
this.onMouseUp_
);
Blockly.Block.onMouseMoveWrapper_ = Blockly.bindEvent_(
document,
'mousemove',
this,
this.onMouseMove_
);
// Build a list of bubbles that need to be moved and where they started.
this.draggedBubbles_ = [];
var descendants = this.getDescendants();
for (var x = 0, descendant; (descendant = descendants[x]); x++) {
var icons = descendant.getIcons();
for (var y = 0; y < icons.length; y++) {
var data = icons[y].getIconLocation();
data.bubble = icons[y];
this.draggedBubbles_.push(data);
}
}
}
// This event has been handled. No need to bubble up to the document.
e.stopPropagation();
};
/**
* Handle a mouse-up anywhere in the SVG pane. Is only registered when a
* block is clicked. We can't use mouseUp on the block since a fast-moving
* cursor can briefly escape the block before it catches up.
* @param {!Event} e Mouse up event.
* @private
*/
Blockly.Block.prototype.onMouseUp_ = function(e) {
var thisBlockSpace = this.blockSpace;
Blockly.BlockSpaceEditor.terminateDrag_();
if (Blockly.selected && Blockly.highlightedConnection_) {
// Connect two blocks together.
Blockly.localConnection_.connect(Blockly.highlightedConnection_);
if (this.svg_) {
// Trigger a connection animation.
// Determine which connection is inferior (lower in the source stack).
var inferiorConnection;
if (Blockly.localConnection_.isSuperior()) {
inferiorConnection = Blockly.highlightedConnection_;
} else {
inferiorConnection = Blockly.localConnection_;
}
inferiorConnection.sourceBlock_.svg_.connectionUiEffect();
}
if (thisBlockSpace.trashcan) {
// Don't throw an object in the trash can if it just got connected.
thisBlockSpace.trashcan.close();
}
} else if (
Blockly.selected &&
Blockly.selected.areBlockAndDescendantsDeletable() &&
thisBlockSpace.isDeleteArea(e.clientX, e.clientY, this.startDragMouseX)
) {
// The ordering of the statement above is important because isDeleteArea()
// has a side effect of opening the trash can.
var trashcan = thisBlockSpace.trashcan;
if (trashcan) {
window.setTimeout(trashcan.close.bind(trashcan), 100);
}
Blockly.selected.dispose(false, true);
if (Blockly.topLevelProcedureAutopopulate && this.isFunctionDefinition()) {
window.setTimeout(function() {
thisBlockSpace.blockSpaceEditor.updateFlyout();
}, 0);
}
// Dropping a block on the trash can will usually cause the blockSpace to
// resize to contain the newly positioned block. Force a second resize now
// that the block has been deleted.
Blockly.fireUiEvent(window, 'resize');
}
if (Blockly.selected) {
Blockly.selected.setIsUnused();
var shadowBlocks = getShadowBlocksInStack(Blockly.selected);
shadowBlocks.forEach(function(block) {
var sourceBlock = block.blockToShadow_(block.getRootBlock());
block.shadowBlockValue_(sourceBlock);
});
}
if (Blockly.highlightedConnection_) {
Blockly.highlightedConnection_.unhighlight();
Blockly.highlightedConnection_ = null;
}
thisBlockSpace.hideDelete();
thisBlockSpace.blockSpaceEditor.setCursor(Blockly.Css.Cursor.OPEN);
};
/**
* Load the block's help page in a new window.
* @private
*/
Blockly.Block.prototype.showHelp_ = function() {
var url = goog.isFunction(this.helpUrl) ? this.helpUrl() : this.helpUrl;
if (url) {
window.open(url);
}
};
/**
* Duplicate this block and its children.
* @return {!Blockly.Block} The duplicate.
* @private
*/
Blockly.Block.prototype.duplicate_ = function() {
// Create a duplicate via XML.
var xmlBlock = Blockly.Xml.blockToDom(this);
Blockly.Xml.deleteNext(xmlBlock);
var newBlock = Blockly.Xml.domToBlock(
/** @type {!Blockly.BlockSpace} */ (this.blockSpace),
xmlBlock
);
// Move the duplicate next to the old block.
var xy = this.getRelativeToSurfaceXY();
// If this is a duplicate on drag, off-set the block by 1 pixel
var snapRadius = this.shouldCopyOnDrag() ? 1 : Blockly.SNAP_RADIUS;
if (Blockly.RTL) {
xy.x -= snapRadius;
} else {
xy.x += snapRadius;
}
xy.y += snapRadius * 2;
newBlock.moveBy(xy.x, xy.y);
return newBlock;
};
/**
* Show the context menu for this block.
* @param {!Event} e Mouse event
* @private
*/
Blockly.Block.prototype.showContextMenu_ = function(e) {
if (this.blockSpace.isReadOnly() || !this.contextMenu) {
return;
}
// Save the current block in a variable for use in closures.
var block = this;
var options = [];
if (this.isDeletable() && !block.isInFlyout) {
// Option to duplicate this block.
var duplicateOption = {
text: Blockly.Msg.DUPLICATE_BLOCK,
enabled: true,
callback: function() {
block.duplicate_();
}
};
if (this.getDescendants().length > this.blockSpace.remainingCapacity()) {
duplicateOption.enabled = false;
}
options.push(duplicateOption);
// Option to disable/enable block.
var disableOption = {
text: this.disabled
? Blockly.Msg.ENABLE_BLOCK
: Blockly.Msg.DISABLE_BLOCK,
enabled: !this.getInheritedDisabled(),
callback: function() {
block.setDisabled(!block.disabled);
}
};
options.push(disableOption);
// Option to delete this block.
// Count the number of blocks that are nested in this block.
var descendantCount = this.getDescendants().length;
if (block.nextConnection && block.nextConnection.targetConnection) {
// Blocks in the current stack would survive this block's deletion.
descendantCount -= this.nextConnection.targetBlock().getDescendants()
.length;
}
var deleteOption = {