-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathblock.ts
2352 lines (2168 loc) · 68.2 KB
/
block.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 2011 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* The class representing one block.
*
* @class
*/
import * as goog from '../closure/goog/goog.js';
goog.declareModuleId('Blockly.Block');
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_block_change.js';
// 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_block_delete.js';
import {Blocks} from './blocks.js';
import * as common from './common.js';
import {Connection} from './connection.js';
import {ConnectionType} from './connection_type.js';
import * as constants from './constants.js';
import {DuplicateIconType} from './icons/exceptions.js';
import type {Abstract} from './events/events_abstract.js';
import type {BlockMove} from './events/events_block_move.js';
import * as eventUtils from './events/utils.js';
import * as Extensions from './extensions.js';
import type {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import {Input} from './inputs/input.js';
import {Align} from './inputs/align.js';
import type {IASTNodeLocation} from './interfaces/i_ast_node_location.js';
import type {IDeletable} from './interfaces/i_deletable.js';
import type {IIcon} from './interfaces/i_icon.js';
import {CommentIcon} from './icons/comment_icon.js';
import type {MutatorIcon} from './icons/mutator_icon.js';
import * as Tooltip from './tooltip.js';
import * as arrayUtils from './utils/array.js';
import {Coordinate} from './utils/coordinate.js';
import * as idGenerator from './utils/idgenerator.js';
import * as parsing from './utils/parsing.js';
import * as registry from './registry.js';
import {Size} from './utils/size.js';
import type {VariableModel} from './variable_model.js';
import type {Workspace} from './workspace.js';
import {DummyInput} from './inputs/dummy_input.js';
import {ValueInput} from './inputs/value_input.js';
import {StatementInput} from './inputs/statement_input.js';
import {IconType} from './icons/icon_types.js';
/**
* Class for one block.
* Not normally called directly, workspace.newBlock() is preferred.
*/
export class Block implements IASTNodeLocation, IDeletable {
/**
* An optional callback method to use whenever the block's parent workspace
* changes. This is usually only called from the constructor, the block type
* initializer function, or an extension initializer function.
*/
onchange?: ((p1: Abstract) => void) | null;
/** The language-neutral ID given to the collapsed input. */
static readonly COLLAPSED_INPUT_NAME: string = constants.COLLAPSED_INPUT_NAME;
/** The language-neutral ID given to the collapsed field. */
static readonly COLLAPSED_FIELD_NAME: string = constants.COLLAPSED_FIELD_NAME;
/**
* Optional text data that round-trips between blocks and XML.
* Has no effect. May be used by 3rd parties for meta information.
*/
data: string | null = null;
/**
* Has this block been disposed of?
*
* @internal
*/
disposed = false;
/**
* Colour of the block as HSV hue value (0-360)
* This may be null if the block colour was not set via a hue number.
*/
private hue_: number | null = null;
/** Colour of the block in '#RRGGBB' format. */
protected colour_ = '#000000';
/** Name of the block style. */
protected styleName_ = '';
/** An optional method called during initialization. */
init?: () => void;
/** An optional method called during disposal. */
destroy?: () => void;
/**
* An optional serialization method for defining how to serialize the
* mutation state to XML. This must be coupled with defining
* `domToMutation`.
*/
mutationToDom?: (...p1: AnyDuringMigration[]) => Element;
/**
* An optional deserialization method for defining how to deserialize the
* mutation state from XML. This must be coupled with defining
* `mutationToDom`.
*/
domToMutation?: (p1: Element) => void;
/**
* An optional serialization method for defining how to serialize the
* block's extra state (eg mutation state) to something JSON compatible.
* This must be coupled with defining `loadExtraState`.
*/
saveExtraState?: () => AnyDuringMigration;
/**
* An optional serialization method for defining how to deserialize the
* block's extra state (eg mutation state) from something JSON compatible.
* This must be coupled with defining `saveExtraState`.
*/
loadExtraState?: (p1: AnyDuringMigration) => void;
/**
* An optional property for suppressing adding STATEMENT_PREFIX and
* STATEMENT_SUFFIX to generated code.
*/
suppressPrefixSuffix: boolean | null = false;
/**
* An optional property for declaring developer variables. Return a list of
* variable names for use by generators. Developer variables are never
* shown to the user, but are declared as global variables in the generated
* code.
*/
getDeveloperVariables?: () => string[];
/**
* An optional function that reconfigures the block based on the contents of
* the mutator dialog.
*/
compose?: (p1: Block) => void;
/**
* An optional function that populates the mutator's dialog with
* this block's components.
*/
decompose?: (p1: Workspace) => Block;
id: string;
outputConnection: Connection | null = null;
nextConnection: Connection | null = null;
previousConnection: Connection | null = null;
inputList: Input[] = [];
inputsInline?: boolean;
icons: IIcon[] = [];
private disabled = false;
tooltip: Tooltip.TipInfo = '';
contextMenu = true;
protected parentBlock_: this | null = null;
protected childBlocks_: this[] = [];
private deletable_ = true;
private movable_ = true;
private editable_ = true;
private isShadow_ = false;
protected collapsed_ = false;
protected outputShape_: number | null = null;
/**
* Is the current block currently in the process of being disposed?
*/
private disposing = false;
private readonly xy_: Coordinate;
isInFlyout: boolean;
isInMutator: boolean;
RTL: boolean;
/** True if this block is an insertion marker. */
protected isInsertionMarker_ = false;
/** Name of the type of hat. */
hat?: string;
rendered: boolean | null = null;
/**
* String for block help, or function that returns a URL. Null for no help.
*/
helpUrl: string | Function | null = null;
/** A bound callback function to use when the parent workspace changes. */
private onchangeWrapper_: ((p1: Abstract) => void) | null = null;
/**
* A count of statement inputs on the block.
*
* @internal
*/
statementInputCount = 0;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
type!: string;
// Record initial inline state.
inputsInlineDefault?: boolean;
workspace: Workspace;
/**
* @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.
* @throws When the prototypeName is not valid or not allowed.
*/
constructor(workspace: Workspace, prototypeName: string, opt_id?: string) {
this.workspace = workspace;
this.id =
opt_id && !workspace.getBlockById(opt_id) ? opt_id : idGenerator.genUid();
workspace.setBlockById(this.id, this);
/**
* The block's position in workspace units. (0, 0) is at the workspace's
* origin; scale does not change this value.
*/
this.xy_ = new Coordinate(0, 0);
this.isInFlyout = workspace.isFlyout;
this.isInMutator = workspace.isMutator;
this.RTL = workspace.RTL;
// Copy the type-specific functions and data from the prototype.
if (prototypeName) {
this.type = prototypeName;
const prototype = Blocks[prototypeName];
if (!prototype || typeof prototype !== 'object') {
throw TypeError('Invalid block definition for type: ' + prototypeName);
}
Object.assign(this, prototype);
}
workspace.addTopBlock(this);
workspace.addTypedBlock(this);
if (new.target === Block) {
this.doInit_();
}
}
/** Calls the init() function and handles associated event firing, etc. */
protected doInit_() {
// All events fired should be part of the same group.
// Any events fired during init should not be undoable,
// so that block creation is atomic.
const existingGroup = eventUtils.getGroup();
if (!existingGroup) {
eventUtils.setGroup(true);
}
const initialUndoFlag = eventUtils.getRecordUndo();
try {
// Call an initialization function, if it exists.
if (typeof this.init === 'function') {
eventUtils.setRecordUndo(false);
this.init();
eventUtils.setRecordUndo(initialUndoFlag);
}
// Fire a create event.
if (eventUtils.isEnabled()) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CREATE))(this));
}
} finally {
eventUtils.setGroup(existingGroup);
// In case init threw, recordUndo flag should still be reset.
eventUtils.setRecordUndo(initialUndoFlag);
}
this.inputsInlineDefault = this.inputsInline;
// Bind an onchange function, if it exists.
if (typeof this.onchange === 'function') {
this.setOnChange(this.onchange);
}
}
/**
* 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.
*/
dispose(healStack: boolean) {
if (this.isDeadOrDying()) return;
// Dispose of this change listener before unplugging.
// Technically not necessary due to the event firing delay.
// But future-proofing.
if (this.onchangeWrapper_) {
this.workspace.removeChangeListener(this.onchangeWrapper_);
}
this.unplug(healStack);
if (eventUtils.isEnabled()) {
// Constructing the delete event is costly. Only perform if necessary.
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_DELETE))(this));
}
this.workspace.removeTopBlock(this);
this.disposeInternal();
}
/**
* Disposes of this block without doing things required by the top block.
* E.g. does not fire events, unplug the block, etc.
*/
protected disposeInternal() {
if (this.isDeadOrDying()) return;
if (this.onchangeWrapper_) {
this.workspace.removeChangeListener(this.onchangeWrapper_);
}
this.workspace.removeTypedBlock(this);
this.workspace.removeBlockById(this.id);
this.disposing = true;
if (typeof this.destroy === 'function') this.destroy();
this.childBlocks_.forEach((c) => c.disposeInternal());
this.inputList.forEach((i) => i.dispose());
this.inputList.length = 0;
this.getConnections_(true).forEach((c) => c.dispose());
this.disposed = true;
}
/**
* Returns true if the block is either in the process of being disposed, or
* is disposed.
*
* @internal
*/
isDeadOrDying(): boolean {
return this.disposing || this.disposed;
}
/**
* Call initModel on all fields on the block.
* May be called more than once.
* Either initModel or initSvg must be called after creating a block and
* before the first interaction with it. Interactions include UI actions
* (e.g. clicking and dragging) and firing events (e.g. create, delete, and
* change).
*/
initModel() {
for (let i = 0, input; (input = this.inputList[i]); i++) {
for (let j = 0, field; (field = input.fieldRow[j]); j++) {
if (field.initModel) {
field.initModel();
}
}
}
}
/**
* Unplug this block from its superior block. If this block is a statement,
* optionally reconnect the block underneath with the block on top.
*
* @param opt_healStack Disconnect child statement and reconnect stack.
* Defaults to false.
*/
unplug(opt_healStack?: boolean) {
if (this.outputConnection) {
this.unplugFromRow_(opt_healStack);
}
if (this.previousConnection) {
this.unplugFromStack_(opt_healStack);
}
}
/**
* Unplug this block's output from an input on another block. Optionally
* reconnect the block's parent to the only child block, if possible.
*
* @param opt_healStack Disconnect right-side block and connect to left-side
* block. Defaults to false.
*/
private unplugFromRow_(opt_healStack?: boolean) {
let parentConnection = null;
if (this.outputConnection?.isConnected()) {
parentConnection = this.outputConnection.targetConnection;
// Disconnect from any superior block.
this.outputConnection.disconnect();
}
// Return early in obvious cases.
if (!parentConnection || !opt_healStack) {
return;
}
const thisConnection = this.getOnlyValueConnection_();
if (
!thisConnection ||
!thisConnection.isConnected() ||
thisConnection.targetBlock()!.isShadow()
) {
// Too many or too few possible connections on this block, or there's
// nothing on the other side of this connection.
return;
}
const childConnection = thisConnection.targetConnection;
// Disconnect the child block.
childConnection?.disconnect();
// Connect child to the parent if possible, otherwise bump away.
if (
this.workspace.connectionChecker.canConnect(
childConnection,
parentConnection,
false,
)
) {
parentConnection.connect(childConnection!);
} else {
childConnection?.onFailedConnect(parentConnection);
}
}
/**
* Returns the connection on the value input that is connected to another
* block. When an insertion marker is connected to a connection with a block
* already attached, the connected block is attached to the insertion marker.
* Since only one block can be displaced and attached to the insertion marker
* this should only ever return one connection.
*
* @returns The connection on the value input, or null.
*/
private getOnlyValueConnection_(): Connection | null {
let connection = null;
for (let i = 0; i < this.inputList.length; i++) {
const thisConnection = this.inputList[i].connection;
if (
thisConnection &&
thisConnection.type === ConnectionType.INPUT_VALUE &&
thisConnection.targetConnection
) {
if (connection) {
return null; // More than one value input found.
}
connection = thisConnection;
}
}
return connection;
}
/**
* Unplug this statement block from its superior block. Optionally reconnect
* the block underneath with the block on top.
*
* @param opt_healStack Disconnect child statement and reconnect stack.
* Defaults to false.
*/
private unplugFromStack_(opt_healStack?: boolean) {
let previousTarget = null;
if (this.previousConnection?.isConnected()) {
// Remember the connection that any next statements need to connect to.
previousTarget = this.previousConnection.targetConnection;
// Detach this block from the parent's tree.
this.previousConnection.disconnect();
}
const nextBlock = this.getNextBlock();
if (opt_healStack && nextBlock && !nextBlock.isShadow()) {
// Disconnect the next statement.
const nextTarget = this.nextConnection?.targetConnection ?? null;
nextTarget?.disconnect();
if (
previousTarget &&
this.workspace.connectionChecker.canConnect(
previousTarget,
nextTarget,
false,
)
) {
// Attach the next statement to the previous statement.
previousTarget.connect(nextTarget!);
}
}
}
/**
* Returns all connections originating from this block.
*
* @param _all If true, return all connections even hidden ones.
* @returns Array of connections.
* @internal
*/
getConnections_(_all: boolean): Connection[] {
const myConnections = [];
if (this.outputConnection) {
myConnections.push(this.outputConnection);
}
if (this.previousConnection) {
myConnections.push(this.previousConnection);
}
if (this.nextConnection) {
myConnections.push(this.nextConnection);
}
for (let i = 0, input; (input = this.inputList[i]); i++) {
if (input.connection) {
myConnections.push(input.connection);
}
}
return myConnections;
}
/**
* Walks down a stack of blocks and finds the last next connection on the
* stack.
*
* @param ignoreShadows If true,the last connection on a non-shadow block will
* be returned. If false, this will follow shadows to find the last
* connection.
* @returns The last next connection on the stack, or null.
* @internal
*/
lastConnectionInStack(ignoreShadows: boolean): Connection | null {
let nextConnection = this.nextConnection;
while (nextConnection) {
const nextBlock = nextConnection.targetBlock();
if (!nextBlock || (ignoreShadows && nextBlock.isShadow())) {
return nextConnection;
}
nextConnection = nextBlock.nextConnection;
}
return null;
}
/**
* Bump unconnected blocks out of alignment. Two blocks which aren't actually
* connected should not coincidentally line up on screen.
*/
bumpNeighbours() {}
// noop.
/**
* Return the parent block or null if this block is at the top level. The
* parent block is either the block connected to the previous connection (for
* a statement block) or the block connected to the output connection (for a
* value block).
*
* @returns The block (if any) that holds the current block.
*/
getParent(): this | null {
return this.parentBlock_;
}
/**
* Return the input that connects to the specified block.
*
* @param block A block connected to an input on this block.
* @returns The input (if any) that connects to the specified block.
*/
getInputWithBlock(block: Block): Input | null {
for (let i = 0, input; (input = this.inputList[i]); i++) {
if (input.connection && input.connection.targetBlock() === block) {
return input;
}
}
return null;
}
/**
* Return the parent block that surrounds the current block, or null if this
* block has no surrounding block. A parent block might just be the previous
* statement, whereas the surrounding block is an if statement, while loop,
* etc.
*
* @returns The block (if any) that surrounds the current block.
*/
getSurroundParent(): this | null {
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
let block: this | null = this;
let prevBlock;
do {
prevBlock = block;
block = block.getParent();
if (!block) {
// Ran off the top.
return null;
}
} while (block.getNextBlock() === prevBlock);
// This block is an enclosing parent, not just a statement in a stack.
return block;
}
/**
* Return the next statement block directly connected to this block.
*
* @returns The next statement block or null.
*/
getNextBlock(): Block | null {
return this.nextConnection && this.nextConnection.targetBlock();
}
/**
* Returns the block connected to the previous connection.
*
* @returns The previous statement block or null.
*/
getPreviousBlock(): Block | null {
return this.previousConnection && this.previousConnection.targetBlock();
}
/**
* Return the top-most block in this block's tree.
* This will return itself if this block is at the top level.
*
* @returns The root block.
*/
getRootBlock(): this {
let rootBlock: this;
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
let block: this | null = this;
do {
rootBlock = block;
block = rootBlock.parentBlock_;
} while (block);
return rootBlock;
}
/**
* Walk up from the given block up through the stack of blocks to find
* the top block of the sub stack. If we are nested in a statement input only
* find the top-most nested block. Do not go all the way to the root block.
*
* @returns The top block in a stack.
* @internal
*/
getTopStackBlock(): this {
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
let block = this;
let previous;
do {
previous = block.getPreviousBlock();
// AnyDuringMigration because: Type 'Block' is not assignable to type
// 'this'.
} while (
previous &&
previous.getNextBlock() === block &&
(block = previous as AnyDuringMigration)
);
return block;
}
/**
* Find all the blocks that are directly nested inside this one.
* Includes value and statement inputs, as well as any following statement.
* Excludes any connection on an output tab or any preceding statement.
* Blocks are optionally sorted by position; top to bottom.
*
* @param ordered Sort the list if true.
* @returns Array of blocks.
*/
getChildren(ordered: boolean): Block[] {
if (!ordered) {
return this.childBlocks_;
}
const blocks = [];
for (let i = 0, input; (input = this.inputList[i]); i++) {
if (input.connection) {
const child = input.connection.targetBlock();
if (child) {
blocks.push(child);
}
}
}
const next = this.getNextBlock();
if (next) {
blocks.push(next);
}
return blocks;
}
/**
* Set parent of this block to be a new block or null.
*
* @param newParent New parent block.
* @internal
*/
setParent(newParent: this | null) {
if (newParent === this.parentBlock_) {
return;
}
// Check that block is connected to new parent if new parent is not null and
// that block is not connected to superior one if new parent is null.
const targetBlock =
(this.previousConnection && this.previousConnection.targetBlock()) ||
(this.outputConnection && this.outputConnection.targetBlock());
const isConnected = !!targetBlock;
if (isConnected && newParent && targetBlock !== newParent) {
throw Error('Block connected to superior one that is not new parent.');
} else if (!isConnected && newParent) {
throw Error('Block not connected to new parent.');
} else if (isConnected && !newParent) {
throw Error(
'Cannot set parent to null while block is still connected to' +
' superior block.',
);
}
// This block hasn't actually moved on-screen, so there's no need to
// update
// its connection locations.
if (this.parentBlock_) {
// Remove this block from the old parent's child list.
arrayUtils.removeElem(this.parentBlock_.childBlocks_, this);
} else {
// New parent must be non-null so remove this block from the workspace's
// list of top-most blocks.
this.workspace.removeTopBlock(this);
}
this.parentBlock_ = newParent;
if (newParent) {
// Add this block to the new parent's child list.
newParent.childBlocks_.push(this);
} else {
this.workspace.addTopBlock(this);
}
}
/**
* Find all the blocks that are directly or indirectly nested inside this one.
* Includes this block in the list.
* Includes value and statement inputs, as well as any following statements.
* Excludes any connection on an output tab or any preceding statements.
* Blocks are optionally sorted by position; top to bottom.
*
* @param ordered Sort the list if true.
* @returns Flattened array of blocks.
*/
getDescendants(ordered: boolean): this[] {
const blocks = [this];
const childBlocks = this.getChildren(ordered);
for (let child, i = 0; (child = childBlocks[i]); i++) {
// AnyDuringMigration because: Argument of type 'Block[]' is not
// assignable to parameter of type 'this[]'.
blocks.push(...(child.getDescendants(ordered) as AnyDuringMigration));
}
return blocks;
}
/**
* Get whether this block is deletable or not.
*
* @returns True if deletable.
*/
isDeletable(): boolean {
return (
this.deletable_ &&
!this.isShadow_ &&
!this.isDeadOrDying() &&
!this.workspace.options.readOnly
);
}
/**
* Return whether this block's own deletable property is true or false.
*
* @returns True if the block's deletable property is true, false otherwise.
*/
isOwnDeletable(): boolean {
return this.deletable_;
}
/**
* Set whether this block is deletable or not.
*
* @param deletable True if deletable.
*/
setDeletable(deletable: boolean) {
this.deletable_ = deletable;
}
/**
* Get whether this block is movable or not.
*
* @returns True if movable.
* @internal
*/
isMovable(): boolean {
return (
this.movable_ &&
!this.isShadow_ &&
!this.isDeadOrDying() &&
!this.workspace.options.readOnly
);
}
/**
* Return whether this block's own movable property is true or false.
*
* @returns True if the block's movable property is true, false otherwise.
* @internal
*/
isOwnMovable(): boolean {
return this.movable_;
}
/**
* Set whether this block is movable or not.
*
* @param movable True if movable.
*/
setMovable(movable: boolean) {
this.movable_ = movable;
}
/**
* Get whether is block is duplicatable or not. If duplicating this block and
* descendants will put this block over the workspace's capacity this block is
* not duplicatable. If duplicating this block and descendants will put any
* type over their maxInstances this block is not duplicatable.
*
* @returns True if duplicatable.
*/
isDuplicatable(): boolean {
if (!this.workspace.hasBlockLimits()) {
return true;
}
return this.workspace.isCapacityAvailable(
common.getBlockTypeCounts(this, true),
);
}
/**
* Get whether this block is a shadow block or not.
*
* @returns True if a shadow.
*/
isShadow(): boolean {
return this.isShadow_;
}
/**
* Set whether this block is a shadow block or not.
*
* @param shadow True if a shadow.
* @internal
*/
setShadow(shadow: boolean) {
this.isShadow_ = shadow;
}
/**
* Get whether this block is an insertion marker block or not.
*
* @returns True if an insertion marker.
*/
isInsertionMarker(): boolean {
return this.isInsertionMarker_;
}
/**
* 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
*/
setInsertionMarker(insertionMarker: boolean) {
this.isInsertionMarker_ = insertionMarker;
}
/**
* Get whether this block is editable or not.
*
* @returns True if editable.
* @internal
*/
isEditable(): boolean {
return (
this.editable_ &&
!this.isDeadOrDying() &&
!this.workspace.options.readOnly
);
}
/**
* Return whether this block's own editable property is true or false.
*
* @returns True if the block's editable property is true, false otherwise.
*/
isOwnEditable(): boolean {
return this.editable_;
}
/**
* Set whether this block is editable or not.
*
* @param editable True if editable.
*/
setEditable(editable: boolean) {
this.editable_ = editable;
for (let i = 0, input; (input = this.inputList[i]); i++) {
for (let j = 0, field; (field = input.fieldRow[j]); j++) {
field.updateEditable();
}
}
}
/**
* Returns if this block has been disposed of / deleted.
*
* @returns True if this block has been disposed of / deleted.
*/
isDisposed(): boolean {
return this.disposed;
}
/**
* Find the connection on this block that corresponds to the given connection
* on the other block.
* Used to match connections between a block and its insertion marker.
*
* @param otherBlock The other block to match against.
* @param conn The other connection to match.
* @returns The matching connection on this block, or null.
* @internal
*/
getMatchingConnection(
otherBlock: Block,
conn: Connection,
): Connection | null {
const connections = this.getConnections_(true);
const otherConnections = otherBlock.getConnections_(true);
if (connections.length !== otherConnections.length) {
throw Error('Connection lists did not match in length.');
}
for (let i = 0; i < otherConnections.length; i++) {
if (otherConnections[i] === conn) {
return connections[i];
}
}
return null;
}
/**
* Set the URL of this block's help page.
*
* @param url URL string for block help, or function that returns a URL. Null
* for no help.
*/
setHelpUrl(url: string | Function) {
this.helpUrl = url;
}
/**
* Sets the tooltip for this block.
*
* @param newTip The text for the tooltip, a function that returns the text
* for the tooltip, or a parent object whose tooltip will be used. To not
* display a tooltip pass the empty string.
*/
setTooltip(newTip: Tooltip.TipInfo) {
this.tooltip = newTip;
}
/**
* Returns the tooltip text for this block.
*
* @returns The tooltip text for this block.
*/
getTooltip(): string {
return Tooltip.getTooltipOfObject(this);
}
/**
* Get the colour of a block.
*
* @returns #RRGGBB string.
*/
getColour(): string {
return this.colour_;
}