chore: format

This commit is contained in:
Beka Westberg
2022-06-17 19:53:57 +00:00
parent cec2e80d04
commit 3ea312a4b6
236 changed files with 5599 additions and 5634 deletions
+140 -140
View File
@@ -19,41 +19,41 @@ import './events/events_block_create';
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_block_delete';
import { Blocks } from './blocks.js';
import {Blocks} from './blocks.js';
/* eslint-disable-next-line no-unused-vars */
import { Comment } from './comment.js';
import {Comment} from './comment.js';
import * as common from './common.js';
import { Connection } from './connection.js';
import { ConnectionType } from './connection_type.js';
import {Connection} from './connection.js';
import {ConnectionType} from './connection_type.js';
import * as constants from './constants.js';
/* eslint-disable-next-line no-unused-vars */
import { Abstract } from './events/events_abstract.js';
import {Abstract} from './events/events_abstract.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockMove } from './events/events_block_move.js';
import {BlockMove} from './events/events_block_move.js';
import * as eventUtils from './events/utils.js';
import * as Extensions from './extensions.js';
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { Align, Input } from './input.js';
import { inputTypes } from './input_types.js';
import {Align, Input} from './input.js';
import {inputTypes} from './input_types.js';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocation } from './interfaces/i_ast_node_location.js';
import {IASTNodeLocation} from './interfaces/i_ast_node_location.js';
/* eslint-disable-next-line no-unused-vars */
import { IDeletable } from './interfaces/i_deletable.js';
import { ASTNode } from './keyboard_nav/ast_node.js';
import {IDeletable} from './interfaces/i_deletable.js';
import {ASTNode} from './keyboard_nav/ast_node.js';
/* eslint-disable-next-line no-unused-vars */
import { Mutator } from './mutator.js';
import {Mutator} from './mutator.js';
import * as Tooltip from './tooltip.js';
import * as arrayUtils from './utils/array.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as idGenerator from './utils/idgenerator.js';
import * as parsing from './utils/parsing.js';
import { Size } from './utils/size.js';
import {Size} from './utils/size.js';
/* eslint-disable-next-line no-unused-vars */
import { VariableModel } from './variable_model.js';
import {VariableModel} from './variable_model.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from './workspace.js';
import {Workspace} from './workspace.js';
/**
@@ -68,7 +68,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* changes. This is usually only called from the constructor, the block type
* initializer function, or an extension initializer function.
*/
onchange?: ((p1: Abstract) => AnyDuringMigration) | null;
onchange?: ((p1: Abstract) => AnyDuringMigration)|null;
/** The language-neutral ID given to the collapsed input. */
static readonly COLLAPSED_INPUT_NAME: string = constants.COLLAPSED_INPUT_NAME;
@@ -80,7 +80,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* 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;
data: string|null = null;
/** Has this block been disposed of? */
disposed = false;
@@ -89,7 +89,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* 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;
private hue_: number|null = null;
/** Colour of the block in '#RRGGBB' format. */
protected colour_ = '#000000';
@@ -98,28 +98,28 @@ export class Block implements IASTNodeLocation, IDeletable {
protected styleName_ = '';
/** An optional method called during initialization. */
init?: (() => AnyDuringMigration) | null = undefined;
init?: (() => AnyDuringMigration)|null = undefined;
/**
* 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) | null = undefined;
mutationToDom?: ((...p1: AnyDuringMigration[]) => Element)|null = undefined;
/**
* An optional deserialization method for defining how to deserialize the
* mutation state from XML. This must be coupled with defining
* `mutationToDom`.
*/
domToMutation?: ((p1: Element) => AnyDuringMigration) | null = undefined;
domToMutation?: ((p1: Element) => AnyDuringMigration)|null = undefined;
/**
* 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) | null = undefined;
saveExtraState?: (() => AnyDuringMigration)|null = undefined;
/**
* An optional serialization method for defining how to deserialize the
@@ -127,13 +127,13 @@ export class Block implements IASTNodeLocation, IDeletable {
* This must be coupled with defining `saveExtraState`.
*/
loadExtraState?:
((p1: AnyDuringMigration) => AnyDuringMigration) | null = undefined;
((p1: AnyDuringMigration) => AnyDuringMigration)|null = undefined;
/**
* An optional property for suppressing adding STATEMENT_PREFIX and
* STATEMENT_SUFFIX to generated code.
*/
suppressPrefixSuffix: boolean | null = false;
suppressPrefixSuffix: boolean|null = false;
/**
* An optional property for declaring developer variables. Return a list of
@@ -141,19 +141,19 @@ export class Block implements IASTNodeLocation, IDeletable {
* shown to the user, but are declared as global variables in the generated
* code.
*/
getDeveloperVariables?: (() => string[]) | null = undefined;
getDeveloperVariables?: (() => string[])|null = undefined;
/**
* An optional function that reconfigures the block based on the contents of
* the mutator dialog.
*/
compose?: ((p1: Block) => void) | null = null;
compose?: ((p1: Block) => void)|null = null;
/**
* An optional function that populates the mutator's dialog with
* this block's components.
*/
decompose?: ((p1: Workspace) => Block) | null = null;
decompose?: ((p1: Workspace) => Block)|null = null;
id: string;
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'Connection'.
@@ -170,7 +170,7 @@ export class Block implements IASTNodeLocation, IDeletable {
tooltip: Tooltip.TipInfo = '';
contextMenu = true;
protected parentBlock_: this | null = null;
protected parentBlock_: this|null = null;
protected childBlocks_: this[] = [];
@@ -183,13 +183,13 @@ export class Block implements IASTNodeLocation, IDeletable {
private isShadow_ = false;
protected collapsed_ = false;
protected outputShape_: number | null = null;
protected outputShape_: number|null = null;
/**
* A string representing the comment attached to this block.
* @deprecated August 2019. Use getCommentText instead.
*/
comment: string | Comment | null = null;
comment: string|Comment|null = null;
commentModel: CommentModel;
private readonly xy_: Coordinate;
isInFlyout: boolean;
@@ -202,17 +202,17 @@ export class Block implements IASTNodeLocation, IDeletable {
/** Name of the type of hat. */
hat?: string = undefined;
rendered: boolean | null = null;
rendered: boolean|null = null;
/**
* String for block help, or function that returns a URL. Null for no help.
*/
// AnyDuringMigration because: Type 'null' is not assignable to type 'string
// | Function'.
helpUrl: string | Function = null as AnyDuringMigration;
helpUrl: string|Function = null as AnyDuringMigration;
/** A bound callback function to use when the parent workspace changes. */
private onchangeWrapper_: ((p1: Abstract) => AnyDuringMigration) | null = null;
private onchangeWrapper_: ((p1: Abstract) => AnyDuringMigration)|null = null;
/** A count of statement inputs on the block. */
statementInputCount = 0;
@@ -234,11 +234,11 @@ export class Block implements IASTNodeLocation, IDeletable {
this.workspace = workspace;
this.id = opt_id && !workspace.getBlockById(opt_id) ? opt_id :
idGenerator.genUid();
idGenerator.genUid();
workspace.setBlockById(this.id, this);
/** A model of the comment attached to this block. */
this.commentModel = { text: null, pinned: false, size: new Size(160, 80) };
this.commentModel = {text: null, pinned: false, size: new Size(160, 80)};
/**
* The block's position in workspace units. (0, 0) is at the workspace's
@@ -414,7 +414,7 @@ export class Block implements IASTNodeLocation, IDeletable {
const thisConnection = this.getOnlyValueConnection_();
if (!thisConnection || !thisConnection.isConnected() ||
thisConnection.targetBlock()!.isShadow()) {
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;
@@ -425,7 +425,7 @@ export class Block implements IASTNodeLocation, IDeletable {
childConnection?.disconnect();
// Connect child to the parent if possible, otherwise bump away.
if (this.workspace.connectionChecker.canConnect(
childConnection, parentConnection, false)) {
childConnection, parentConnection, false)) {
parentConnection.connect(childConnection!);
} else {
childConnection?.onFailedConnect(parentConnection);
@@ -441,13 +441,13 @@ export class Block implements IASTNodeLocation, IDeletable {
*
* @return The connection on the value input, or null.
*/
private getOnlyValueConnection_(): Connection | 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) {
thisConnection.type === ConnectionType.INPUT_VALUE &&
thisConnection.targetConnection) {
if (connection) {
return null;
}
@@ -478,8 +478,8 @@ export class Block implements IASTNodeLocation, IDeletable {
const nextTarget = this.nextConnection.targetConnection;
nextTarget?.disconnect();
if (previousTarget &&
this.workspace.connectionChecker.canConnect(
previousTarget, nextTarget, false)) {
this.workspace.connectionChecker.canConnect(
previousTarget, nextTarget, false)) {
// Attach the next statement to the previous statement.
previousTarget.connect(nextTarget!);
}
@@ -518,7 +518,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* connection.
* @return The last next connection on the stack, or null.
*/
lastConnectionInStack(ignoreShadows: boolean): Connection | null {
lastConnectionInStack(ignoreShadows: boolean): Connection|null {
let nextConnection = this.nextConnection;
while (nextConnection) {
const nextBlock = nextConnection.targetBlock();
@@ -544,7 +544,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* value block).
* @return The block (if any) that holds the current block.
*/
getParent(): this | null {
getParent(): this|null {
return this.parentBlock_;
}
@@ -553,7 +553,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param block A block connected to an input on this block.
* @return The input (if any) that connects to the specified block.
*/
getInputWithBlock(block: Block): Input | null {
getInputWithBlock(block: Block): Input|null {
for (let i = 0, input; input = this.inputList[i]; i++) {
if (input.connection && input.connection.targetBlock() === block) {
return input;
@@ -569,7 +569,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* etc.
* @return The block (if any) that surrounds the current block.
*/
getSurroundParent(): this | null {
getSurroundParent(): this|null {
let block = this;
let prevBlock;
do {
@@ -590,7 +590,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Return the next statement block directly connected to this block.
* @return The next statement block or null.
*/
getNextBlock(): Block | null {
getNextBlock(): Block|null {
return this.nextConnection && this.nextConnection.targetBlock();
}
@@ -598,7 +598,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Returns the block connected to the previous connection.
* @return The previous statement block or null.
*/
getPreviousBlock(): Block | null {
getPreviousBlock(): Block|null {
return this.previousConnection && this.previousConnection.targetBlock();
}
@@ -607,10 +607,10 @@ export class Block implements IASTNodeLocation, IDeletable {
* if there are none.
* @return The first statement connection or null.
*/
getFirstStatementConnection(): Connection | null {
getFirstStatementConnection(): Connection|null {
for (let i = 0, input; input = this.inputList[i]; i++) {
if (input.connection &&
input.connection.type === ConnectionType.NEXT_STATEMENT) {
input.connection.type === ConnectionType.NEXT_STATEMENT) {
return input.connection;
}
}
@@ -624,7 +624,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
getRootBlock(): this {
let rootBlock: this;
let block: this | null = this;
let block: this|null = this;
do {
rootBlock = block;
block = rootBlock.parentBlock_;
@@ -646,7 +646,7 @@ export class Block implements IASTNodeLocation, IDeletable {
// AnyDuringMigration because: Type 'Block' is not assignable to type
// 'this'.
} while (previous && previous.getNextBlock() === block &&
(block = previous as AnyDuringMigration));
(block = previous as AnyDuringMigration));
return block;
}
@@ -682,7 +682,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Set parent of this block to be a new block or null.
* @param newParent New parent block.
*/
setParent(newParent: this | null) {
setParent(newParent: this|null) {
if (newParent === this.parentBlock_) {
return;
}
@@ -690,8 +690,8 @@ export class Block implements IASTNodeLocation, IDeletable {
// 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();
this.previousConnection && this.previousConnection.targetBlock() ||
this.outputConnection && this.outputConnection.targetBlock();
const isConnected = !!targetBlock;
if (isConnected && newParent && targetBlock !== newParent) {
@@ -700,8 +700,8 @@ export class Block implements IASTNodeLocation, IDeletable {
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.');
'Cannot set parent to null while block is still connected to' +
' superior block.');
}
@@ -742,7 +742,7 @@ export class Block implements IASTNodeLocation, IDeletable {
// AnyDuringMigration because: Argument of type 'Block[]' is not
// assignable to parameter of type 'this[]'.
blocks.push.apply(
blocks, child.getDescendants(ordered) as AnyDuringMigration);
blocks, child.getDescendants(ordered) as AnyDuringMigration);
}
return blocks;
}
@@ -753,7 +753,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
isDeletable(): boolean {
return this.deletable_ && !this.isShadow_ &&
!(this.workspace && this.workspace.options.readOnly);
!(this.workspace && this.workspace.options.readOnly);
}
/**
@@ -770,7 +770,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
isMovable(): boolean {
return this.movable_ && !this.isShadow_ &&
!(this.workspace && this.workspace.options.readOnly);
!(this.workspace && this.workspace.options.readOnly);
}
/**
@@ -793,7 +793,7 @@ export class Block implements IASTNodeLocation, IDeletable {
return true;
}
return this.workspace.isCapacityAvailable(
common.getBlockTypeCounts(this, true));
common.getBlockTypeCounts(this, true));
}
/**
@@ -835,7 +835,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
isEditable(): boolean {
return this.editable_ &&
!(this.workspace && this.workspace.options.readOnly);
!(this.workspace && this.workspace.options.readOnly);
}
/**
@@ -867,7 +867,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param conn The other connection to match.
* @return The matching connection on this block, or null.
*/
getMatchingConnection(otherBlock: Block, conn: Connection): Connection | null {
getMatchingConnection(otherBlock: Block, conn: Connection): Connection|null {
const connections = this.getConnections_(true);
const otherConnections = otherBlock.getConnections_(true);
if (connections.length !== otherConnections.length) {
@@ -886,7 +886,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param url URL string for block help, or function that returns a URL. Null
* for no help.
*/
setHelpUrl(url: string | Function) {
setHelpUrl(url: string|Function) {
this.helpUrl = url;
}
@@ -928,7 +928,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Get the HSV hue value of a block. Null if hue not set.
* @return Hue value (0-360).
*/
getHue(): number | null {
getHue(): number|null {
return this.hue_;
}
@@ -937,7 +937,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param colour HSV hue value (0 to 360), #RRGGBB string, or a message
* reference string pointing to one of those two values.
*/
setColour(colour: number | string) {
setColour(colour: number|string) {
const parsed = parsing.parseBlockColour(colour);
this.hue_ = parsed.hue;
this.colour_ = parsed.hex;
@@ -976,13 +976,13 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param name The name of the field.
* @return Named field, or null if field does not exist.
*/
getField(name: string): Field | null {
getField(name: string): Field|null {
if (typeof name !== 'string') {
throw TypeError(
'Block.prototype.getField expects a string ' +
'with the field name but received ' +
(name === undefined ? 'nothing' : name + ' of type ' + typeof name) +
' instead');
'Block.prototype.getField expects a string ' +
'with the field name but received ' +
(name === undefined ? 'nothing' : name + ' of type ' + typeof name) +
' instead');
}
for (let i = 0, input; input = this.inputList[i]; i++) {
for (let j = 0, field; field = input.fieldRow[j]; j++) {
@@ -1020,7 +1020,7 @@ export class Block implements IASTNodeLocation, IDeletable {
for (let j = 0, field; field = input.fieldRow[j]; j++) {
if (field.referencesVariables()) {
const model =
this.workspace.getVariableById(field.getValue() as string);
this.workspace.getVariableById(field.getValue() as string);
// Check if the variable actually exists (and isn't just a potential
// variable).
if (model) {
@@ -1041,7 +1041,7 @@ export class Block implements IASTNodeLocation, IDeletable {
for (let i = 0, input; input = this.inputList[i]; i++) {
for (let j = 0, field; field = input.fieldRow[j]; j++) {
if (field.referencesVariables() &&
variable.getId() === field.getValue()) {
variable.getId() === field.getValue()) {
field.refreshVariableName();
}
}
@@ -1097,22 +1097,22 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param opt_check Statement type or list of statement types. Null/undefined
* if any type could be connected.
*/
setPreviousStatement(newBoolean: boolean, opt_check?: string | string[] | null) {
setPreviousStatement(newBoolean: boolean, opt_check?: string|string[]|null) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.previousConnection) {
this.previousConnection =
this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT);
this.makeConnection_(ConnectionType.PREVIOUS_STATEMENT);
}
this.previousConnection.setCheck(opt_check);
} else {
if (this.previousConnection) {
if (this.previousConnection.isConnected()) {
throw Error(
'Must disconnect previous statement before removing ' +
'connection.');
'Must disconnect previous statement before removing ' +
'connection.');
}
this.previousConnection.dispose();
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -1128,22 +1128,22 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param opt_check Statement type or list of statement types. Null/undefined
* if any type could be connected.
*/
setNextStatement(newBoolean: boolean, opt_check?: string | string[] | null) {
setNextStatement(newBoolean: boolean, opt_check?: string|string[]|null) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.nextConnection) {
this.nextConnection =
this.makeConnection_(ConnectionType.NEXT_STATEMENT);
this.makeConnection_(ConnectionType.NEXT_STATEMENT);
}
this.nextConnection.setCheck(opt_check);
} else {
if (this.nextConnection) {
if (this.nextConnection.isConnected()) {
throw Error(
'Must disconnect next statement before removing ' +
'connection.');
'Must disconnect next statement before removing ' +
'connection.');
}
this.nextConnection.dispose();
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -1159,21 +1159,21 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param opt_check Returned type or list of returned types. Null or
* undefined if any type could be returned (e.g. variable get).
*/
setOutput(newBoolean: boolean, opt_check?: string | string[] | null) {
setOutput(newBoolean: boolean, opt_check?: string|string[]|null) {
if (newBoolean) {
if (opt_check === undefined) {
opt_check = null;
}
if (!this.outputConnection) {
this.outputConnection =
this.makeConnection_(ConnectionType.OUTPUT_VALUE);
this.makeConnection_(ConnectionType.OUTPUT_VALUE);
}
this.outputConnection.setCheck(opt_check);
} else {
if (this.outputConnection) {
if (this.outputConnection.isConnected()) {
throw Error(
'Must disconnect output value before removing connection.');
'Must disconnect output value before removing connection.');
}
this.outputConnection.dispose();
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -1190,7 +1190,7 @@ export class Block implements IASTNodeLocation, IDeletable {
setInputsInline(newBoolean: boolean) {
if (this.inputsInline !== newBoolean) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this, 'inline', null, this.inputsInline, newBoolean));
(this, 'inline', null, this.inputsInline, newBoolean));
this.inputsInline = newBoolean;
}
}
@@ -1207,14 +1207,14 @@ export class Block implements IASTNodeLocation, IDeletable {
// Not defined explicitly. Figure out what would look best.
for (let i = 1; i < this.inputList.length; i++) {
if (this.inputList[i - 1].type === inputTypes.DUMMY &&
this.inputList[i].type === inputTypes.DUMMY) {
this.inputList[i].type === inputTypes.DUMMY) {
// Two dummy inputs in a row. Don't inline them.
return false;
}
}
for (let i = 1; i < this.inputList.length; i++) {
if (this.inputList[i - 1].type === inputTypes.VALUE &&
this.inputList[i].type === inputTypes.DUMMY) {
this.inputList[i].type === inputTypes.DUMMY) {
// Dummy input after a value input. Inline them.
return true;
}
@@ -1226,7 +1226,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Set the block's output shape.
* @param outputShape Value representing an output shape.
*/
setOutputShape(outputShape: number | null) {
setOutputShape(outputShape: number|null) {
this.outputShape_ = outputShape;
}
@@ -1234,7 +1234,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Get the block's output shape.
* @return Value representing output shape if one exists.
*/
getOutputShape(): number | null {
getOutputShape(): number|null {
return this.outputShape_;
}
@@ -1255,7 +1255,7 @@ export class Block implements IASTNodeLocation, IDeletable {
const oldValue = this.disabled;
this.disabled = !enabled;
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this, 'disabled', null, oldValue, !enabled));
(this, 'disabled', null, oldValue, !enabled));
}
}
@@ -1291,7 +1291,7 @@ export class Block implements IASTNodeLocation, IDeletable {
setCollapsed(collapsed: boolean) {
if (this.collapsed_ !== collapsed) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this, 'collapsed', null, this.collapsed_, collapsed));
(this, 'collapsed', null, this.collapsed_, collapsed));
this.collapsed_ = collapsed;
}
}
@@ -1325,13 +1325,13 @@ export class Block implements IASTNodeLocation, IDeletable {
checks = connection.targetConnection.getCheck();
}
return !!checks &&
(checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1);
(checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1);
}
/** Check that we haven't circled back to the original root node. */
function checkRoot() {
if (node && node.getType() === rootNode?.getType() &&
node.getLocation() === rootNode?.getLocation()) {
node.getLocation() === rootNode?.getLocation()) {
node = null;
}
}
@@ -1368,7 +1368,7 @@ export class Block implements IASTNodeLocation, IDeletable {
checkRoot();
// If we hit an input on the way up, possibly close out parentheses.
if (node && node.getType() === ASTNode.types.INPUT &&
shouldAddParentheses(node.getLocation() as Connection)) {
shouldAddParentheses(node.getLocation() as Connection)) {
text.push(')');
}
}
@@ -1394,7 +1394,7 @@ export class Block implements IASTNodeLocation, IDeletable {
// Join the text array, removing spaces around added parentheses.
// AnyDuringMigration because: Type 'string' is not assignable to type
// 'any[]'.
text = text.reduce(function (acc, value) {
text = text.reduce(function(acc, value) {
return acc + (acc.substr(-1) === '(' || value === ')' ? '' : ' ') + value;
}, '') as AnyDuringMigration;
// AnyDuringMigration because: Property 'trim' does not exist on type
@@ -1408,7 +1408,7 @@ export class Block implements IASTNodeLocation, IDeletable {
// AnyDuringMigration because: Type 'string' is not assignable to type
// 'any[]'.
text = (text.substring(0, opt_maxLength - 3) + '...') as
AnyDuringMigration;
AnyDuringMigration;
}
}
return text;
@@ -1455,8 +1455,8 @@ export class Block implements IASTNodeLocation, IDeletable {
// Validate inputs.
if (json['output'] && json['previousStatement']) {
throw Error(
warningPrefix +
'Must not have both an output and a previousStatement.');
warningPrefix +
'Must not have both an output and a previousStatement.');
}
// Set basic properties of block.
@@ -1480,8 +1480,8 @@ export class Block implements IASTNodeLocation, IDeletable {
let i = 0;
while (json['message' + i] !== undefined) {
this.interpolate_(
json['message' + i], json['args' + i] || [],
json['lastDummyAlign' + i], warningPrefix);
json['message' + i], json['args' + i] || [],
json['lastDummyAlign' + i], warningPrefix);
i++;
}
@@ -1519,10 +1519,10 @@ export class Block implements IASTNodeLocation, IDeletable {
}
if (typeof json['extensions'] === 'string') {
console.warn(
warningPrefix +
'JSON attribute \'extensions\' should be an array of' +
' strings. Found raw string in JSON for \'' + json['type'] +
'\' block.');
warningPrefix +
'JSON attribute \'extensions\' should be an array of' +
' strings. Found raw string in JSON for \'' + json['type'] +
'\' block.');
json['extensions'] = [json['extensions']];
}
// Correct and continue.
@@ -1585,7 +1585,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
mixin(mixinObj: AnyDuringMigration, opt_disableCheck?: boolean) {
if (opt_disableCheck !== undefined &&
typeof opt_disableCheck !== 'boolean') {
typeof opt_disableCheck !== 'boolean') {
throw Error('opt_disableCheck must be a boolean if provided');
}
if (!opt_disableCheck) {
@@ -1597,8 +1597,8 @@ export class Block implements IASTNodeLocation, IDeletable {
}
if (overwrites.length) {
throw Error(
'Mixin will overwrite block members: ' +
JSON.stringify(overwrites));
'Mixin will overwrite block members: ' +
JSON.stringify(overwrites));
}
}
Object.assign(this, mixinObj);
@@ -1614,8 +1614,8 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param warningPrefix Warning prefix string identifying block.
*/
private interpolate_(
message: string, args: AnyDuringMigration[],
lastDummyAlign: string | undefined, warningPrefix: string) {
message: string, args: AnyDuringMigration[],
lastDummyAlign: string|undefined, warningPrefix: string) {
const tokens = parsing.tokenizeInterpolation(message);
this.validateTokens_(tokens, args.length);
const elements = this.interpolateArguments_(tokens, args, lastDummyAlign);
@@ -1650,7 +1650,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param tokens An array of tokens to validate
* @param argsCount The number of args that need to be referred to.
*/
private validateTokens_(tokens: Array<string | number>, argsCount: number) {
private validateTokens_(tokens: Array<string|number>, argsCount: number) {
const visitedArgsHash = [];
let visitedArgsCount = 0;
for (let i = 0; i < tokens.length; i++) {
@@ -1660,21 +1660,21 @@ export class Block implements IASTNodeLocation, IDeletable {
}
if (token < 1 || token > argsCount) {
throw Error(
'Block "' + this.type + '": ' +
'Message index %' + token + ' out of range.');
'Block "' + this.type + '": ' +
'Message index %' + token + ' out of range.');
}
if (visitedArgsHash[token]) {
throw Error(
'Block "' + this.type + '": ' +
'Message index %' + token + ' duplicated.');
'Block "' + this.type + '": ' +
'Message index %' + token + ' duplicated.');
}
visitedArgsHash[token] = true;
visitedArgsCount++;
}
if (visitedArgsCount !== argsCount) {
throw Error(
'Block "' + this.type + '": ' +
'Message does not reference all ' + argsCount + ' arg(s).');
'Block "' + this.type + '": ' +
'Message does not reference all ' + argsCount + ' arg(s).');
}
}
@@ -1689,8 +1689,8 @@ export class Block implements IASTNodeLocation, IDeletable {
* @return The JSON definitions of field and inputs to add to the block.
*/
private interpolateArguments_(
tokens: Array<string | number>, args: Array<AnyDuringMigration | string>,
lastDummyAlign: string | undefined): AnyDuringMigration[] {
tokens: Array<string|number>, args: Array<AnyDuringMigration|string>,
lastDummyAlign: string|undefined): AnyDuringMigration[] {
const elements = [];
for (let i = 0; i < tokens.length; i++) {
let element = tokens[i];
@@ -1711,9 +1711,9 @@ export class Block implements IASTNodeLocation, IDeletable {
const length = elements.length;
if (length &&
!this.isInputKeyword_(
(elements as AnyDuringMigration)[length - 1]['type'])) {
const dummyInput = { 'type': 'input_dummy' };
!this.isInputKeyword_(
(elements as AnyDuringMigration)[length - 1]['type'])) {
const dummyInput = {'type': 'input_dummy'};
if (lastDummyAlign) {
(dummyInput as AnyDuringMigration)['align'] = lastDummyAlign;
}
@@ -1730,8 +1730,8 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param element The element to try to turn into a field.
* @return The field defined by the JSON, or null if one couldn't be created.
*/
private fieldFromJson_(element: { alt?: string, type?: string, text?: string }):
Field | null {
private fieldFromJson_(element: {alt?: string, type?: string, text?: string}):
Field|null {
const field = fieldRegistry.fromJson(element);
if (!field && element['alt']) {
if (typeof element['alt'] === 'string') {
@@ -1753,7 +1753,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* created for some reason (should never happen).
*/
private inputFromJson_(element: AnyDuringMigration, warningPrefix: string):
Input | null {
Input|null {
const alignmentLookup = {
'LEFT': Align.LEFT,
'RIGHT': Align.RIGHT,
@@ -1783,8 +1783,8 @@ export class Block implements IASTNodeLocation, IDeletable {
}
if (element['align']) {
const alignment =
(alignmentLookup as
AnyDuringMigration)[element['align'].toUpperCase()];
(alignmentLookup as
AnyDuringMigration)[element['align'].toUpperCase()];
if (alignment === undefined) {
console.warn(warningPrefix + 'Illegal align value: ', element['align']);
} else {
@@ -1802,7 +1802,7 @@ export class Block implements IASTNodeLocation, IDeletable {
*/
private isInputKeyword_(str: string): boolean {
return str === 'input_value' || str === 'input_statement' ||
str === 'input_dummy';
str === 'input_dummy';
}
/**
@@ -1811,7 +1811,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param str String to turn into the JSON definition of a label field.
* @return The JSON definition or null.
*/
private stringToFieldJson_(str: string): { text: string, type: string } | null {
private stringToFieldJson_(str: string): {text: string, type: string}|null {
str = str.trim();
if (str) {
return {
@@ -1840,7 +1840,7 @@ export class Block implements IASTNodeLocation, IDeletable {
// AnyDuringMigration because: Argument of type 'Connection | null' is not
// assignable to parameter of type 'Connection'.
const input =
new Input(type, name, this, (connection as AnyDuringMigration));
new Input(type, name, this, (connection as AnyDuringMigration));
// Append input to list.
this.inputList.push(input);
return input;
@@ -1852,7 +1852,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param refName Name of input that should be after the moved input, or null
* to be the input at the end.
*/
moveInputBefore(name: string, refName: string | null) {
moveInputBefore(name: string, refName: string|null) {
if (name === refName) {
return;
}
@@ -1937,7 +1937,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param name The name of the input.
* @return The input object, or null if input does not exist.
*/
getInput(name: string): Input | null {
getInput(name: string): Input|null {
for (let i = 0, input; input = this.inputList[i]; i++) {
if (input.name === name) {
return input;
@@ -1953,7 +1953,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @return The attached value block, or null if the input is either
* disconnected or if the input does not exist.
*/
getInputTargetBlock(name: string): Block | null {
getInputTargetBlock(name: string): Block|null {
const input = this.getInput(name);
return input && input.connection && input.connection.targetBlock();
}
@@ -1962,7 +1962,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* Returns the comment on this block (or null if there is no comment).
* @return Block's comment.
*/
getCommentText(): string | null {
getCommentText(): string|null {
return this.commentModel.text;
}
@@ -1970,12 +1970,12 @@ export class Block implements IASTNodeLocation, IDeletable {
* Set this block's comment text.
* @param text The text, or null to delete.
*/
setCommentText(text: string | null) {
setCommentText(text: string|null) {
if (this.commentModel.text === text) {
return;
}
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this, 'comment', null, this.commentModel.text, text));
(this, 'comment', null, this.commentModel.text, text));
this.commentModel.text = text;
// AnyDuringMigration because: Type 'string | null' is not assignable to
// type 'string | Comment'.
@@ -1989,7 +1989,7 @@ export class Block implements IASTNodeLocation, IDeletable {
* @param _opt_id An optional ID for the warning text to be able to maintain
* multiple warnings.
*/
setWarningText(_text: string | null, _opt_id?: string) {}
setWarningText(_text: string|null, _opt_id?: string) {}
// NOP.
/**
@@ -2018,7 +2018,7 @@ export class Block implements IASTNodeLocation, IDeletable {
throw Error('Block has parent.');
}
const event =
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(this) as BlockMove;
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(this) as BlockMove;
this.xy_.translate(dx, dy);
event.recordNew();
eventUtils.fire(event);
@@ -2087,7 +2087,7 @@ export class Block implements IASTNodeLocation, IDeletable {
}
}
export interface CommentModel {
text: string | null;
text: string|null;
pinned: boolean;
size: Size;
}
+24 -24
View File
@@ -13,9 +13,9 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as dom from './utils/dom.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
/** A bounding box for a cloned block. */
interface CloneRect {
@@ -48,7 +48,7 @@ export function disposeUiEffect(block: BlockSvg) {
// AnyDuringMigration because: Property 'setAttribute' does not exist on type
// 'Node'.
(clone as AnyDuringMigration)
.setAttribute('transform', 'translate(' + xy.x + ',' + xy.y + ')');
.setAttribute('transform', 'translate(' + xy.x + ',' + xy.y + ')');
workspace.getParentSvg().appendChild(clone);
const cloneRect =
{'x': xy.x, 'y': xy.y, 'width': block.width, 'height': block.height};
@@ -56,8 +56,8 @@ export function disposeUiEffect(block: BlockSvg) {
// AnyDuringMigration because: Argument of type 'Node' is not assignable to
// parameter of type 'Element'.
disposeUiStep(
clone as AnyDuringMigration, cloneRect, workspace.RTL, new Date(),
workspace.scale);
clone as AnyDuringMigration, cloneRect, workspace.RTL, new Date(),
workspace.scale);
}
/**
* Animate a cloned block and eventually dispose of it.
@@ -70,21 +70,21 @@ export function disposeUiEffect(block: BlockSvg) {
* @param workspaceScale Scale of workspace.
*/
function disposeUiStep(
clone: Element, rect: CloneRect, rtl: boolean, start: Date,
workspaceScale: number) {
clone: Element, rect: CloneRect, rtl: boolean, start: Date,
workspaceScale: number) {
const ms = new Date().getTime() - start.getTime();
const percent = ms / 150;
if (percent > 1) {
dom.removeNode(clone);
} else {
const x =
rect.x + (rtl ? -1 : 1) * rect.width * workspaceScale / 2 * percent;
rect.x + (rtl ? -1 : 1) * rect.width * workspaceScale / 2 * percent;
const y = rect.y + rect.height * workspaceScale * percent;
const scale = (1 - percent) * workspaceScale;
clone.setAttribute(
'transform',
'translate(' + x + ',' + y + ')' +
' scale(' + scale + ')');
'transform',
'translate(' + x + ',' + y + ')' +
' scale(' + scale + ')');
setTimeout(disposeUiStep, 10, clone, rect, rtl, start, workspaceScale);
}
}
@@ -113,15 +113,15 @@ export function connectionUiEffect(block: BlockSvg) {
xy.y += 3 * scale;
}
const ripple = dom.createSvgElement(
Svg.CIRCLE, {
'cx': xy.x,
'cy': xy.y,
'r': 0,
'fill': 'none',
'stroke': '#888',
'stroke-width': 10,
},
workspace.getParentSvg());
Svg.CIRCLE, {
'cx': xy.x,
'cy': xy.y,
'r': 0,
'fill': 'none',
'stroke': '#888',
'stroke-width': 10,
},
workspace.getParentSvg());
// Start the animation.
connectionUiStep(ripple, new Date(), scale);
}
@@ -188,15 +188,15 @@ function disconnectUiStep(group: SVGElement, magnitude: number, start: Date) {
(group as AnyDuringMigration).skew_ = '';
} else {
const skew = Math.round(
Math.sin(percent * Math.PI * WIGGLES) * (1 - percent) * magnitude);
Math.sin(percent * Math.PI * WIGGLES) * (1 - percent) * magnitude);
(group as AnyDuringMigration).skew_ = 'skewX(' + skew + ')';
disconnectGroup = group;
disconnectPid = setTimeout(disconnectUiStep, 10, group, magnitude, start);
}
group.setAttribute(
'transform',
(group as AnyDuringMigration).translate_ +
(group as AnyDuringMigration).skew_);
'transform',
(group as AnyDuringMigration).translate_ +
(group as AnyDuringMigration).skew_);
}
/**
+19 -19
View File
@@ -25,9 +25,9 @@
* @class
*/
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
import * as svgMath from './utils/svg_math.js';
@@ -38,13 +38,13 @@ import * as svgMath from './utils/svg_math.js';
*/
export class BlockDragSurfaceSvg {
/** The SVG drag surface. Set once by BlockDragSurfaceSvg.createDom. */
private SVG_: SVGElement | null = null;
private SVG_: SVGElement|null = null;
/**
* This is where blocks live while they are being dragged if the drag
* surface is enabled.
*/
private dragGroup_: SVGElement | null = null;
private dragGroup_: SVGElement|null = null;
/**
* Cached value for the scale of the drag surface.
@@ -57,7 +57,7 @@ export class BlockDragSurfaceSvg {
* This translation is in pixel units, because the scale is applied to the
* drag group rather than the top-level SVG.
*/
private surfaceXY_: Coordinate | null = null;
private surfaceXY_: Coordinate|null = null;
private readonly childSurfaceXY_: Coordinate;
/** @param container Containing element. */
@@ -79,18 +79,18 @@ export class BlockDragSurfaceSvg {
}
// Already created.
this.SVG_ = dom.createSvgElement(
Svg.SVG, {
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
'version': '1.1',
'class': 'blocklyBlockDragSurface',
},
this.container);
Svg.SVG, {
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
'version': '1.1',
'class': 'blocklyBlockDragSurface',
},
this.container);
// AnyDuringMigration because: Argument of type 'SVGElement | null' is not
// assignable to parameter of type 'Element | undefined'.
this.dragGroup_ =
dom.createSvgElement(Svg.G, {}, this.SVG_ as AnyDuringMigration);
dom.createSvgElement(Svg.G, {}, this.SVG_ as AnyDuringMigration);
}
/**
@@ -142,8 +142,8 @@ export class BlockDragSurfaceSvg {
// AnyDuringMigration because: Argument of type 'SVGElement | null' is not
// assignable to parameter of type 'Element'.
dom.setCssTransform(
this.SVG_ as AnyDuringMigration,
'translate3d(' + x + 'px, ' + y + 'px, 0)');
this.SVG_ as AnyDuringMigration,
'translate3d(' + x + 'px, ' + y + 'px, 0)');
}
/**
@@ -186,7 +186,7 @@ export class BlockDragSurfaceSvg {
* BlockSvg.getRelativeToSurfaceXY).
* @return Drag surface group element.
*/
getGroup(): SVGElement | null {
getGroup(): SVGElement|null {
return this.dragGroup_;
}
@@ -194,7 +194,7 @@ export class BlockDragSurfaceSvg {
* Returns the SVG drag surface.
* @returns The SVG drag surface.
*/
getSvgRoot(): SVGElement | null {
getSvgRoot(): SVGElement|null {
return this.SVG_;
}
@@ -203,7 +203,7 @@ export class BlockDragSurfaceSvg {
* for BlockSvg.getRelativeToSurfaceXY).
* @return Drag surface block DOM element, or null if no blocks exist.
*/
getCurrentBlock(): Element | null {
getCurrentBlock(): Element|null {
return this.dragGroup_!.firstChild as Element;
}
+32 -31
View File
@@ -17,24 +17,24 @@ import './events/events_block_drag';
import * as blockAnimation from './block_animations.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as bumpObjects from './bump_objects.js';
import * as common from './common.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockMove } from './events/events_block_move.js';
import {BlockMove} from './events/events_block_move.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { Icon } from './icon.js';
import { InsertionMarkerManager } from './insertion_marker_manager.js';
import {Icon} from './icon.js';
import {InsertionMarkerManager} from './insertion_marker_manager.js';
/* eslint-disable-next-line no-unused-vars */
import { IBlockDragger } from './interfaces/i_block_dragger.js';
import {IBlockDragger} from './interfaces/i_block_dragger.js';
/* eslint-disable-next-line no-unused-vars */
import { IDragTarget } from './interfaces/i_drag_target.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
import * as registry from './registry.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -46,7 +46,7 @@ export class BlockDragger implements IBlockDragger {
protected draggedConnectionManager_: InsertionMarkerManager;
/** Which drag area the mouse pointer is over, if any. */
private dragTarget_: IDragTarget | null = null;
private dragTarget_: IDragTarget|null = null;
/** Whether the block would be deleted if dropped immediately. */
protected wouldDeleteBlock_ = false;
@@ -58,8 +58,8 @@ export class BlockDragger implements IBlockDragger {
* @param workspace The workspace to drag on.
*/
constructor(
private readonly block: BlockSvg,
private readonly workspace: WorkspaceSvg) {
private readonly block: BlockSvg,
private readonly workspace: WorkspaceSvg) {
/** Object that keeps track of connections on dragged blocks. */
this.draggedConnectionManager_ = new InsertionMarkerManager(this.block);
@@ -129,9 +129,9 @@ export class BlockDragger implements IBlockDragger {
*/
protected shouldDisconnect_(healStack: boolean): boolean {
return !!(
this.block.getParent() ||
healStack && this.block.nextConnection &&
this.block.nextConnection.targetBlock());
this.block.getParent() ||
healStack && this.block.nextConnection &&
this.block.nextConnection.targetBlock());
}
/**
@@ -141,7 +141,7 @@ export class BlockDragger implements IBlockDragger {
* at mouse down, in pixel units.
*/
protected disconnectBlock_(
healStack: boolean, currentDragDeltaXY: Coordinate) {
healStack: boolean, currentDragDeltaXY: Coordinate) {
this.block.unplug(healStack);
const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY);
const newLoc = Coordinate.sum(this.startXY_, delta);
@@ -154,7 +154,7 @@ export class BlockDragger implements IBlockDragger {
/** Fire a UI event at the start of a block drag. */
protected fireDragStartEvent_() {
const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))!
(this.block, true, this.block.getDescendants(false));
(this.block, true, this.block.getDescendants(false));
eventUtils.fire(event);
}
@@ -208,9 +208,9 @@ export class BlockDragger implements IBlockDragger {
blockAnimation.disconnectUiStop();
const preventMove =
!!this.dragTarget_ && this.dragTarget_.shouldPreventMove(this.block);
!!this.dragTarget_ && this.dragTarget_.shouldPreventMove(this.block);
let newLoc: Coordinate;
let delta: Coordinate | null = null;
let delta: Coordinate|null = null;
if (preventMove) {
newLoc = this.startXY_;
} else {
@@ -234,9 +234,9 @@ export class BlockDragger implements IBlockDragger {
// Blocks dragged directly from a flyout may need to be bumped into
// bounds.
bumpObjects.bumpIntoBounds(
this.block.workspace,
this.workspace.getMetricsManager().getScrollMetrics(true),
this.block);
this.block.workspace,
this.workspace.getMetricsManager().getScrollMetrics(true),
this.block);
}
}
this.workspace.setResizesEnabled(true);
@@ -251,7 +251,8 @@ export class BlockDragger implements IBlockDragger {
* @return New location after drag. delta is in workspace units. newLocation
* is the new coordinate where the block should end up.
*/
protected getNewLocationAfterDrag_(currentDragDeltaXY: Coordinate): { delta: Coordinate, newLocation: Coordinate } {
protected getNewLocationAfterDrag_(currentDragDeltaXY: Coordinate):
{delta: Coordinate, newLocation: Coordinate} {
const delta = this.pixelsToWorkspaceUnits_(currentDragDeltaXY);
const newLocation = Coordinate.sum(this.startXY_, delta);
return {
@@ -297,7 +298,7 @@ export class BlockDragger implements IBlockDragger {
/** Fire a UI event at the end of a block drag. */
protected fireDragEndEvent_() {
const event = new (eventUtils.get(eventUtils.BLOCK_DRAG))!
(this.block, false, this.block.getDescendants(false));
(this.block, false, this.block.getDescendants(false));
eventUtils.fire(event);
}
@@ -312,20 +313,20 @@ export class BlockDragger implements IBlockDragger {
if (toolbox) {
const style = this.block.isDeletable() ? 'blocklyToolboxDelete' :
'blocklyToolboxGrab';
'blocklyToolboxGrab';
// AnyDuringMigration because: Property 'removeStyle' does not exist on
// type 'IToolbox'.
if (isEnd &&
typeof (toolbox as AnyDuringMigration).removeStyle === 'function') {
typeof (toolbox as AnyDuringMigration).removeStyle === 'function') {
// AnyDuringMigration because: Property 'removeStyle' does not exist on
// type 'IToolbox'.
(toolbox as AnyDuringMigration).removeStyle(style);
// AnyDuringMigration because: Property 'addStyle' does not exist on
// type 'IToolbox'.
} else if (
!isEnd &&
typeof (toolbox as AnyDuringMigration).addStyle === 'function') {
!isEnd &&
typeof (toolbox as AnyDuringMigration).addStyle === 'function') {
// AnyDuringMigration because: Property 'addStyle' does not exist on
// type 'IToolbox'.
(toolbox as AnyDuringMigration).addStyle(style);
@@ -336,7 +337,7 @@ export class BlockDragger implements IBlockDragger {
/** Fire a move event at the end of a block drag. */
protected fireMoveEvent_() {
const event =
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(this.block) as BlockMove;
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(this.block) as BlockMove;
event.oldCoordinate = this.startXY_;
event.recordNew();
eventUtils.fire(event);
@@ -360,8 +361,8 @@ export class BlockDragger implements IBlockDragger {
*/
protected pixelsToWorkspaceUnits_(pixelCoord: Coordinate): Coordinate {
const result = new Coordinate(
pixelCoord.x / this.workspace.scale,
pixelCoord.y / this.workspace.scale);
pixelCoord.x / this.workspace.scale,
pixelCoord.y / this.workspace.scale);
if (this.workspace.isMutator) {
// If we're in a mutator, its scale is always 1, purely because of some
// oddities in our rendering optimizations. The actual scale is the same
@@ -393,7 +394,7 @@ export class BlockDragger implements IBlockDragger {
getInsertionMarkers(): BlockSvg[] {
// No insertion markers with the old style of dragged connection managers.
if (this.draggedConnectionManager_ &&
this.draggedConnectionManager_.getInsertionMarkers) {
this.draggedConnectionManager_.getInsertionMarkers) {
return this.draggedConnectionManager_.getInsertionMarkers();
}
return [];
+103 -103
View File
@@ -19,61 +19,61 @@ import './events/events_selected';
// Unused import preserved for side-effects. Remove if unneeded.
import './touch';
import { Block } from './block.js';
import {Block} from './block.js';
import * as blockAnimations from './block_animations.js';
import * as browserEvents from './browser_events.js';
/* eslint-disable-next-line no-unused-vars */
import { Comment } from './comment.js';
import {Comment} from './comment.js';
import * as common from './common.js';
import { config } from './config.js';
import {config} from './config.js';
/* eslint-disable-next-line no-unused-vars */
import { Connection } from './connection.js';
import { ConnectionType } from './connection_type.js';
import {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 {ContextMenuOption, ContextMenuRegistry, LegacyContextMenuOption} from './contextmenu_registry.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockMove } from './events/events_block_move.js';
import {BlockMove} from './events/events_block_move.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import { FieldLabel } from './field_label.js';
import {Field} from './field.js';
import {FieldLabel} from './field_label.js';
/* eslint-disable-next-line no-unused-vars */
import { Icon } from './icon.js';
import {Icon} from './icon.js';
/* eslint-disable-next-line no-unused-vars */
import { Input } from './input.js';
import {Input} from './input.js';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocationSvg } from './interfaces/i_ast_node_location_svg.js';
import {IASTNodeLocationSvg} from './interfaces/i_ast_node_location_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { IBoundedElement } from './interfaces/i_bounded_element.js';
import { CopyData, ICopyable } from './interfaces/i_copyable.js';
import {IBoundedElement} from './interfaces/i_bounded_element.js';
import {CopyData, ICopyable} from './interfaces/i_copyable.js';
/* eslint-disable-next-line no-unused-vars */
import { IDraggable } from './interfaces/i_draggable.js';
import {IDraggable} from './interfaces/i_draggable.js';
import * as internalConstants from './internal_constants.js';
import { ASTNode } from './keyboard_nav/ast_node.js';
import { TabNavigateCursor } from './keyboard_nav/tab_navigate_cursor.js';
import { MarkerManager } from './marker_manager.js';
import { Msg } from './msg.js';
import {ASTNode} from './keyboard_nav/ast_node.js';
import {TabNavigateCursor} from './keyboard_nav/tab_navigate_cursor.js';
import {MarkerManager} from './marker_manager.js';
import {Msg} from './msg.js';
/* eslint-disable-next-line no-unused-vars */
import { Mutator } from './mutator.js';
import { RenderedConnection } from './rendered_connection.js';
import {Mutator} from './mutator.js';
import {RenderedConnection} from './rendered_connection.js';
/* eslint-disable-next-line no-unused-vars */
import { Debug as BlockRenderingDebug } from './renderers/common/debugger.js';
import {Debug as BlockRenderingDebug} from './renderers/common/debugger.js';
/* eslint-disable-next-line no-unused-vars */
import { IPathObject } from './renderers/common/i_path_object.js';
import {IPathObject} from './renderers/common/i_path_object.js';
import * as blocks from './serialization/blocks.js';
import { BlockStyle } from './theme.js';
import {BlockStyle} from './theme.js';
import * as Tooltip from './tooltip.js';
import { Coordinate } from './utils/coordinate.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 {Rect} from './utils/rect.js';
import {Svg} from './utils/svg.js';
import * as svgMath from './utils/svg_math.js';
/* eslint-disable-next-line no-unused-vars */
import { Warning } from './warning.js';
import { Workspace } from './workspace.js';
import {Warning} from './warning.js';
import {Workspace} from './workspace.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -82,8 +82,8 @@ import { WorkspaceSvg } from './workspace_svg.js';
* @alias Blockly.BlockSvg
*/
export class BlockSvg extends Block implements IASTNodeLocationSvg,
IBoundedElement, ICopyable,
IDraggable {
IBoundedElement, ICopyable,
IDraggable {
/**
* Constant for identifying rows that are to be rendered inline.
* Don't collide with Blockly.inputTypes.
@@ -96,17 +96,17 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* the block.
*/
static readonly COLLAPSED_WARNING_ID = 'TEMP_COLLAPSED_WARNING_';
override decompose?: ((p1: Workspace) => BlockSvg) | null;
override decompose?: ((p1: Workspace) => BlockSvg)|null;
// override compose?: ((p1: BlockSvg) => void)|null;
saveConnections?: ((p1: BlockSvg) => AnyDuringMigration) | null;
saveConnections?: ((p1: BlockSvg) => AnyDuringMigration)|null;
customContextMenu?:
((p1: Array<ContextMenuOption | LegacyContextMenuOption>) =>
AnyDuringMigration) | null;
((p1: Array<ContextMenuOption|LegacyContextMenuOption>) =>
AnyDuringMigration)|null;
/**
* An property used internally to reference the block's rendering debugger.
*/
renderingDebugger: BlockRenderingDebug | null = null;
renderingDebugger: BlockRenderingDebug|null = null;
/**
* Height of this block, not including any statement blocks above or below.
@@ -126,16 +126,16 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
// AnyDuringMigration because: Type 'null' is not assignable to type '{ [key:
// string]: number; }'.
private warningTextDb_: { [key: string]: number } = null as AnyDuringMigration;
private warningTextDb_: {[key: string]: number} = null as AnyDuringMigration;
/** Block's mutator icon (if any). */
mutator: Mutator | null = null;
mutator: Mutator|null = null;
/** Block's comment icon (if any). */
private commentIcon_: Comment | null = null;
private commentIcon_: Comment|null = null;
/** Block's warning icon (if any). */
warning: Warning | null = null;
warning: Warning|null = null;
// Create core elements for the block.
private svgGroup_: SVGGElement;
@@ -207,14 +207,14 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
/** The renderer's path object. */
this.pathObject =
workspace.getRenderer().makePathObject(this.svgGroup_, this.style);
workspace.getRenderer().makePathObject(this.svgGroup_, this.style);
/**
* Whether to move the block to the drag surface when it is dragged.
* True if it should move, false if it should be translated directly.
*/
this.useDragSurface_ =
svgMath.is3dSupported() && !!workspace.getBlockDragSurface();
svgMath.is3dSupported() && !!workspace.getBlockDragSurface();
const svgPath = this.pathObject.svgPath;
(svgPath as AnyDuringMigration).tooltip = this;
@@ -258,7 +258,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Get the secondary colour of a block.
* @return #RRGGBB string.
*/
getColourSecondary(): string | null {
getColourSecondary(): string|null {
return this.style.colourSecondary;
}
@@ -266,7 +266,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Get the tertiary colour of a block.
* @return #RRGGBB string.
*/
getColourTertiary(): string | null {
getColourTertiary(): string|null {
return this.style.colourTertiary;
}
@@ -295,7 +295,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
}
}
const event = new (eventUtils.get(eventUtils.SELECTED))!
(oldId, this.id, this.workspace.id);
(oldId, this.id, this.workspace.id);
eventUtils.fire(event);
common.setSelected(this);
this.addSelect();
@@ -310,7 +310,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
return;
}
const event = new (eventUtils.get(eventUtils.SELECTED))!
(this.id, null, this.workspace.id);
(this.id, null, this.workspace.id);
event.workspaceId = this.workspace.id;
eventUtils.fire(event);
common.setSelected(null);
@@ -339,7 +339,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Sets the parent of this block to be a new block or null.
* @param newParent New parent block.
*/
override setParent(newParent: this | null) {
override setParent(newParent: this|null) {
const oldParent = this.parentBlock_;
if (newParent === oldParent) {
return;
@@ -388,8 +388,8 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
let y = 0;
const dragSurfaceGroup = this.useDragSurface_ ?
this.workspace.getBlockDragSurface()!.getGroup() :
null;
this.workspace.getBlockDragSurface()!.getGroup() :
null;
let element: SVGElement = this.getSvgRoot();
if (element) {
@@ -401,16 +401,16 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// If this element is the current element on the drag surface, include
// the translation of the drag surface itself.
if (this.useDragSurface_ &&
this.workspace.getBlockDragSurface()!.getCurrentBlock() ===
element) {
this.workspace.getBlockDragSurface()!.getCurrentBlock() ===
element) {
const surfaceTranslation =
this.workspace.getBlockDragSurface()!.getSurfaceTranslation();
this.workspace.getBlockDragSurface()!.getSurfaceTranslation();
x += surfaceTranslation.x;
y += surfaceTranslation.y;
}
element = element.parentNode as SVGElement;
} while (element && element !== this.workspace.getCanvas() &&
element !== dragSurfaceGroup);
element !== dragSurfaceGroup);
}
return new Coordinate(x, y);
}
@@ -425,7 +425,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
throw Error('Block has parent.');
}
const eventsEnabled = eventUtils.isEnabled();
let event: BlockMove | null = null;
let event: BlockMove|null = null;
if (eventsEnabled) {
event = new (eventUtils.get(eventUtils.BLOCK_MOVE))!(this) as BlockMove;
}
@@ -447,7 +447,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
translate(x: number, y: number) {
this.getSvgRoot().setAttribute(
'transform', 'translate(' + x + ',' + y + ')');
'transform', 'translate(' + x + ',' + y + ')');
}
/**
@@ -496,7 +496,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// Translate to current position, turning off 3d.
this.translate(newXY.x, newXY.y);
this.workspace.getBlockDragSurface()!.clearAndHide(
this.workspace.getCanvas());
this.workspace.getCanvas());
}
/**
@@ -508,15 +508,15 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
moveDuringDrag(newLoc: Coordinate) {
if (this.useDragSurface_) {
this.workspace.getBlockDragSurface()!.translateSurface(
newLoc.x, newLoc.y);
newLoc.x, newLoc.y);
} else {
(this.svgGroup_ as AnyDuringMigration).translate_ =
'translate(' + newLoc.x + ',' + newLoc.y + ')';
'translate(' + newLoc.x + ',' + newLoc.y + ')';
(this.svgGroup_ as AnyDuringMigration)
.setAttribute(
'transform',
(this.svgGroup_ as AnyDuringMigration).translate_ +
(this.svgGroup_ as AnyDuringMigration).skew_);
.setAttribute(
'transform',
(this.svgGroup_ as AnyDuringMigration).translate_ +
(this.svgGroup_ as AnyDuringMigration).skew_);
}
}
@@ -555,9 +555,9 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
const half = spacing / 2;
const xy = this.getRelativeToSurfaceXY();
const dx =
Math.round(Math.round((xy.x - half) / spacing) * spacing + half - xy.x);
Math.round(Math.round((xy.x - half) / spacing) * spacing + half - xy.x);
const dy =
Math.round(Math.round((xy.y - half) / spacing) * spacing + half - xy.y);
Math.round(Math.round((xy.y - half) / spacing) * spacing + half - xy.y);
if (dx || dy) {
this.moveBy(dx, dy);
}
@@ -646,11 +646,11 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
return;
}
const input = this.getInput(collapsedInputName) ||
this.appendDummyInput(collapsedInputName);
this.appendDummyInput(collapsedInputName);
// AnyDuringMigration because: Argument of type 'FieldLabel' is not
// assignable to parameter of type 'string | Field'.
input.appendField(
new FieldLabel(text) as AnyDuringMigration, collapsedFieldName);
new FieldLabel(text) as AnyDuringMigration, collapsedFieldName);
}
/**
@@ -695,7 +695,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
/** Load the block's help page in a new window. */
showHelp() {
const url =
typeof this.helpUrl === 'function' ? this.helpUrl() : this.helpUrl;
typeof this.helpUrl === 'function' ? this.helpUrl() : this.helpUrl;
if (url) {
window.open(url);
}
@@ -706,15 +706,15 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* @return Context menu options or null if no menu.
*/
protected generateContextMenu():
Array<ContextMenuOption | LegacyContextMenuOption> | null {
Array<ContextMenuOption|LegacyContextMenuOption>|null {
if (this.workspace.options.readOnly || !this.contextMenu) {
return null;
}
// AnyDuringMigration because: Argument of type '{ block: this; }' is not
// assignable to parameter of type 'Scope'.
const menuOptions = ContextMenuRegistry.registry.getContextMenuOptions(
ContextMenuRegistry.ScopeType.BLOCK,
{ block: this } as AnyDuringMigration);
ContextMenuRegistry.ScopeType.BLOCK,
{block: this} as AnyDuringMigration);
// Allow the block to add or modify menuOptions.
if (this.customContextMenu) {
@@ -831,7 +831,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
this.isInsertionMarker_ = insertionMarker;
if (this.isInsertionMarker_) {
this.setColour(
this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR);
this.workspace.getRenderer().getConstants().INSERTION_MARKER_COLOUR);
this.pathObject.updateInsertionMarker(true);
}
}
@@ -932,7 +932,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
this.dispose(false, true);
} else {
this.dispose(/* heal */
true, true);
true, true);
}
eventUtils.setGroup(false);
}
@@ -941,7 +941,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Encode a block for copying.
* @return Copy metadata, or null if the block is an insertion marker.
*/
toCopyData(): CopyData | null {
toCopyData(): CopyData|null {
if (this.isInsertionMarker_) {
return null;
}
@@ -950,9 +950,9 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// 'this' is not assignable to parameter of type 'Block'.
return {
saveInfo: blocks.save(
this as AnyDuringMigration,
{ addCoordinates: true, addNextBlocks: false }) as
blocks.State,
this as AnyDuringMigration,
{addCoordinates: true, addNextBlocks: false}) as
blocks.State,
source: this.workspace,
typeCounts: common.getBlockTypeCounts(this as AnyDuringMigration, true),
};
@@ -996,7 +996,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* comment.
* @return The comment icon attached to this block, or null.
*/
getCommentIcon(): Comment | null {
getCommentIcon(): Comment|null {
return this.commentIcon_;
}
@@ -1004,7 +1004,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Set this block's comment text.
* @param text The text, or null to delete.
*/
override setCommentText(text: string | null) {
override setCommentText(text: string|null) {
// AnyDuringMigration because: Property 'get' does not exist on type
// '(name: string) => void'.
if (this.commentModel.text === text) {
@@ -1043,7 +1043,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* @param opt_id An optional ID for the warning text to be able to maintain
* multiple warnings.
*/
override setWarningText(text: string | null, opt_id?: string) {
override setWarningText(text: string|null, opt_id?: string) {
if (!this.warningTextDb_) {
// Create a database of warning PIDs.
// Only runs once per block (and only those with warnings).
@@ -1065,7 +1065,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// Don't change the warning text during a drag.
// Wait until the drag finishes.
const thisBlock = this;
this.warningTextDb_[id] = setTimeout(function () {
this.warningTextDb_[id] = setTimeout(function() {
if (thisBlock.workspace) {
// Check block wasn't deleted.
delete thisBlock.warningTextDb_[id];
@@ -1091,7 +1091,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
}
if (collapsedParent) {
collapsedParent.setWarningText(
Msg['COLLAPSED_WARNINGS_WARNING'], BlockSvg.COLLAPSED_WARNING_ID);
Msg['COLLAPSED_WARNINGS_WARNING'], BlockSvg.COLLAPSED_WARNING_ID);
}
if (!this.warning) {
@@ -1125,7 +1125,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Give this block a mutator dialog.
* @param mutator A mutator dialog instance or null to remove.
*/
override setMutator(mutator: Mutator | null) {
override setMutator(mutator: Mutator|null) {
if (this.mutator && this.mutator !== mutator) {
this.mutator.dispose();
}
@@ -1208,11 +1208,11 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Change the colour of a block.
* @param colour HSV hue value, or #RRGGBB string.
*/
override setColour(colour: number | string) {
override setColour(colour: number|string) {
super.setColour(colour);
const styleObj =
this.workspace.getRenderer().getConstants().getBlockStyleForColour(
this.colour_);
this.workspace.getRenderer().getConstants().getBlockStyleForColour(
this.colour_);
this.pathObject.setStyle(styleObj.style);
this.style = styleObj.style;
@@ -1228,8 +1228,8 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
override setStyle(blockStyleName: string) {
const blockStyle =
this.workspace.getRenderer().getConstants().getBlockStyle(
blockStyleName);
this.workspace.getRenderer().getConstants().getBlockStyle(
blockStyleName);
this.styleName_ = blockStyleName;
if (blockStyle) {
@@ -1274,7 +1274,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* if any type could be connected.
*/
override setPreviousStatement(
newBoolean: boolean, opt_check?: string | string[] | null) {
newBoolean: boolean, opt_check?: string|string[]|null) {
super.setPreviousStatement(newBoolean, opt_check);
if (this.rendered) {
@@ -1290,7 +1290,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* if any type could be connected.
*/
override setNextStatement(
newBoolean: boolean, opt_check?: string | string[] | null) {
newBoolean: boolean, opt_check?: string|string[]|null) {
super.setNextStatement(newBoolean, opt_check);
if (this.rendered) {
@@ -1305,7 +1305,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* @param opt_check Returned type or list of returned types. Null or
* undefined if any type could be returned (e.g. variable get).
*/
override setOutput(newBoolean: boolean, opt_check?: string | string[] | null) {
override setOutput(newBoolean: boolean, opt_check?: string|string[]|null) {
super.setOutput(newBoolean, opt_check);
if (this.rendered) {
@@ -1463,7 +1463,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* @return The last next connection on the stack, or null.
*/
override lastConnectionInStack(ignoreShadows: boolean): RenderedConnection
| null {
|null {
return super.lastConnectionInStack(ignoreShadows) as RenderedConnection;
}
@@ -1476,7 +1476,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* @return The matching connection on this block, or null.
*/
override getMatchingConnection(otherBlock: Block, conn: Connection):
RenderedConnection | null {
RenderedConnection|null {
return super.getMatchingConnection(otherBlock, conn) as RenderedConnection;
}
@@ -1493,7 +1493,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Return the next statement block directly connected to this block.
* @return The next statement block or null.
*/
override getNextBlock(): BlockSvg | null {
override getNextBlock(): BlockSvg|null {
return super.getNextBlock() as BlockSvg;
}
@@ -1501,7 +1501,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* Returns the block connected to the previous connection.
* @return The previous statement block or null.
*/
override getPreviousBlock(): BlockSvg | null {
override getPreviousBlock(): BlockSvg|null {
return super.getPreviousBlock() as BlockSvg;
}
@@ -1561,13 +1561,13 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// Ensure that any snap and bump are part of this move's event group.
const group = eventUtils.getGroup();
setTimeout(function () {
setTimeout(function() {
eventUtils.setGroup(group);
block.snapToGrid();
eventUtils.setGroup(false);
}, config.bumpDelay / 2);
setTimeout(function () {
setTimeout(function() {
eventUtils.setGroup(group);
block.bumpNeighbours();
eventUtils.setGroup(false);
@@ -1583,12 +1583,12 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* block is positioned.
*/
positionNearConnection(
sourceConnection: RenderedConnection,
targetConnection: RenderedConnection) {
sourceConnection: RenderedConnection,
targetConnection: RenderedConnection) {
// We only need to position the new block if it's before the existing one,
// otherwise its position is set by the previous block.
if (sourceConnection.type === ConnectionType.NEXT_STATEMENT ||
sourceConnection.type === ConnectionType.INPUT_VALUE) {
sourceConnection.type === ConnectionType.INPUT_VALUE) {
const dx = targetConnection.x - sourceConnection.x;
const dy = targetConnection.y - sourceConnection.y;
@@ -1597,7 +1597,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
}
/** @return The first statement connection or null. */
override getFirstStatementConnection(): RenderedConnection | null {
override getFirstStatementConnection(): RenderedConnection|null {
return super.getFirstStatementConnection() as RenderedConnection | null;
}
@@ -1719,7 +1719,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
* and any blocks stacked below it.
* @return Object with height and width properties in workspace units.
*/
getHeightWidth(): { height: number, width: number } {
getHeightWidth(): {height: number, width: number} {
let height = this.height;
let width = this.width;
// Recursively add size of subsequent blocks.
@@ -1731,7 +1731,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
height += nextHeightWidth.height - tabHeight;
width = Math.max(width, nextHeightWidth.width);
}
return { height, width };
return {height, width};
}
/**
+281 -281
View File
@@ -22,117 +22,117 @@ import './events/events_ui_base';
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_var_create';
import { Block } from './block.js';
import {Block} from './block.js';
import * as blockAnimations from './block_animations.js';
import { BlockDragSurfaceSvg } from './block_drag_surface.js';
import { BlockDragger } from './block_dragger.js';
import { BlockSvg } from './block_svg.js';
import { BlocklyOptions } from './blockly_options.js';
import { Blocks } from './blocks.js';
import {BlockDragSurfaceSvg} from './block_drag_surface.js';
import {BlockDragger} from './block_dragger.js';
import {BlockSvg} from './block_svg.js';
import {BlocklyOptions} from './blockly_options.js';
import {Blocks} from './blocks.js';
import * as browserEvents from './browser_events.js';
import { Bubble } from './bubble.js';
import { BubbleDragger } from './bubble_dragger.js';
import {Bubble} from './bubble.js';
import {BubbleDragger} from './bubble_dragger.js';
import * as bumpObjects from './bump_objects.js';
import * as clipboard from './clipboard.js';
import { Comment } from './comment.js';
import {Comment} from './comment.js';
import * as common from './common.js';
import { ComponentManager } from './component_manager.js';
import { config } from './config.js';
import { Connection } from './connection.js';
import { ConnectionChecker } from './connection_checker.js';
import { ConnectionDB } from './connection_db.js';
import { ConnectionType } from './connection_type.js';
import {ComponentManager} from './component_manager.js';
import {config} from './config.js';
import {Connection} from './connection.js';
import {ConnectionChecker} from './connection_checker.js';
import {ConnectionDB} from './connection_db.js';
import {ConnectionType} from './connection_type.js';
import * as ContextMenu from './contextmenu.js';
import * as ContextMenuItems from './contextmenu_items.js';
import { ContextMenuRegistry } from './contextmenu_registry.js';
import {ContextMenuRegistry} from './contextmenu_registry.js';
import * as Css from './css.js';
import { DeleteArea } from './delete_area.js';
import {DeleteArea} from './delete_area.js';
import * as dialog from './dialog.js';
import { DragTarget } from './drag_target.js';
import {DragTarget} from './drag_target.js';
import * as dropDownDiv from './dropdowndiv.js';
import * as Events from './events/events.js';
import * as Extensions from './extensions.js';
import { Field } from './field.js';
import { FieldAngle } from './field_angle.js';
import { FieldCheckbox } from './field_checkbox.js';
import { FieldColour } from './field_colour.js';
import { FieldDropdown } from './field_dropdown.js';
import { FieldImage } from './field_image.js';
import { FieldLabel } from './field_label.js';
import { FieldLabelSerializable } from './field_label_serializable.js';
import { FieldMultilineInput } from './field_multilineinput.js';
import { FieldNumber } from './field_number.js';
import {Field} from './field.js';
import {FieldAngle} from './field_angle.js';
import {FieldCheckbox} from './field_checkbox.js';
import {FieldColour} from './field_colour.js';
import {FieldDropdown} from './field_dropdown.js';
import {FieldImage} from './field_image.js';
import {FieldLabel} from './field_label.js';
import {FieldLabelSerializable} from './field_label_serializable.js';
import {FieldMultilineInput} from './field_multilineinput.js';
import {FieldNumber} from './field_number.js';
import * as fieldRegistry from './field_registry.js';
import { FieldTextInput } from './field_textinput.js';
import { FieldVariable } from './field_variable.js';
import { Flyout } from './flyout_base.js';
import { FlyoutButton } from './flyout_button.js';
import { HorizontalFlyout } from './flyout_horizontal.js';
import { FlyoutMetricsManager } from './flyout_metrics_manager.js';
import { VerticalFlyout } from './flyout_vertical.js';
import { Generator } from './generator.js';
import { Gesture } from './gesture.js';
import { Grid } from './grid.js';
import { Icon } from './icon.js';
import { inject } from './inject.js';
import { Align, Input } from './input.js';
import { inputTypes } from './input_types.js';
import { InsertionMarkerManager } from './insertion_marker_manager.js';
import { IASTNodeLocation } from './interfaces/i_ast_node_location.js';
import { IASTNodeLocationSvg } from './interfaces/i_ast_node_location_svg.js';
import { IASTNodeLocationWithBlock } from './interfaces/i_ast_node_location_with_block.js';
import { IAutoHideable } from './interfaces/i_autohideable.js';
import { IBlockDragger } from './interfaces/i_block_dragger.js';
import { IBoundedElement } from './interfaces/i_bounded_element.js';
import { IBubble } from './interfaces/i_bubble.js';
import { ICollapsibleToolboxItem } from './interfaces/i_collapsible_toolbox_item.js';
import { IComponent } from './interfaces/i_component.js';
import { IConnectionChecker } from './interfaces/i_connection_checker.js';
import { IContextMenu } from './interfaces/i_contextmenu.js';
import { ICopyable } from './interfaces/i_copyable.js';
import { IDeletable } from './interfaces/i_deletable.js';
import { IDeleteArea } from './interfaces/i_delete_area.js';
import { IDragTarget } from './interfaces/i_drag_target.js';
import { IDraggable } from './interfaces/i_draggable.js';
import { IFlyout } from './interfaces/i_flyout.js';
import { IKeyboardAccessible } from './interfaces/i_keyboard_accessible.js';
import { IMetricsManager } from './interfaces/i_metrics_manager.js';
import { IMovable } from './interfaces/i_movable.js';
import { IPositionable } from './interfaces/i_positionable.js';
import { IRegistrable } from './interfaces/i_registrable.js';
import { IRegistrableField } from './interfaces/i_registrable_field.js';
import { ISelectable } from './interfaces/i_selectable.js';
import { ISelectableToolboxItem } from './interfaces/i_selectable_toolbox_item.js';
import { ISerializer as SerializerInterface } from './interfaces/i_serializer.js';
import { IStyleable } from './interfaces/i_styleable.js';
import { IToolbox } from './interfaces/i_toolbox.js';
import { IToolboxItem } from './interfaces/i_toolbox_item.js';
import {FieldTextInput} from './field_textinput.js';
import {FieldVariable} from './field_variable.js';
import {Flyout} from './flyout_base.js';
import {FlyoutButton} from './flyout_button.js';
import {HorizontalFlyout} from './flyout_horizontal.js';
import {FlyoutMetricsManager} from './flyout_metrics_manager.js';
import {VerticalFlyout} from './flyout_vertical.js';
import {Generator} from './generator.js';
import {Gesture} from './gesture.js';
import {Grid} from './grid.js';
import {Icon} from './icon.js';
import {inject} from './inject.js';
import {Align, Input} from './input.js';
import {inputTypes} from './input_types.js';
import {InsertionMarkerManager} from './insertion_marker_manager.js';
import {IASTNodeLocation} from './interfaces/i_ast_node_location.js';
import {IASTNodeLocationSvg} from './interfaces/i_ast_node_location_svg.js';
import {IASTNodeLocationWithBlock} from './interfaces/i_ast_node_location_with_block.js';
import {IAutoHideable} from './interfaces/i_autohideable.js';
import {IBlockDragger} from './interfaces/i_block_dragger.js';
import {IBoundedElement} from './interfaces/i_bounded_element.js';
import {IBubble} from './interfaces/i_bubble.js';
import {ICollapsibleToolboxItem} from './interfaces/i_collapsible_toolbox_item.js';
import {IComponent} from './interfaces/i_component.js';
import {IConnectionChecker} from './interfaces/i_connection_checker.js';
import {IContextMenu} from './interfaces/i_contextmenu.js';
import {ICopyable} from './interfaces/i_copyable.js';
import {IDeletable} from './interfaces/i_deletable.js';
import {IDeleteArea} from './interfaces/i_delete_area.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
import {IDraggable} from './interfaces/i_draggable.js';
import {IFlyout} from './interfaces/i_flyout.js';
import {IKeyboardAccessible} from './interfaces/i_keyboard_accessible.js';
import {IMetricsManager} from './interfaces/i_metrics_manager.js';
import {IMovable} from './interfaces/i_movable.js';
import {IPositionable} from './interfaces/i_positionable.js';
import {IRegistrable} from './interfaces/i_registrable.js';
import {IRegistrableField} from './interfaces/i_registrable_field.js';
import {ISelectable} from './interfaces/i_selectable.js';
import {ISelectableToolboxItem} from './interfaces/i_selectable_toolbox_item.js';
import {ISerializer as SerializerInterface} from './interfaces/i_serializer.js';
import {IStyleable} from './interfaces/i_styleable.js';
import {IToolbox} from './interfaces/i_toolbox.js';
import {IToolboxItem} from './interfaces/i_toolbox_item.js';
import * as internalConstants from './internal_constants.js';
import { ASTNode } from './keyboard_nav/ast_node.js';
import { BasicCursor } from './keyboard_nav/basic_cursor.js';
import { Cursor } from './keyboard_nav/cursor.js';
import { Marker } from './keyboard_nav/marker.js';
import { TabNavigateCursor } from './keyboard_nav/tab_navigate_cursor.js';
import { MarkerManager } from './marker_manager.js';
import { Menu } from './menu.js';
import { MenuItem } from './menuitem.js';
import { MetricsManager } from './metrics_manager.js';
import { Msg } from './msg.js';
import { Mutator } from './mutator.js';
import { Names } from './names.js';
import { Options } from './options.js';
import {ASTNode} from './keyboard_nav/ast_node.js';
import {BasicCursor} from './keyboard_nav/basic_cursor.js';
import {Cursor} from './keyboard_nav/cursor.js';
import {Marker} from './keyboard_nav/marker.js';
import {TabNavigateCursor} from './keyboard_nav/tab_navigate_cursor.js';
import {MarkerManager} from './marker_manager.js';
import {Menu} from './menu.js';
import {MenuItem} from './menuitem.js';
import {MetricsManager} from './metrics_manager.js';
import {Msg} from './msg.js';
import {Mutator} from './mutator.js';
import {Names} from './names.js';
import {Options} from './options.js';
import * as uiPosition from './positionable_helpers.js';
import * as Procedures from './procedures.js';
import * as registry from './registry.js';
import { RenderedConnection } from './rendered_connection.js';
import {RenderedConnection} from './rendered_connection.js';
import * as blockRendering from './renderers/common/block_rendering.js';
import * as constants from './renderers/common/constants.js';
import * as geras from './renderers/geras/geras.js';
import * as minimalist from './renderers/minimalist/minimalist.js';
import * as thrasos from './renderers/thrasos/thrasos.js';
import * as zelos from './renderers/zelos/zelos.js';
import { Scrollbar } from './scrollbar.js';
import { ScrollbarPair } from './scrollbar_pair.js';
import {Scrollbar} from './scrollbar.js';
import {ScrollbarPair} from './scrollbar_pair.js';
import * as serializationBlocks from './serialization/blocks.js';
import * as serializationExceptions from './serialization/exceptions.js';
import * as serializationPriorities from './serialization/priorities.js';
@@ -140,39 +140,39 @@ import * as serializationRegistry from './serialization/registry.js';
import * as serializationVariables from './serialization/variables.js';
import * as serializationWorkspaces from './serialization/workspaces.js';
import * as ShortcutItems from './shortcut_items.js';
import { ShortcutRegistry } from './shortcut_registry.js';
import { Theme } from './theme.js';
import {ShortcutRegistry} from './shortcut_registry.js';
import {Theme} from './theme.js';
import * as Themes from './theme/themes.js';
import { ThemeManager } from './theme_manager.js';
import { ToolboxCategory } from './toolbox/category.js';
import { CollapsibleToolboxCategory } from './toolbox/collapsible_category.js';
import { ToolboxSeparator } from './toolbox/separator.js';
import { Toolbox } from './toolbox/toolbox.js';
import { ToolboxItem } from './toolbox/toolbox_item.js';
import {ThemeManager} from './theme_manager.js';
import {ToolboxCategory} from './toolbox/category.js';
import {CollapsibleToolboxCategory} from './toolbox/collapsible_category.js';
import {ToolboxSeparator} from './toolbox/separator.js';
import {Toolbox} from './toolbox/toolbox.js';
import {ToolboxItem} from './toolbox/toolbox_item.js';
import * as Tooltip from './tooltip.js';
import * as Touch from './touch.js';
import { TouchGesture } from './touch_gesture.js';
import { Trashcan } from './trashcan.js';
import {TouchGesture} from './touch_gesture.js';
import {Trashcan} from './trashcan.js';
import * as utils from './utils.js';
import * as colour from './utils/colour.js';
import * as deprecation from './utils/deprecation.js';
import * as svgMath from './utils/svg_math.js';
import * as toolbox from './utils/toolbox.js';
import { VariableMap } from './variable_map.js';
import { VariableModel } from './variable_model.js';
import {VariableMap} from './variable_map.js';
import {VariableModel} from './variable_model.js';
import * as Variables from './variables.js';
import * as VariablesDynamic from './variables_dynamic.js';
import { Warning } from './warning.js';
import {Warning} from './warning.js';
import * as WidgetDiv from './widgetdiv.js';
import { Workspace } from './workspace.js';
import { WorkspaceAudio } from './workspace_audio.js';
import { WorkspaceComment } from './workspace_comment.js';
import { WorkspaceCommentSvg } from './workspace_comment_svg.js';
import { WorkspaceDragSurfaceSvg } from './workspace_drag_surface_svg.js';
import { WorkspaceDragger } from './workspace_dragger.js';
import { resizeSvgContents as realResizeSvgContents, WorkspaceSvg } from './workspace_svg.js';
import {Workspace} from './workspace.js';
import {WorkspaceAudio} from './workspace_audio.js';
import {WorkspaceComment} from './workspace_comment.js';
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
import {WorkspaceDragSurfaceSvg} from './workspace_drag_surface_svg.js';
import {WorkspaceDragger} from './workspace_dragger.js';
import {resizeSvgContents as realResizeSvgContents, WorkspaceSvg} from './workspace_svg.js';
import * as Xml from './xml.js';
import { ZoomControls } from './zoom_controls.js';
import {ZoomControls} from './zoom_controls.js';
/**
@@ -304,7 +304,7 @@ export function hideChaff(opt_onlyClosePopups?: boolean) {
// AnyDuringMigration because: Property 'getMainWorkspace' does not exist on
// type 'void'.
((common as AnyDuringMigration).getMainWorkspace() as WorkspaceSvg)
.hideChaff(opt_onlyClosePopups);
.hideChaff(opt_onlyClosePopups);
}
/**
@@ -329,7 +329,7 @@ export const getMainWorkspace = (common as AnyDuringMigration).getMainWorkspace;
// AnyDuringMigration because: Property 'defineBlocksWithJsonArray' does not
// exist on type 'void'.
export const defineBlocksWithJsonArray =
(common as AnyDuringMigration).defineBlocksWithJsonArray;
(common as AnyDuringMigration).defineBlocksWithJsonArray;
/**
* Set the parent container. This is the container element that the WidgetDiv,
* dropDownDiv, and Tooltip are rendered into the first time `Blockly.inject`
@@ -342,7 +342,7 @@ export const defineBlocksWithJsonArray =
// AnyDuringMigration because: Property 'setParentContainer' does not exist on
// type 'void'.
export const setParentContainer =
(common as AnyDuringMigration).setParentContainer;
(common as AnyDuringMigration).setParentContainer;
/**
@@ -365,8 +365,8 @@ export const svgSize = svgMath.svgSize;
*/
function resizeSvgContentsLocal(workspace: WorkspaceSvg) {
deprecation.warn(
'Blockly.resizeSvgContents', 'December 2021', 'December 2022',
'Blockly.WorkspaceSvg.resizeSvgContents');
'Blockly.resizeSvgContents', 'December 2021', 'December 2022',
'Blockly.WorkspaceSvg.resizeSvgContents');
realResizeSvgContents(workspace);
}
export const resizeSvgContents = resizeSvgContentsLocal;
@@ -380,8 +380,8 @@ export const resizeSvgContents = resizeSvgContentsLocal;
*/
export function copy(toCopy: ICopyable) {
deprecation.warn(
'Blockly.copy', 'December 2021', 'December 2022',
'Blockly.clipboard.copy');
'Blockly.copy', 'December 2021', 'December 2022',
'Blockly.clipboard.copy');
// AnyDuringMigration because: Property 'copy' does not exist on type 'void'.
(clipboard as AnyDuringMigration).copy(toCopy);
}
@@ -395,8 +395,8 @@ export function copy(toCopy: ICopyable) {
*/
export function paste(): boolean {
deprecation.warn(
'Blockly.paste', 'December 2021', 'December 2022',
'Blockly.clipboard.paste');
'Blockly.paste', 'December 2021', 'December 2022',
'Blockly.clipboard.paste');
// AnyDuringMigration because: Property 'paste' does not exist on type
// 'void'.
return !!(clipboard as AnyDuringMigration).paste();
@@ -411,8 +411,8 @@ export function paste(): boolean {
*/
export function duplicate(toDuplicate: ICopyable) {
deprecation.warn(
'Blockly.duplicate', 'December 2021', 'December 2022',
'Blockly.clipboard.duplicate');
'Blockly.duplicate', 'December 2021', 'December 2022',
'Blockly.clipboard.duplicate');
// AnyDuringMigration because: Property 'duplicate' does not exist on type
// 'void'.
(clipboard as AnyDuringMigration).duplicate(toDuplicate);
@@ -428,8 +428,8 @@ export function duplicate(toDuplicate: ICopyable) {
*/
export function isNumber(str: string): boolean {
deprecation.warn(
'Blockly.isNumber', 'December 2021', 'December 2022',
'Blockly.utils.string.isNumber');
'Blockly.isNumber', 'December 2021', 'December 2022',
'Blockly.utils.string.isNumber');
// AnyDuringMigration because: Property 'string' does not exist on type
// 'void'.
return (utils as AnyDuringMigration).string.isNumber(str);
@@ -445,8 +445,8 @@ export function isNumber(str: string): boolean {
*/
export function hueToHex(hue: number): string {
deprecation.warn(
'Blockly.hueToHex', 'December 2021', 'December 2022',
'Blockly.utils.colour.hueToHex');
'Blockly.hueToHex', 'December 2021', 'December 2022',
'Blockly.utils.colour.hueToHex');
return colour.hueToHex(hue);
}
@@ -465,11 +465,11 @@ export function hueToHex(hue: number): string {
* @alias Blockly.bindEvent_
*/
export function bindEvent_(
node: EventTarget, name: string, thisObject: AnyDuringMigration | null,
func: Function): browserEvents.Data {
node: EventTarget, name: string, thisObject: AnyDuringMigration|null,
func: Function): browserEvents.Data {
deprecation.warn(
'Blockly.bindEvent_', 'December 2021', 'December 2022',
'Blockly.browserEvents.bind');
'Blockly.bindEvent_', 'December 2021', 'December 2022',
'Blockly.browserEvents.bind');
return browserEvents.bind(node, name, thisObject, func);
}
@@ -484,8 +484,8 @@ export function bindEvent_(
*/
export function unbindEvent_(bindData: browserEvents.Data): Function {
deprecation.warn(
'Blockly.unbindEvent_', 'December 2021', 'December 2022',
'Blockly.browserEvents.unbind');
'Blockly.unbindEvent_', 'December 2021', 'December 2022',
'Blockly.browserEvents.unbind');
return browserEvents.unbind(bindData);
}
@@ -510,15 +510,15 @@ export function unbindEvent_(bindData: browserEvents.Data): Function {
* @alias Blockly.bindEventWithChecks_
*/
export function bindEventWithChecks_(
node: EventTarget, name: string, thisObject: AnyDuringMigration | null,
func: Function, opt_noCaptureIdentifier?: boolean,
opt_noPreventDefault?: boolean): browserEvents.Data {
node: EventTarget, name: string, thisObject: AnyDuringMigration|null,
func: Function, opt_noCaptureIdentifier?: boolean,
opt_noPreventDefault?: boolean): browserEvents.Data {
deprecation.warn(
'Blockly.bindEventWithChecks_', 'December 2021', 'December 2022',
'Blockly.browserEvents.conditionalBind');
'Blockly.bindEventWithChecks_', 'December 2021', 'December 2022',
'Blockly.browserEvents.conditionalBind');
return browserEvents.conditionalBind(
node, name, thisObject, func, opt_noCaptureIdentifier,
opt_noPreventDefault);
node, name, thisObject, func, opt_noCaptureIdentifier,
opt_noPreventDefault);
}
// Aliases to allow external code to access these values for legacy reasons.
@@ -530,11 +530,11 @@ export const DELETE_VARIABLE_ID = internalConstants.DELETE_VARIABLE_ID;
// AnyDuringMigration because: Property 'COLLAPSED_INPUT_NAME' does not exist
// on type 'void'.
export const COLLAPSED_INPUT_NAME =
(constants as AnyDuringMigration).COLLAPSED_INPUT_NAME;
(constants as AnyDuringMigration).COLLAPSED_INPUT_NAME;
// AnyDuringMigration because: Property 'COLLAPSED_FIELD_NAME' does not exist
// on type 'void'.
export const COLLAPSED_FIELD_NAME =
(constants as AnyDuringMigration).COLLAPSED_FIELD_NAME;
(constants as AnyDuringMigration).COLLAPSED_FIELD_NAME;
/**
* String for use in the "custom" attribute of a category in toolbox XML.
@@ -545,7 +545,7 @@ export const COLLAPSED_FIELD_NAME =
// AnyDuringMigration because: Property 'CATEGORY_NAME' does not exist on type
// 'void'.
export const VARIABLE_CATEGORY_NAME: string =
(Variables as AnyDuringMigration).CATEGORY_NAME;
(Variables as AnyDuringMigration).CATEGORY_NAME;
/**
* String for use in the "custom" attribute of a category in toolbox XML.
@@ -556,7 +556,7 @@ export const VARIABLE_CATEGORY_NAME: string =
// AnyDuringMigration because: Property 'CATEGORY_NAME' does not exist on type
// 'void'.
export const VARIABLE_DYNAMIC_CATEGORY_NAME: string =
(VariablesDynamic as AnyDuringMigration).CATEGORY_NAME;
(VariablesDynamic as AnyDuringMigration).CATEGORY_NAME;
/**
* String for use in the "custom" attribute of a category in toolbox XML.
* This string indicates that the category should be dynamically populated with
@@ -566,150 +566,150 @@ export const VARIABLE_DYNAMIC_CATEGORY_NAME: string =
// AnyDuringMigration because: Property 'CATEGORY_NAME' does not exist on type
// 'void'.
export const PROCEDURE_CATEGORY_NAME: string =
(Procedures as AnyDuringMigration).CATEGORY_NAME;
(Procedures as AnyDuringMigration).CATEGORY_NAME;
// Re-export submodules that no longer declareLegacyNamespace.
export { browserEvents };
export { ContextMenu };
export { ContextMenuItems };
export { Css };
export { Events };
export { Extensions };
export { Procedures };
export { ShortcutItems };
export { Themes };
export { Tooltip };
export { Touch };
export { Variables };
export { VariablesDynamic };
export { WidgetDiv };
export { Xml };
export { blockAnimations };
export { blockRendering };
export { bumpObjects };
export { clipboard };
export { common };
export { constants };
export { dialog };
export { fieldRegistry };
export { geras };
export { minimalist };
export { registry };
export { thrasos };
export { uiPosition };
export { utils };
export { zelos };
export { ASTNode };
export { BasicCursor };
export { Block };
export { BlocklyOptions };
export { BlockDragger };
export { BlockDragSurfaceSvg };
export { BlockSvg };
export { Blocks };
export { Bubble };
export { BubbleDragger };
export { CollapsibleToolboxCategory };
export { Comment };
export { ComponentManager };
export { Connection };
export { ConnectionType };
export { ConnectionChecker };
export { ConnectionDB };
export { ContextMenuRegistry };
export { Cursor };
export { DeleteArea };
export { DragTarget };
export {browserEvents};
export {ContextMenu};
export {ContextMenuItems};
export {Css};
export {Events};
export {Extensions};
export {Procedures};
export {ShortcutItems};
export {Themes};
export {Tooltip};
export {Touch};
export {Variables};
export {VariablesDynamic};
export {WidgetDiv};
export {Xml};
export {blockAnimations};
export {blockRendering};
export {bumpObjects};
export {clipboard};
export {common};
export {constants};
export {dialog};
export {fieldRegistry};
export {geras};
export {minimalist};
export {registry};
export {thrasos};
export {uiPosition};
export {utils};
export {zelos};
export {ASTNode};
export {BasicCursor};
export {Block};
export {BlocklyOptions};
export {BlockDragger};
export {BlockDragSurfaceSvg};
export {BlockSvg};
export {Blocks};
export {Bubble};
export {BubbleDragger};
export {CollapsibleToolboxCategory};
export {Comment};
export {ComponentManager};
export {Connection};
export {ConnectionType};
export {ConnectionChecker};
export {ConnectionDB};
export {ContextMenuRegistry};
export {Cursor};
export {DeleteArea};
export {DragTarget};
export const DropDownDiv = dropDownDiv;
export { Field };
export { FieldAngle };
export { FieldCheckbox };
export { FieldColour };
export { FieldDropdown };
export { FieldImage };
export { FieldLabel };
export { FieldLabelSerializable };
export { FieldMultilineInput };
export { FieldNumber };
export { FieldTextInput };
export { FieldVariable };
export { Flyout };
export { FlyoutButton };
export { FlyoutMetricsManager };
export { Generator };
export { Gesture };
export { Grid };
export { HorizontalFlyout };
export { IASTNodeLocation };
export { IASTNodeLocationSvg };
export { IASTNodeLocationWithBlock };
export { IAutoHideable };
export { IBlockDragger };
export { IBoundedElement };
export { IBubble };
export { ICollapsibleToolboxItem };
export { IComponent };
export { IConnectionChecker };
export { IContextMenu };
export { Icon };
export { ICopyable };
export { IDeletable };
export { IDeleteArea };
export { IDragTarget };
export { IDraggable };
export { IFlyout };
export { IKeyboardAccessible };
export { IMetricsManager };
export { IMovable };
export { Input };
export { InsertionMarkerManager };
export { IPositionable };
export { IRegistrable };
export { IRegistrableField };
export { ISelectable };
export { ISelectableToolboxItem };
export { IStyleable };
export { IToolbox };
export { IToolboxItem };
export { Marker };
export { MarkerManager };
export { Menu };
export { MenuItem };
export { MetricsManager };
export { Mutator };
export { Msg };
export { Names };
export { Options };
export { RenderedConnection };
export { Scrollbar };
export { ScrollbarPair };
export { ShortcutRegistry };
export { TabNavigateCursor };
export { Theme };
export { ThemeManager };
export { Toolbox };
export { ToolboxCategory };
export { ToolboxItem };
export { ToolboxSeparator };
export { TouchGesture };
export { Trashcan };
export { VariableMap };
export { VariableModel };
export { VerticalFlyout };
export { Warning };
export { Workspace };
export { WorkspaceAudio };
export { WorkspaceComment };
export { WorkspaceCommentSvg };
export { WorkspaceDragSurfaceSvg };
export { WorkspaceDragger };
export { WorkspaceSvg };
export { ZoomControls };
export { config };
export {Field};
export {FieldAngle};
export {FieldCheckbox};
export {FieldColour};
export {FieldDropdown};
export {FieldImage};
export {FieldLabel};
export {FieldLabelSerializable};
export {FieldMultilineInput};
export {FieldNumber};
export {FieldTextInput};
export {FieldVariable};
export {Flyout};
export {FlyoutButton};
export {FlyoutMetricsManager};
export {Generator};
export {Gesture};
export {Grid};
export {HorizontalFlyout};
export {IASTNodeLocation};
export {IASTNodeLocationSvg};
export {IASTNodeLocationWithBlock};
export {IAutoHideable};
export {IBlockDragger};
export {IBoundedElement};
export {IBubble};
export {ICollapsibleToolboxItem};
export {IComponent};
export {IConnectionChecker};
export {IContextMenu};
export {Icon};
export {ICopyable};
export {IDeletable};
export {IDeleteArea};
export {IDragTarget};
export {IDraggable};
export {IFlyout};
export {IKeyboardAccessible};
export {IMetricsManager};
export {IMovable};
export {Input};
export {InsertionMarkerManager};
export {IPositionable};
export {IRegistrable};
export {IRegistrableField};
export {ISelectable};
export {ISelectableToolboxItem};
export {IStyleable};
export {IToolbox};
export {IToolboxItem};
export {Marker};
export {MarkerManager};
export {Menu};
export {MenuItem};
export {MetricsManager};
export {Mutator};
export {Msg};
export {Names};
export {Options};
export {RenderedConnection};
export {Scrollbar};
export {ScrollbarPair};
export {ShortcutRegistry};
export {TabNavigateCursor};
export {Theme};
export {ThemeManager};
export {Toolbox};
export {ToolboxCategory};
export {ToolboxItem};
export {ToolboxSeparator};
export {TouchGesture};
export {Trashcan};
export {VariableMap};
export {VariableModel};
export {VerticalFlyout};
export {Warning};
export {Workspace};
export {WorkspaceAudio};
export {WorkspaceComment};
export {WorkspaceCommentSvg};
export {WorkspaceDragSurfaceSvg};
export {WorkspaceDragger};
export {WorkspaceSvg};
export {ZoomControls};
export {config};
/** @deprecated Use Blockly.ConnectionType instead. */
export const connectionTypes = ConnectionType;
export { inject };
export { inputTypes };
export {inject};
export {inputTypes};
export namespace serialization {
export const blocks = serializationBlocks;
export const exceptions = serializationExceptions;
@@ -731,5 +731,5 @@ export namespace serialization {
// Blockly.Msg module - so make sure it is, but only if there is not
// yet a Blockly global variable.
if (!('Blockly' in globalThis)) {
(globalThis as AnyDuringMigration)['Blockly'] = { 'Msg': Msg };
(globalThis as AnyDuringMigration)['Blockly'] = {'Msg': Msg};
}
+1 -1
View File
@@ -23,4 +23,4 @@ export type BlockDefinition = AnyDuringMigration;
* A mapping of block type names to block prototype objects.
* @alias Blockly.blocks.Blocks
*/
export const Blocks: { [key: string]: BlockDefinition } = Object.create(null);
export const Blocks: {[key: string]: BlockDefinition} = Object.create(null);
+12 -12
View File
@@ -56,9 +56,9 @@ const PAGE_MODE_MULTIPLIER = 125;
* @alias Blockly.browserEvents.conditionalBind
*/
export function conditionalBind(
node: EventTarget, name: string, thisObject: AnyDuringMigration | null,
func: Function, opt_noCaptureIdentifier?: boolean,
opt_noPreventDefault?: boolean): Data {
node: EventTarget, name: string, thisObject: AnyDuringMigration|null,
func: Function, opt_noCaptureIdentifier?: boolean,
opt_noPreventDefault?: boolean): Data {
let handled = false;
function wrapFunc(e: AnyDuringMigration) {
const captureIdentifier = !opt_noCaptureIdentifier;
@@ -126,8 +126,8 @@ export function conditionalBind(
* @alias Blockly.browserEvents.bind
*/
export function bind(
node: EventTarget, name: string, thisObject: AnyDuringMigration | null,
func: Function): Data {
node: EventTarget, name: string, thisObject: AnyDuringMigration|null,
func: Function): Data {
function wrapFunc(e: AnyDuringMigration) {
if (thisObject) {
func.call(thisObject, e);
@@ -200,16 +200,16 @@ export function unbind(bindData: Data): Function {
export function isTargetInput(e: Event): boolean {
if (e.target instanceof HTMLElement) {
if (e.target.isContentEditable ||
e.target.getAttribute('data-is-text-input') === 'true') {
e.target.getAttribute('data-is-text-input') === 'true') {
return true;
}
if (e.target instanceof HTMLInputElement) {
const target = e.target;
return target.type === 'text' || target.type === 'number' ||
target.type === 'email' || target.type === 'password' ||
target.type === 'search' || target.type === 'tel' ||
target.type === 'url';
target.type === 'email' || target.type === 'password' ||
target.type === 'search' || target.type === 'tel' ||
target.type === 'url';
}
if (e.target instanceof HTMLTextAreaElement) {
@@ -249,7 +249,7 @@ export function isRightButton(e: Event): boolean {
* @alias Blockly.browserEvents.mouseToSvg
*/
export function mouseToSvg(
e: Event, svg: SVGSVGElement, matrix: SVGMatrix | null): SVGPoint {
e: Event, svg: SVGSVGElement, matrix: SVGMatrix|null): SVGPoint {
const svgPoint = svg.createSVGPoint();
// AnyDuringMigration because: Property 'clientX' does not exist on type
// 'Event'.
@@ -270,12 +270,12 @@ export function mouseToSvg(
* @return Scroll delta object with .x and .y properties.
* @alias Blockly.browserEvents.getScrollDeltaPixels
*/
export function getScrollDeltaPixels(e: WheelEvent): { x: number, y: number } {
export function getScrollDeltaPixels(e: WheelEvent): {x: number, y: number} {
switch (e.deltaMode) {
case 0x00:
// Pixel mode.
default:
return { x: e.deltaX, y: e.deltaY };
return {x: e.deltaX, y: e.deltaY};
case 0x01:
// Line mode.
return {
+109 -109
View File
@@ -18,23 +18,23 @@ import './metrics_manager';
import './workspace';
/* eslint-disable-next-line no-unused-vars */
import { BlockDragSurfaceSvg } from './block_drag_surface.js';
import {BlockDragSurfaceSvg} from './block_drag_surface.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
/* eslint-disable-next-line no-unused-vars */
import { IBubble } from './interfaces/i_bubble.js';
import { ContainerRegion } from './metrics_manager.js';
import { Scrollbar } from './scrollbar.js';
import {IBubble} from './interfaces/i_bubble.js';
import {ContainerRegion} from './metrics_manager.js';
import {Scrollbar} from './scrollbar.js';
import * as Touch from './touch.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as math from './utils/math.js';
import { Size } from './utils/size.js';
import { Svg } from './utils/svg.js';
import {Size} from './utils/size.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -64,10 +64,10 @@ export class Bubble implements IBubble {
static ANCHOR_RADIUS = 8;
/** Mouse up event data. */
private static onMouseUpWrapper_: browserEvents.Data | null = null;
private static onMouseUpWrapper_: browserEvents.Data|null = null;
/** Mouse move event data. */
private static onMouseMoveWrapper_: browserEvents.Data | null = null;
private static onMouseMoveWrapper_: browserEvents.Data|null = null;
workspace_: AnyDuringMigration;
content_: AnyDuringMigration;
shape_: AnyDuringMigration;
@@ -125,16 +125,16 @@ export class Bubble implements IBubble {
private autoLayout_ = true;
/** Method to call on resize of bubble. */
private resizeCallback_: (() => AnyDuringMigration) | null = null;
private resizeCallback_: (() => AnyDuringMigration)|null = null;
/** Method to call on move of bubble. */
private moveCallback_: (() => AnyDuringMigration) | null = null;
private moveCallback_: (() => AnyDuringMigration)|null = null;
/** Mouse down on bubbleBack_ event data. */
private onMouseDownBubbleWrapper_: browserEvents.Data | null = null;
private onMouseDownBubbleWrapper_: browserEvents.Data|null = null;
/** Mouse down on resizeGroup_ event data. */
private onMouseDownResizeWrapper_: browserEvents.Data | null = null;
private onMouseDownResizeWrapper_: browserEvents.Data|null = null;
/**
* Describes whether this bubble has been disposed of (nodes and event
@@ -153,9 +153,9 @@ export class Bubble implements IBubble {
* @struct
*/
constructor(
workspace: WorkspaceSvg, content: SVGElement, shape: SVGElement,
anchorXY: Coordinate, bubbleWidth: number | null,
bubbleHeight: number | null) {
workspace: WorkspaceSvg, content: SVGElement, shape: SVGElement,
anchorXY: Coordinate, bubbleWidth: number|null,
bubbleHeight: number|null) {
this.rendered_ = false;
this.workspace_ = workspace;
this.content_ = content;
@@ -169,7 +169,7 @@ export class Bubble implements IBubble {
const canvas = workspace.getBubbleCanvas();
canvas.appendChild(
this.createDom_(content, !!(bubbleWidth && bubbleHeight)));
this.createDom_(content, !!(bubbleWidth && bubbleHeight)));
this.setAnchorLocation(anchorXY);
if (!bubbleWidth || !bubbleHeight) {
@@ -208,9 +208,9 @@ export class Bubble implements IBubble {
</g>
*/
this.bubbleGroup_ = dom.createSvgElement(Svg.G, {});
let filter: { filter?: string } = {
let filter: {filter?: string} = {
'filter': 'url(#' +
this.workspace_.getRenderer().getConstants().embossFilterId + ')',
this.workspace_.getRenderer().getConstants().embossFilterId + ')',
};
if (userAgent.JavaFx) {
// Multiple reports that JavaFX can't handle filters.
@@ -220,44 +220,44 @@ export class Bubble implements IBubble {
const bubbleEmboss = dom.createSvgElement(Svg.G, filter, this.bubbleGroup_);
this.bubbleArrow_ = dom.createSvgElement(Svg.PATH, {}, bubbleEmboss);
this.bubbleBack_ = dom.createSvgElement(
Svg.RECT, {
'class': 'blocklyDraggable',
'x': 0,
'y': 0,
'rx': Bubble.BORDER_WIDTH,
'ry': Bubble.BORDER_WIDTH,
},
bubbleEmboss);
Svg.RECT, {
'class': 'blocklyDraggable',
'x': 0,
'y': 0,
'rx': Bubble.BORDER_WIDTH,
'ry': Bubble.BORDER_WIDTH,
},
bubbleEmboss);
if (hasResize) {
this.resizeGroup_ = dom.createSvgElement(
Svg.G, {
'class': this.workspace_.RTL ? 'blocklyResizeSW' :
'blocklyResizeSE',
},
this.bubbleGroup_);
Svg.G, {
'class': this.workspace_.RTL ? 'blocklyResizeSW' :
'blocklyResizeSE',
},
this.bubbleGroup_);
const resizeSize = 2 * Bubble.BORDER_WIDTH;
dom.createSvgElement(
Svg.POLYGON,
{ 'points': '0,x x,x x,0'.replace(/x/g, resizeSize.toString()) },
this.resizeGroup_);
Svg.POLYGON,
{'points': '0,x x,x x,0'.replace(/x/g, resizeSize.toString())},
this.resizeGroup_);
dom.createSvgElement(
Svg.LINE, {
'class': 'blocklyResizeLine',
'x1': resizeSize / 3,
'y1': resizeSize - 1,
'x2': resizeSize - 1,
'y2': resizeSize / 3,
},
this.resizeGroup_);
Svg.LINE, {
'class': 'blocklyResizeLine',
'x1': resizeSize / 3,
'y1': resizeSize - 1,
'x2': resizeSize - 1,
'y2': resizeSize / 3,
},
this.resizeGroup_);
dom.createSvgElement(
Svg.LINE, {
'class': 'blocklyResizeLine',
'x1': resizeSize * 2 / 3,
'y1': resizeSize - 1,
'x2': resizeSize - 1,
'y2': resizeSize * 2 / 3,
},
this.resizeGroup_);
Svg.LINE, {
'class': 'blocklyResizeLine',
'x1': resizeSize * 2 / 3,
'y1': resizeSize - 1,
'x2': resizeSize - 1,
'y2': resizeSize * 2 / 3,
},
this.resizeGroup_);
} else {
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'SVGGElement'.
@@ -266,10 +266,10 @@ export class Bubble implements IBubble {
if (!this.workspace_.options.readOnly) {
this.onMouseDownBubbleWrapper_ = browserEvents.conditionalBind(
this.bubbleBack_, 'mousedown', this, this.bubbleMouseDown_);
this.bubbleBack_, 'mousedown', this, this.bubbleMouseDown_);
if (this.resizeGroup_) {
this.onMouseDownResizeWrapper_ = browserEvents.conditionalBind(
this.resizeGroup_, 'mousedown', this, this.resizeMouseDown_);
this.resizeGroup_, 'mousedown', this, this.resizeMouseDown_);
}
}
this.bubbleGroup_.appendChild(content);
@@ -340,14 +340,14 @@ export class Bubble implements IBubble {
}
// Left-click (or middle click)
this.workspace_.startDrag(
e,
new Coordinate(
this.workspace_.RTL ? -this.width_ : this.width_, this.height_));
e,
new Coordinate(
this.workspace_.RTL ? -this.width_ : this.width_, this.height_));
Bubble.onMouseUpWrapper_ = browserEvents.conditionalBind(
document, 'mouseup', this, Bubble.bubbleMouseUp_);
document, 'mouseup', this, Bubble.bubbleMouseUp_);
Bubble.onMouseMoveWrapper_ = browserEvents.conditionalBind(
document, 'mousemove', this, this.resizeMouseMove_);
document, 'mousemove', this, this.resizeMouseMove_);
this.workspace_.hideChaff();
// This event has been handled. No need to bubble up to the document.
e.stopPropagation();
@@ -416,7 +416,7 @@ export class Bubble implements IBubble {
private layoutBubble_() {
// Get the metrics in workspace units.
const viewMetrics =
this.workspace_.getMetricsManager().getViewMetrics(true);
this.workspace_.getMetricsManager().getViewMetrics(true);
const optimalLeft = this.getOptimalRelativeLeft_(viewMetrics);
const optimalTop = this.getOptimalRelativeTop_(viewMetrics);
@@ -425,29 +425,29 @@ export class Bubble implements IBubble {
const topPosition = {
x: optimalLeft,
y: -this.height_ -
this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT as
number,
this.workspace_.getRenderer().getConstants().MIN_BLOCK_HEIGHT as
number,
};
const startPosition = { x: -this.width_ - 30, y: optimalTop };
const endPosition = { x: bbox.width, y: optimalTop };
const bottomPosition = { x: optimalLeft, y: bbox.height };
const startPosition = {x: -this.width_ - 30, y: optimalTop};
const endPosition = {x: bbox.width, y: optimalTop};
const bottomPosition = {x: optimalLeft, y: bbox.height};
const closerPosition =
bbox.width < bbox.height ? endPosition : bottomPosition;
bbox.width < bbox.height ? endPosition : bottomPosition;
const fartherPosition =
bbox.width < bbox.height ? bottomPosition : endPosition;
bbox.width < bbox.height ? bottomPosition : endPosition;
const topPositionOverlap = this.getOverlap_(topPosition, viewMetrics);
const startPositionOverlap = this.getOverlap_(startPosition, viewMetrics);
const closerPositionOverlap = this.getOverlap_(closerPosition, viewMetrics);
const fartherPositionOverlap =
this.getOverlap_(fartherPosition, viewMetrics);
this.getOverlap_(fartherPosition, viewMetrics);
// Set the position to whichever position shows the most of the bubble,
// with tiebreaks going in the order: top > start > close > far.
const mostOverlap = Math.max(
topPositionOverlap, startPositionOverlap, closerPositionOverlap,
fartherPositionOverlap);
topPositionOverlap, startPositionOverlap, closerPositionOverlap,
fartherPositionOverlap);
if (topPositionOverlap === mostOverlap) {
this.relativeLeft_ = topPosition.x;
this.relativeTop_ = topPosition.y;
@@ -480,12 +480,12 @@ export class Bubble implements IBubble {
* @return The percentage of the bubble that is visible.
*/
private getOverlap_(
relativeMin: { x: number, y: number },
viewMetrics: ContainerRegion): number {
relativeMin: {x: number, y: number},
viewMetrics: ContainerRegion): number {
// The position of the top-left corner of the bubble in workspace units.
const bubbleMin = {
x: this.workspace_.RTL ? this.anchorXY_.x - relativeMin.x - this.width_ :
relativeMin.x + this.anchorXY_.x,
relativeMin.x + this.anchorXY_.x,
y: relativeMin.y + this.anchorXY_.y,
};
// The position of the bottom-right corner of the bubble in workspace units.
@@ -500,7 +500,7 @@ export class Bubble implements IBubble {
// the calculation.
// The position of the top-left corner of the workspace.
const workspaceMin = { x: viewMetrics.left, y: viewMetrics.top };
const workspaceMin = {x: viewMetrics.left, y: viewMetrics.top};
// The position of the bottom-right corner of the workspace.
const workspaceMax = {
x: viewMetrics.left + viewMetrics.width,
@@ -508,13 +508,13 @@ export class Bubble implements IBubble {
};
const overlapWidth = Math.min(bubbleMax.x, workspaceMax.x) -
Math.max(bubbleMin.x, workspaceMin.x);
Math.max(bubbleMin.x, workspaceMin.x);
const overlapHeight = Math.min(bubbleMax.y, workspaceMax.y) -
Math.max(bubbleMin.y, workspaceMin.y);
Math.max(bubbleMin.y, workspaceMin.y);
return Math.max(
0,
Math.min(
1, overlapWidth * overlapHeight / (this.width_ * this.height_)));
0,
Math.min(
1, overlapWidth * overlapHeight / (this.width_ * this.height_)));
}
/**
@@ -541,7 +541,7 @@ export class Bubble implements IBubble {
const workspaceRight = viewMetrics.left + viewMetrics.width;
const workspaceLeft = viewMetrics.left + // Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
Scrollbar.scrollbarThickness / this.workspace_.scale;
if (bubbleLeft < workspaceLeft) {
// Slide the bubble right until it is onscreen.
@@ -556,8 +556,8 @@ export class Bubble implements IBubble {
const workspaceLeft = viewMetrics.left;
const workspaceRight = viewMetrics.left +
viewMetrics.width - // Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
viewMetrics.width - // Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
if (bubbleLeft < workspaceLeft) {
// Slide the bubble right until it is onscreen.
@@ -591,8 +591,8 @@ export class Bubble implements IBubble {
const bubbleBottom = bubbleTop + this.height_;
const workspaceTop = viewMetrics.top;
const workspaceBottom = viewMetrics.top +
viewMetrics.height - // Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
viewMetrics.height - // Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
const anchorY = this.anchorXY_.y;
if (bubbleTop < workspaceTop) {
@@ -625,7 +625,7 @@ export class Bubble implements IBubble {
*/
moveTo(x: number, y: number) {
this.bubbleGroup_.setAttribute(
'transform', 'translate(' + x + ',' + y + ')');
'transform', 'translate(' + x + ',' + y + ')');
}
/**
@@ -669,14 +669,14 @@ export class Bubble implements IBubble {
// Mirror the resize group.
const resizeSize = 2 * Bubble.BORDER_WIDTH;
this.resizeGroup_.setAttribute(
'transform',
'translate(' + resizeSize + ',' + (height - doubleBorderWidth) +
') scale(-1 1)');
'transform',
'translate(' + resizeSize + ',' + (height - doubleBorderWidth) +
') scale(-1 1)');
} else {
this.resizeGroup_.setAttribute(
'transform',
'translate(' + (width - doubleBorderWidth) + ',' +
(height - doubleBorderWidth) + ')');
'transform',
'translate(' + (width - doubleBorderWidth) + ',' +
(height - doubleBorderWidth) + ')');
}
}
if (this.autoLayout_) {
@@ -727,7 +727,7 @@ export class Bubble implements IBubble {
// Calculate the thickness of the base of the arrow.
const bubbleSize = this.getBubbleSize();
let thickness =
(bubbleSize.width + bubbleSize.height) / Bubble.ARROW_THICKNESS;
(bubbleSize.width + bubbleSize.height) / Bubble.ARROW_THICKNESS;
thickness = Math.min(thickness, bubbleSize.width, bubbleSize.height) / 4;
// Back the tip of the arrow off of the anchor.
@@ -751,11 +751,11 @@ export class Bubble implements IBubble {
steps.push('M' + baseX1 + ',' + baseY1);
steps.push(
'C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) + ' ' +
relAnchorX + ',' + relAnchorY + ' ' + relAnchorX + ',' + relAnchorY);
'C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) + ' ' +
relAnchorX + ',' + relAnchorY + ' ' + relAnchorX + ',' + relAnchorY);
steps.push(
'C' + relAnchorX + ',' + relAnchorY + ' ' + (baseX2 + swirlRun) +
',' + (baseY2 + swirlRise) + ' ' + baseX2 + ',' + baseY2);
'C' + relAnchorX + ',' + relAnchorY + ' ' + (baseX2 + swirlRun) +
',' + (baseY2 + swirlRise) + ' ' + baseX2 + ',' + baseY2);
}
steps.push('z');
this.bubbleArrow_.setAttribute('d', steps.join(' '));
@@ -812,10 +812,10 @@ export class Bubble implements IBubble {
*/
getRelativeToSurfaceXY(): Coordinate {
return new Coordinate(
this.workspace_.RTL ?
-this.relativeLeft_ + this.anchorXY_.x - this.width_ :
this.anchorXY_.x + this.relativeLeft_,
this.anchorXY_.y + this.relativeTop_);
this.workspace_.RTL ?
-this.relativeLeft_ + this.anchorXY_.x - this.width_ :
this.anchorXY_.x + this.relativeLeft_,
this.anchorXY_.y + this.relativeTop_);
}
/**
@@ -862,7 +862,7 @@ export class Bubble implements IBubble {
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
const tspanElement = dom.createSvgElement(
Svg.TSPAN, { 'dy': '1em', 'x': Bubble.BORDER_WIDTH }, paragraph);
Svg.TSPAN, {'dy': '1em', 'x': Bubble.BORDER_WIDTH}, paragraph);
const textNode = document.createTextNode(lines[i]);
tspanElement.appendChild(textNode);
}
@@ -877,11 +877,11 @@ export class Bubble implements IBubble {
* @return The non editable bubble.
*/
static createNonEditableBubble(
paragraphElement: SVGTextElement, block: BlockSvg,
iconXY: Coordinate): Bubble {
paragraphElement: SVGTextElement, block: BlockSvg,
iconXY: Coordinate): Bubble {
const bubble = new Bubble(
(block.workspace), paragraphElement, block.pathObject.svgPath, (iconXY),
null, null);
(block.workspace), paragraphElement, block.pathObject.svgPath, (iconXY),
null, null);
// Expose this bubble's block's ID on its top-level SVG group.
bubble.setSvgId(block.id);
if (block.RTL) {
@@ -889,11 +889,11 @@ export class Bubble implements IBubble {
// This cannot be done until the bubble is rendered on screen.
const maxWidth = paragraphElement.getBBox().width;
for (let i = 0, textElement;
textElement = paragraphElement.childNodes[i] as SVGTSpanElement;
i++) {
textElement = paragraphElement.childNodes[i] as SVGTSpanElement;
i++) {
textElement.setAttribute('text-anchor', 'end');
textElement.setAttribute(
'x', (maxWidth + Bubble.BORDER_WIDTH).toString());
'x', (maxWidth + Bubble.BORDER_WIDTH).toString());
}
}
return bubble;
+19 -19
View File
@@ -18,22 +18,22 @@ import './bubble';
import './constants';
/* eslint-disable-next-line no-unused-vars */
import { BlockDragSurfaceSvg } from './block_drag_surface.js';
import { ComponentManager } from './component_manager.js';
import {BlockDragSurfaceSvg} from './block_drag_surface.js';
import {ComponentManager} from './component_manager.js';
/* eslint-disable-next-line no-unused-vars */
import { CommentMove } from './events/events_comment_move.js';
import {CommentMove} from './events/events_comment_move.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { IBubble } from './interfaces/i_bubble.js';
import {IBubble} from './interfaces/i_bubble.js';
/* eslint-disable-next-line no-unused-vars */
import { IDeleteArea } from './interfaces/i_delete_area.js';
import {IDeleteArea} from './interfaces/i_delete_area.js';
/* eslint-disable-next-line no-unused-vars */
import { IDragTarget } from './interfaces/i_drag_target.js';
import { Coordinate } from './utils/coordinate.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
import {Coordinate} from './utils/coordinate.js';
import * as svgMath from './utils/svg_math.js';
import { WorkspaceCommentSvg } from './workspace_comment_svg.js';
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -44,7 +44,7 @@ import { WorkspaceSvg } from './workspace_svg.js';
*/
export class BubbleDragger {
/** Which drag target the mouse pointer is over, if any. */
private dragTarget_: IDragTarget | null = null;
private dragTarget_: IDragTarget|null = null;
/** Whether the bubble would be deleted if dropped immediately. */
private wouldDeleteBubble_ = false;
@@ -69,9 +69,9 @@ export class BubbleDragger {
// AnyDuringMigration because: Type 'BlockDragSurfaceSvg | null' is not
// assignable to type 'BlockDragSurfaceSvg'.
this.dragSurface_ =
(svgMath.is3dSupported() && !!workspace.getBlockDragSurface() ?
workspace.getBlockDragSurface() :
null) as AnyDuringMigration;
(svgMath.is3dSupported() && !!workspace.getBlockDragSurface() ?
workspace.getBlockDragSurface() :
null) as AnyDuringMigration;
}
/**
@@ -142,11 +142,11 @@ export class BubbleDragger {
* @param dragTarget The drag target that the bubblee is currently over.
* @return Whether dropping the bubble immediately would delete the block.
*/
private shouldDelete_(dragTarget: IDragTarget | null): boolean {
private shouldDelete_(dragTarget: IDragTarget|null): boolean {
if (dragTarget) {
const componentManager = this.workspace.getComponentManager();
const isDeleteArea = componentManager.hasCapability(
dragTarget.id, ComponentManager.Capability.DELETE_AREA);
dragTarget.id, ComponentManager.Capability.DELETE_AREA);
if (isDeleteArea) {
return (dragTarget as IDeleteArea).wouldDelete(this.bubble, false);
}
@@ -173,7 +173,7 @@ export class BubbleDragger {
this.dragBubble(e, currentDragDeltaXY);
const preventMove =
this.dragTarget_ && this.dragTarget_.shouldPreventMove(this.bubble);
this.dragTarget_ && this.dragTarget_.shouldPreventMove(this.bubble);
let newLoc;
if (preventMove) {
newLoc = this.startXY_;
@@ -211,7 +211,7 @@ export class BubbleDragger {
private fireMoveEvent_() {
if (this.bubble instanceof WorkspaceCommentSvg) {
const event = new (eventUtils.get(eventUtils.COMMENT_MOVE))!
(this.bubble) as CommentMove;
(this.bubble) as CommentMove;
event.setOldCoordinate(this.startXY_);
event.recordNew();
eventUtils.fire(event);
@@ -230,8 +230,8 @@ export class BubbleDragger {
*/
private pixelsToWorkspaceUnits_(pixelCoord: Coordinate): Coordinate {
const result = new Coordinate(
pixelCoord.x / this.workspace.scale,
pixelCoord.y / this.workspace.scale);
pixelCoord.x / this.workspace.scale,
pixelCoord.y / this.workspace.scale);
if (this.workspace.isMutator) {
// If we're in a mutator, its scale is always 1, purely because of some
// oddities in our rendering optimizations. The actual scale is the same
+26 -26
View File
@@ -33,24 +33,24 @@
* @namespace Blockly.bumpObjects
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { Abstract } from './events/events_abstract.js';
import { BlockCreate } from './events/events_block_create.js';
import { BlockMove } from './events/events_block_move.js';
import { CommentCreate } from './events/events_comment_create.js';
import { CommentMove } from './events/events_comment_move.js';
import {Abstract} from './events/events_abstract.js';
import {BlockCreate} from './events/events_block_create.js';
import {BlockMove} from './events/events_block_move.js';
import {CommentCreate} from './events/events_comment_create.js';
import {CommentMove} from './events/events_comment_move.js';
/* eslint-disable-next-line no-unused-vars */
import { ViewportChange } from './events/events_viewport.js';
import {ViewportChange} from './events/events_viewport.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { IBoundedElement } from './interfaces/i_bounded_element.js';
import { ContainerRegion, MetricsManager } from './metrics_manager.js';
import {IBoundedElement} from './interfaces/i_bounded_element.js';
import {ContainerRegion, MetricsManager} from './metrics_manager.js';
import * as mathUtils from './utils/math.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceCommentSvg } from './workspace_comment_svg.js';
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -63,8 +63,8 @@ import { WorkspaceSvg } from './workspace_svg.js';
* @alias Blockly.bumpObjects.bumpIntoBounds
*/
function bumpObjectIntoBounds(
workspace: WorkspaceSvg, scrollMetrics: ContainerRegion,
object: IBoundedElement): boolean {
workspace: WorkspaceSvg, scrollMetrics: ContainerRegion,
object: IBoundedElement): boolean {
// Compute new top/left position for object.
const objectMetrics = object.getBoundingRectangle();
const height = objectMetrics.bottom - objectMetrics.top;
@@ -76,7 +76,7 @@ function bumpObjectIntoBounds(
// If the object is taller than the workspace we want to
// top-align the block
const newYPosition =
mathUtils.clamp(topClamp, objectMetrics.top, bottomClamp);
mathUtils.clamp(topClamp, objectMetrics.top, bottomClamp);
const deltaY = newYPosition - objectMetrics.top;
// Note: Even in RTL mode the "anchor" of the object is the
@@ -96,7 +96,7 @@ function bumpObjectIntoBounds(
rightClamp = Math.max(leftClamp, rightClamp);
}
const newXPosition =
mathUtils.clamp(leftClamp, objectMetrics.left, rightClamp);
mathUtils.clamp(leftClamp, objectMetrics.left, rightClamp);
const deltaX = newXPosition - objectMetrics.left;
if (deltaX || deltaY) {
@@ -114,7 +114,7 @@ export const bumpIntoBounds = bumpObjectIntoBounds;
* @alias Blockly.bumpObjects.bumpIntoBoundsHandler
*/
export function bumpIntoBoundsHandler(workspace: WorkspaceSvg):
(p1: Abstract) => AnyDuringMigration {
(p1: Abstract) => AnyDuringMigration {
return (e) => {
const metricsManager = workspace.getMetricsManager();
if (!metricsManager.hasFixedEdges() || workspace.isDragging()) {
@@ -126,7 +126,7 @@ export function bumpIntoBoundsHandler(workspace: WorkspaceSvg):
// Triggered by move/create event
const object =
extractObjectFromEvent(workspace, e as eventUtils.BumpEvent);
extractObjectFromEvent(workspace, e as eventUtils.BumpEvent);
if (!object) {
return;
}
@@ -135,12 +135,12 @@ export function bumpIntoBoundsHandler(workspace: WorkspaceSvg):
eventUtils.setGroup(e.group);
const wasBumped = bumpObjectIntoBounds(
workspace, scrollMetricsInWsCoords, (object as IBoundedElement));
workspace, scrollMetricsInWsCoords, (object as IBoundedElement));
if (wasBumped && !e.group) {
console.warn(
'Moved object in bounds but there was no' +
' event group. This may break undo.');
'Moved object in bounds but there was no' +
' event group. This may break undo.');
}
if (oldGroup !== null) {
eventUtils.setGroup(oldGroup);
@@ -148,7 +148,7 @@ export function bumpIntoBoundsHandler(workspace: WorkspaceSvg):
} else if (e.type === eventUtils.VIEWPORT_CHANGE) {
const viewportEvent = (e as ViewportChange);
if (viewportEvent.scale && viewportEvent.oldScale &&
viewportEvent.scale > viewportEvent.oldScale) {
viewportEvent.scale > viewportEvent.oldScale) {
bumpTopObjectsIntoBounds(workspace);
}
}
@@ -164,8 +164,8 @@ export function bumpIntoBoundsHandler(workspace: WorkspaceSvg):
* object.
*/
function extractObjectFromEvent(
workspace: WorkspaceSvg, e: eventUtils.BumpEvent): BlockSvg | null |
WorkspaceCommentSvg {
workspace: WorkspaceSvg, e: eventUtils.BumpEvent): BlockSvg|null|
WorkspaceCommentSvg {
let object = null;
switch (e.type) {
case eventUtils.BLOCK_CREATE:
@@ -178,9 +178,9 @@ function extractObjectFromEvent(
case eventUtils.COMMENT_CREATE:
case eventUtils.COMMENT_MOVE:
object = workspace.getCommentById(
(e as CommentCreate | CommentMove).commentId) as
WorkspaceCommentSvg |
null;
(e as CommentCreate | CommentMove).commentId) as
WorkspaceCommentSvg |
null;
break;
}
return object;
+5 -5
View File
@@ -11,11 +11,11 @@
* Blockly's internal clipboard for managing copy-paste.
* @namespace Blockly.clipboard
*/
import { CopyData, ICopyable } from './interfaces/i_copyable.js';
import {CopyData, ICopyable} from './interfaces/i_copyable.js';
/** Metadata about the object that is currently on the clipboard. */
let copyData: CopyData | null = null;
let copyData: CopyData|null = null;
/**
* Copy a block or workspace comment onto the local clipboard.
@@ -31,7 +31,7 @@ export function copy(toCopy: ICopyable) {
* @return The pasted thing if the paste was successful, null otherwise.
* @alias Blockly.clipboard.paste
*/
export function paste(): ICopyable | null {
export function paste(): ICopyable|null {
if (!copyData) {
return null;
}
@@ -42,7 +42,7 @@ export function paste(): ICopyable | null {
workspace = workspace.targetWorkspace;
}
if (copyData.typeCounts &&
workspace.isCapacityAvailable(copyData.typeCounts)) {
workspace.isCapacityAvailable(copyData.typeCounts)) {
return workspace.paste(copyData.saveInfo);
}
return null;
@@ -55,7 +55,7 @@ export function paste(): ICopyable | null {
* duplication failed.
* @alias Blockly.clipboard.duplicate
*/
export function duplicate(toDuplicate: ICopyable): ICopyable | null {
export function duplicate(toDuplicate: ICopyable): ICopyable|null {
const oldCopyData = copyData;
copy(toDuplicate);
const pastedThing = toDuplicate.toCopyData().source.paste(copyData!.saveInfo);
+61 -61
View File
@@ -24,20 +24,20 @@ import './events/events_bubble_open';
// Unused import preserved for side-effects. Remove if unneeded.
import './warning';
import { CommentModel } from './block.js';
import {CommentModel} from './block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import { Bubble } from './bubble.js';
import {Bubble} from './bubble.js';
import * as Css from './css.js';
import * as eventUtils from './events/utils.js';
import { Icon } from './icon.js';
import {Icon} from './icon.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
/* eslint-disable-next-line no-unused-vars */
import { Size } from './utils/size.js';
import { Svg } from './utils/svg.js';
import {Size} from './utils/size.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
@@ -52,30 +52,30 @@ export class Comment extends Icon {
* The model's text value at the start of an edit.
* Used to tell if an event should be fired at the end of an edit.
*/
private cachedText_: string | null = '';
private cachedText_: string|null = '';
/** Mouse up event data. */
private onMouseUpWrapper_: browserEvents.Data | null = null;
private onMouseUpWrapper_: browserEvents.Data|null = null;
/** Wheel event data. */
private onWheelWrapper_: browserEvents.Data | null = null;
private onWheelWrapper_: browserEvents.Data|null = null;
/** Change event data. */
private onChangeWrapper_: browserEvents.Data | null = null;
private onChangeWrapper_: browserEvents.Data|null = null;
/** Input event data. */
private onInputWrapper_: browserEvents.Data | null = null;
private onInputWrapper_: browserEvents.Data|null = null;
/**
* The SVG element that contains the text edit area, or null if not created.
*/
private foreignObject_: SVGForeignObjectElement | null = null;
private foreignObject_: SVGForeignObjectElement|null = null;
/** The editable text area, or null if not created. */
private textarea_: HTMLTextAreaElement | null = null;
private textarea_: HTMLTextAreaElement|null = null;
/** The top-level node of the comment text, or null if not created. */
private paragraphElement_: SVGTextElement | null = null;
private paragraphElement_: SVGTextElement|null = null;
override bubble_: AnyDuringMigration;
/** @param block The block associated with this comment. */
@@ -98,28 +98,28 @@ export class Comment extends Icon {
protected override drawIcon_(group: Element) {
// Circle.
dom.createSvgElement(
Svg.CIRCLE,
{ 'class': 'blocklyIconShape', 'r': '8', 'cx': '8', 'cy': '8' }, group);
Svg.CIRCLE,
{'class': 'blocklyIconShape', 'r': '8', 'cx': '8', 'cy': '8'}, group);
// Can't use a real '?' text character since different browsers and
// operating systems render it differently. Body of question mark.
dom.createSvgElement(
Svg.PATH, {
'class': 'blocklyIconSymbol',
'd': 'm6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.405' +
'0.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25' +
'-1.201,0.998 -1.201,1.528 -1.204,2.19z',
},
group);
Svg.PATH, {
'class': 'blocklyIconSymbol',
'd': 'm6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.405' +
'0.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25' +
'-1.201,0.998 -1.201,1.528 -1.204,2.19z',
},
group);
// Dot of question mark.
dom.createSvgElement(
Svg.RECT, {
'class': 'blocklyIconSymbol',
'x': '6.8',
'y': '10.78',
'height': '2',
'width': '2',
},
group);
Svg.RECT, {
'class': 'blocklyIconSymbol',
'x': '6.8',
'y': '10.78',
'height': '2',
'width': '2',
},
group);
}
/**
@@ -140,15 +140,15 @@ export class Comment extends Icon {
*/
this.foreignObject_ = dom.createSvgElement(
Svg.FOREIGNOBJECT,
{ 'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH });
Svg.FOREIGNOBJECT,
{'x': Bubble.BORDER_WIDTH, 'y': Bubble.BORDER_WIDTH});
const body = document.createElementNS(dom.HTML_NS, 'body');
body.setAttribute('xmlns', dom.HTML_NS);
body.className = 'blocklyMinimalBody';
this.textarea_ = document.createElementNS(dom.HTML_NS, 'textarea') as
HTMLTextAreaElement;
HTMLTextAreaElement;
const textarea = this.textarea_;
textarea.className = 'blocklyCommentTextarea';
textarea.setAttribute('dir', this.block_.RTL ? 'RTL' : 'LTR');
@@ -164,28 +164,28 @@ export class Comment extends Icon {
// However doing so in Firefox swallows the cursor for unknown reasons.
// So this is hooked to mouseup instead. No big deal.
this.onMouseUpWrapper_ = browserEvents.conditionalBind(
textarea, 'mouseup', this, this.startEdit_, true, true);
textarea, 'mouseup', this, this.startEdit_, true, true);
// Don't zoom with mousewheel.
this.onWheelWrapper_ = browserEvents.conditionalBind(
textarea, 'wheel', this, function (e: AnyDuringMigration) {
e.stopPropagation();
});
textarea, 'wheel', this, function(e: AnyDuringMigration) {
e.stopPropagation();
});
this.onChangeWrapper_ = browserEvents.conditionalBind(
textarea, 'change', this,
/** @param _e Unused event parameter. */
function (this: Comment, _e: Event) {
if (this.cachedText_ !== this.model_.text) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this.block_, 'comment', null, this.cachedText_,
this.model_.text));
}
});
textarea, 'change', this,
/** @param _e Unused event parameter. */
function(this: Comment, _e: Event) {
if (this.cachedText_ !== this.model_.text) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this.block_, 'comment', null, this.cachedText_,
this.model_.text));
}
});
this.onInputWrapper_ = browserEvents.conditionalBind(
textarea, 'input', this,
/** @param _e Unused event parameter. */
function (this: Comment, _e: Event) {
this.model_.text = textarea.value;
});
textarea, 'input', this,
/** @param _e Unused event parameter. */
function(this: Comment, _e: Event) {
this.model_.text = textarea.value;
});
setTimeout(textarea.focus.bind(textarea), 0);
@@ -228,11 +228,11 @@ export class Comment extends Icon {
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.foreignObject_!.setAttribute(
'width', widthMinusBorder as AnyDuringMigration);
'width', widthMinusBorder as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.foreignObject_!.setAttribute(
'height', heightMinusBorder as AnyDuringMigration);
'height', heightMinusBorder as AnyDuringMigration);
this.textarea_!.style.width = widthMinusBorder - 4 + 'px';
this.textarea_!.style.height = heightMinusBorder - 4 + 'px';
}
@@ -246,7 +246,7 @@ export class Comment extends Icon {
return;
}
eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))!
(this.block_, visible, 'comment'));
(this.block_, visible, 'comment'));
this.model_.pinned = visible;
if (visible) {
this.createBubble_();
@@ -270,9 +270,9 @@ export class Comment extends Icon {
/** Show an editable bubble. */
private createEditableBubble_() {
this.bubble_ = new Bubble(
(this.block_.workspace), this.createEditor_(),
this.block_.pathObject.svgPath, (this.iconXY_ as Coordinate),
this.model_.size.width, this.model_.size.height);
(this.block_.workspace), this.createEditor_(),
this.block_.pathObject.svgPath, (this.iconXY_ as Coordinate),
this.model_.size.width, this.model_.size.height);
// Expose this comment's block's ID on its top-level SVG group.
this.bubble_.setSvgId(this.block_.id);
this.bubble_.registerResizeEvent(this.onBubbleResize_.bind(this));
@@ -288,9 +288,9 @@ export class Comment extends Icon {
// AnyDuringMigration because: Argument of type 'string | null' is not
// assignable to parameter of type 'string'.
this.paragraphElement_ =
Bubble.textToDom(this.block_.getCommentText() as AnyDuringMigration);
Bubble.textToDom(this.block_.getCommentText() as AnyDuringMigration);
this.bubble_ = Bubble.createNonEditableBubble(
this.paragraphElement_, (this.block_), this.iconXY_ as Coordinate);
this.paragraphElement_, (this.block_), this.iconXY_ as Coordinate);
this.applyColour();
}
+19 -19
View File
@@ -37,16 +37,16 @@
/* eslint-disable-next-line no-unused-vars */
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import { BlockDefinition, Blocks } from './blocks.js';
import {Block} from './block.js';
import {BlockDefinition, Blocks} from './blocks.js';
/* eslint-disable-next-line no-unused-vars */
import { Connection } from './connection.js';
import {Connection} from './connection.js';
/* eslint-disable-next-line no-unused-vars */
import { ICopyable } from './interfaces/i_copyable.js';
import {ICopyable} from './interfaces/i_copyable.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from './workspace.js';
import {Workspace} from './workspace.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -78,14 +78,14 @@ export function setMainWorkspace(workspace: Workspace) {
/**
* Currently selected block.
*/
let selected: ICopyable | null = null;
let selected: ICopyable|null = null;
/**
* Returns the currently selected block.
* @return The currently selected block.
* @alias Blockly.common.getSelected
*/
export function getSelected(): ICopyable | null {
export function getSelected(): ICopyable|null {
return selected;
}
@@ -96,14 +96,14 @@ export function getSelected(): ICopyable | null {
* @param newSelection The newly selected block.
* @alias Blockly.common.setSelected
*/
export function setSelected(newSelection: ICopyable | null) {
export function setSelected(newSelection: ICopyable|null) {
selected = newSelection;
}
/**
* Container element in which to render the WidgetDiv, DropDownDiv and Tooltip.
*/
let parentContainer: Element | null;
let parentContainer: Element|null;
/**
* Get the container element in which to render the WidgetDiv, DropDownDiv and\
@@ -111,7 +111,7 @@ let parentContainer: Element | null;
* @return The parent container.
* @alias Blockly.common.getParentContainer
*/
export function getParentContainer(): Element | null {
export function getParentContainer(): Element|null {
return parentContainer;
}
@@ -178,7 +178,7 @@ export const draggingConnections: Connection[] = [];
* @alias Blockly.common.getBlockTypeCounts
*/
export function getBlockTypeCounts(
block: Block, opt_stripFollowing?: boolean): AnyDuringMigration {
block: Block, opt_stripFollowing?: boolean): AnyDuringMigration {
const typeCountsMap = Object.create(null);
const descendants = block.getDescendants(true);
if (opt_stripFollowing) {
@@ -206,7 +206,7 @@ export function getBlockTypeCounts(
* of jsonDef.
*/
function jsonInitFactory(jsonDef: AnyDuringMigration): () => void {
return function (this: Block) {
return function(this: Block) {
this.jsonInit(jsonDef);
};
}
@@ -230,8 +230,8 @@ export function defineBlocksWithJsonArray(jsonArray: AnyDuringMigration[]) {
* @alias Blockly.common.defineBlocksWithJsonArray
*/
export function createBlockDefinitionsFromJsonArray(
jsonArray: AnyDuringMigration[]): { [key: string]: BlockDefinition } {
const blocks: { [key: string]: BlockDefinition } = {};
jsonArray: AnyDuringMigration[]): {[key: string]: BlockDefinition} {
const blocks: {[key: string]: BlockDefinition} = {};
for (let i = 0; i < jsonArray.length; i++) {
const elem = jsonArray[i];
if (!elem) {
@@ -241,11 +241,11 @@ export function createBlockDefinitionsFromJsonArray(
const type = elem['type'];
if (!type) {
console.warn(
`Block definition #${i} in JSON array is missing a type attribute. ` +
'Skipping.');
`Block definition #${i} in JSON array is missing a type attribute. ` +
'Skipping.');
continue;
}
blocks[type] = { init: jsonInitFactory(elem) };
blocks[type] = {init: jsonInitFactory(elem)};
}
return blocks;
}
@@ -257,7 +257,7 @@ export function createBlockDefinitionsFromJsonArray(
* type names to block definitions.
* @alias Blockly.common.defineBlocks
*/
export function defineBlocks(blocks: { [key: string]: BlockDefinition }) {
export function defineBlocks(blocks: {[key: string]: BlockDefinition}) {
// Iterate over own enumerable properties.
for (const type of Object.keys(blocks)) {
const definition = blocks[type];
+30 -30
View File
@@ -14,23 +14,23 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { IAutoHideable } from './interfaces/i_autohideable.js';
import {IAutoHideable} from './interfaces/i_autohideable.js';
/* eslint-disable-next-line no-unused-vars */
import { IComponent } from './interfaces/i_component.js';
import {IComponent} from './interfaces/i_component.js';
/* eslint-disable-next-line no-unused-vars */
import { IDeleteArea } from './interfaces/i_delete_area.js';
import {IDeleteArea} from './interfaces/i_delete_area.js';
/* eslint-disable-next-line no-unused-vars */
import { IDragTarget } from './interfaces/i_drag_target.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
/* eslint-disable-next-line no-unused-vars */
import { IPositionable } from './interfaces/i_positionable.js';
import {IPositionable} from './interfaces/i_positionable.js';
import * as arrayUtils from './utils/array.js';
class Capability<T> {
static POSITIONABLE = new Capability < IPositionable > ('positionable');
static DRAG_TARGET = new Capability < IDragTarget > ('drag_target');
static DELETE_AREA = new Capability < IDeleteArea > ('delete_area');
static AUTOHIDEABLE = new Capability < IAutoHideable > ('autohideable');
static POSITIONABLE = new Capability<IPositionable>('positionable');
static DRAG_TARGET = new Capability<IDragTarget>('drag_target');
static DELETE_AREA = new Capability<IDeleteArea>('delete_area');
static AUTOHIDEABLE = new Capability<IAutoHideable>('autohideable');
private readonly name_: string;
/** @param name The name of the component capability. */
constructor(name: string) {
@@ -54,8 +54,8 @@ export class ComponentManager {
static Capability = Capability;
// static Capability: AnyDuringMigration;
private readonly componentData_: { [key: string]: ComponentDatum };
private readonly capabilityToComponentIds_: { [key: string]: string[] };
private readonly componentData_: {[key: string]: ComponentDatum};
private readonly capabilityToComponentIds_: {[key: string]: string[]};
/** Creates a new ComponentManager instance. */
constructor() {
@@ -79,8 +79,8 @@ export class ComponentManager {
const id = componentInfo.component.id;
if (!opt_allowOverrides && this.componentData_[id]) {
throw Error(
'Plugin "' + id + '" with capabilities "' +
this.componentData_[id].capabilities + '" already added.');
'Plugin "' + id + '" with capabilities "' +
this.componentData_[id].capabilities + '" already added.');
}
this.componentData_[id] = componentInfo;
const stringCapabilities = [];
@@ -117,15 +117,15 @@ export class ComponentManager {
* @param id The ID of the component to add the capability to.
* @param capability The capability to add.
*/
addCapability<T>(id: string, capability: string | Capability<T>) {
addCapability<T>(id: string, capability: string|Capability<T>) {
if (!this.getComponent(id)) {
throw Error(
'Cannot add capability, "' + capability + '". Plugin "' + id +
'" has not been added to the ComponentManager');
'Cannot add capability, "' + capability + '". Plugin "' + id +
'" has not been added to the ComponentManager');
}
if (this.hasCapability(id, capability)) {
console.warn(
'Plugin "' + id + 'already has capability "' + capability + '"');
'Plugin "' + id + 'already has capability "' + capability + '"');
return;
}
capability = String(capability).toLowerCase();
@@ -138,16 +138,16 @@ export class ComponentManager {
* @param id The ID of the component to remove the capability from.
* @param capability The capability to remove.
*/
removeCapability<T>(id: string, capability: string | Capability<T>) {
removeCapability<T>(id: string, capability: string|Capability<T>) {
if (!this.getComponent(id)) {
throw Error(
'Cannot remove capability, "' + capability + '". Plugin "' + id +
'" has not been added to the ComponentManager');
'Cannot remove capability, "' + capability + '". Plugin "' + id +
'" has not been added to the ComponentManager');
}
if (!this.hasCapability(id, capability)) {
console.warn(
'Plugin "' + id + 'doesn\'t have capability "' + capability +
'" to remove');
'Plugin "' + id + 'doesn\'t have capability "' + capability +
'" to remove');
return;
}
capability = String(capability).toLowerCase();
@@ -161,7 +161,7 @@ export class ComponentManager {
* @param capability The capability to check for.
* @return Whether the component has the capability.
*/
hasCapability<T>(id: string, capability: string | Capability<T>): boolean {
hasCapability<T>(id: string, capability: string|Capability<T>): boolean {
capability = String(capability).toLowerCase();
return this.componentData_[id].capabilities.indexOf(capability) !== -1;
}
@@ -171,7 +171,7 @@ export class ComponentManager {
* @param id The ID of the component to get.
* @return The component with the given name or undefined if not found.
*/
getComponent(id: string): IComponent | undefined {
getComponent(id: string): IComponent|undefined {
return this.componentData_[id] && this.componentData_[id].component;
}
@@ -181,7 +181,7 @@ export class ComponentManager {
* @param sorted Whether to return list ordered by weights.
* @return The components that match the specified capability.
*/
getComponents<T>(capability: string | Capability<T>, sorted: boolean): T[] {
getComponents<T>(capability: string|Capability<T>, sorted: boolean): T[] {
capability = String(capability).toLowerCase();
const componentIds = this.capabilityToComponentIds_[capability];
if (!componentIds) {
@@ -191,18 +191,18 @@ export class ComponentManager {
if (sorted) {
const componentDataList: AnyDuringMigration[] = [];
const componentData = this.componentData_;
componentIds.forEach(function (id) {
componentIds.forEach(function(id) {
componentDataList.push(componentData[id]);
});
componentDataList.sort(function (a, b) {
componentDataList.sort(function(a, b) {
return a.weight - b.weight;
});
componentDataList.forEach(function (ComponentDatum) {
componentDataList.forEach(function(ComponentDatum) {
components.push(ComponentDatum.component);
});
} else {
const componentData = this.componentData_;
componentIds.forEach(function (id) {
componentIds.forEach(function(id) {
components.push(componentData[id].component);
});
}
@@ -211,6 +211,6 @@ export class ComponentManager {
}
export interface ComponentDatum {
component: IComponent;
capabilities: Array<string | Capability<IComponent>>;
capabilities: Array<string|Capability<IComponent>>;
weight: number;
}
+46 -45
View File
@@ -16,17 +16,17 @@
import './constants';
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import { ConnectionType } from './connection_type.js';
import {Block} from './block.js';
import {ConnectionType} from './connection_type.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockMove } from './events/events_block_move.js';
import {BlockMove} from './events/events_block_move.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { Input } from './input.js';
import {Input} from './input.js';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocationWithBlock } from './interfaces/i_ast_node_location_with_block.js';
import {IASTNodeLocationWithBlock} from './interfaces/i_ast_node_location_with_block.js';
/* eslint-disable-next-line no-unused-vars */
import { IConnectionChecker } from './interfaces/i_connection_checker.js';
import {IConnectionChecker} from './interfaces/i_connection_checker.js';
import * as blocks from './serialization/blocks.js';
import * as Xml from './xml.js';
@@ -48,7 +48,7 @@ export class Connection implements IASTNodeLocationWithBlock {
static REASON_PREVIOUS_AND_OUTPUT = 8;
/** Connection this connection connects to. Null if not connected. */
targetConnection: Connection | null = null;
targetConnection: Connection|null = null;
/** Has this connection been disposed of? */
disposed = false;
@@ -68,7 +68,7 @@ export class Connection implements IASTNodeLocationWithBlock {
/** Vertical location of this connection. */
y = 0;
private shadowState_: blocks.State | null = null;
private shadowState_: blocks.State|null = null;
/**
* @param source The block establishing this connection.
@@ -110,7 +110,7 @@ export class Connection implements IASTNodeLocationWithBlock {
let event;
if (eventUtils.isEnabled()) {
event =
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(childBlock) as BlockMove;
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(childBlock) as BlockMove;
}
connectReciprocally(parentConnection, childConnection);
childBlock.setParent(parentBlock);
@@ -122,10 +122,10 @@ export class Connection implements IASTNodeLocationWithBlock {
// Deal with the orphan if it exists.
if (orphan) {
const orphanConnection = parentConnection.type === INPUT ?
orphan.outputConnection :
orphan.previousConnection;
orphan.outputConnection :
orphan.previousConnection;
const connection = Connection.getConnectionForOrphanedConnection(
childBlock, (orphanConnection));
childBlock, (orphanConnection));
if (connection) {
orphanConnection.connect(connection);
} else {
@@ -166,7 +166,7 @@ export class Connection implements IASTNodeLocationWithBlock {
*/
isSuperior(): boolean {
return this.type === ConnectionType.INPUT_VALUE ||
this.type === ConnectionType.NEXT_STATEMENT;
this.type === ConnectionType.NEXT_STATEMENT;
}
/**
@@ -274,7 +274,7 @@ export class Connection implements IASTNodeLocationWithBlock {
let event;
if (eventUtils.isEnabled()) {
event =
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(childBlock) as BlockMove;
new (eventUtils.get(eventUtils.BLOCK_MOVE))!(childBlock) as BlockMove;
}
const otherConnection = this.targetConnection;
if (otherConnection) {
@@ -300,7 +300,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* Returns the block that this connection connects to.
* @return The connected block or null if none is connected.
*/
targetBlock(): Block | null {
targetBlock(): Block|null {
if (this.isConnected()) {
return this.targetConnection?.getSourceBlock() ?? null;
}
@@ -313,9 +313,9 @@ export class Connection implements IASTNodeLocationWithBlock {
protected 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))) {
(!this.targetConnection ||
!this.getConnectionChecker().canConnect(
this, this.targetConnection, false))) {
const child = this.isSuperior() ? this.targetBlock() : this.source;
child!.unplug();
}
@@ -327,7 +327,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* types are compatible.
* @return The connection being modified (to allow chaining).
*/
setCheck(check: string | string[] | null): Connection {
setCheck(check: string|string[]|null): Connection {
if (check) {
// Ensure that check is in an array.
if (!Array.isArray(check)) {
@@ -348,7 +348,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* @return List of compatible value types.
* Null if all types are compatible.
*/
getCheck(): AnyDuringMigration[] | null {
getCheck(): AnyDuringMigration[]|null {
return this.check_;
}
@@ -356,8 +356,8 @@ export class Connection implements IASTNodeLocationWithBlock {
* Changes the connection's shadow block.
* @param shadowDom DOM representation of a block or null.
*/
setShadowDom(shadowDom: Element | null) {
this.setShadowStateInternal_({ shadowDom });
setShadowDom(shadowDom: Element|null) {
this.setShadowStateInternal_({shadowDom});
}
/**
@@ -368,18 +368,18 @@ export class Connection implements IASTNodeLocationWithBlock {
* just returned.
* @return Shadow DOM representation of a block or null.
*/
getShadowDom(returnCurrent?: boolean): Element | null {
getShadowDom(returnCurrent?: boolean): Element|null {
return returnCurrent && this.targetBlock()!.isShadow() ?
Xml.blockToDom((this.targetBlock() as Block)) as Element :
this.shadowDom_;
Xml.blockToDom((this.targetBlock() as Block)) as Element :
this.shadowDom_;
}
/**
* Changes the connection's shadow block.
* @param shadowState An state represetation of the block or null.
*/
setShadowState(shadowState: blocks.State | null) {
this.setShadowStateInternal_({ shadowState });
setShadowState(shadowState: blocks.State|null) {
this.setShadowStateInternal_({shadowState});
}
/**
@@ -391,7 +391,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* returned.
* @return Serialized object representation of the block, or null.
*/
getShadowState(returnCurrent?: boolean): blocks.State | null {
getShadowState(returnCurrent?: boolean): blocks.State|null {
if (returnCurrent && this.targetBlock() && this.targetBlock()!.isShadow()) {
return blocks.save(this.targetBlock() as Block);
}
@@ -418,7 +418,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* @return The input that the connection belongs to or null if no parent
* exists.
*/
getParentInput(): Input | null {
getParentInput(): Input|null {
let parentInput = null;
const inputs = this.source.inputList;
for (let i = 0; i < inputs.length; i++) {
@@ -470,7 +470,8 @@ export class Connection implements IASTNodeLocationWithBlock {
* temporarily sets those properties to null so no shadow respawns.
* @return The state of both the shadowDom_ and shadowState_ properties.
*/
private stashShadowState_(): { shadowDom: Element | null, shadowState: blocks.State | null } {
private stashShadowState_():
{shadowDom: Element|null, shadowState: blocks.State|null} {
const shadowDom = this.getShadowDom(true);
const shadowState = this.getShadowState(true);
// Set to null so it doesn't respawn.
@@ -478,7 +479,7 @@ export class Connection implements IASTNodeLocationWithBlock {
// 'Element'.
this.shadowDom_ = null as AnyDuringMigration;
this.shadowState_ = null;
return { shadowDom, shadowState };
return {shadowDom, shadowState};
}
/**
@@ -486,9 +487,9 @@ export class Connection implements IASTNodeLocationWithBlock {
* @param param0 The state to reapply to the shadowDom_ and shadowState_
* properties.
*/
private applyShadowState_({ shadowDom, shadowState }: {
shadowDom: Element | null,
shadowState: blocks.State | null
private applyShadowState_({shadowDom, shadowState}: {
shadowDom: Element|null,
shadowState: blocks.State|null
}) {
// AnyDuringMigration because: Type 'Element | null' is not assignable to
// type 'Element'.
@@ -500,9 +501,9 @@ export class Connection implements IASTNodeLocationWithBlock {
* Sets the state of the shadow of this connection.
* @param param0 The state to set the shadow of this connection to.
*/
private setShadowStateInternal_({ shadowDom = null, shadowState = null }: {
shadowDom?: Element | null,
shadowState?: blocks.State | null
private setShadowStateInternal_({shadowDom = null, shadowState = null}: {
shadowDom?: Element|null,
shadowState?: blocks.State|null
} = {}) {
// One or both of these should always be null.
// If neither is null, the shadowState will get priority.
@@ -540,7 +541,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* @return The shadow block that was created, or null if both the shadowState_
* and shadowDom_ are null.
*/
private createShadowBlock_(attemptToConnect: boolean): Block | null {
private createShadowBlock_(attemptToConnect: boolean): Block|null {
const parentBlock = this.getSourceBlock();
const shadowState = this.getShadowState();
const shadowDom = this.getShadowDom();
@@ -577,7 +578,7 @@ export class Connection implements IASTNodeLocationWithBlock {
}
} else {
throw new Error(
'Cannot connect a shadow block to a previous/output connection');
'Cannot connect a shadow block to a previous/output connection');
}
}
return blockShadow;
@@ -590,7 +591,7 @@ export class Connection implements IASTNodeLocationWithBlock {
* properties, in their respective serialized forms.
* @param shadow The shadow to serialize, or null.
*/
private serializeShadow_(shadow: Block | null) {
private serializeShadow_(shadow: Block|null) {
if (!shadow) {
return;
}
@@ -607,10 +608,10 @@ export class Connection implements IASTNodeLocationWithBlock {
* @return The suitable connection point on the chain of blocks, or null.
*/
static getConnectionForOrphanedConnection(
startBlock: Block, orphanConnection: Connection): Connection | null {
startBlock: Block, orphanConnection: Connection): Connection|null {
if (orphanConnection.type === ConnectionType.OUTPUT_VALUE) {
return getConnectionForOrphanedOutput(
startBlock, orphanConnection.getSourceBlock());
startBlock, orphanConnection.getSourceBlock());
}
// Otherwise we're dealing with a stack.
const connection = startBlock.lastConnectionInStack(true);
@@ -643,8 +644,8 @@ function connectReciprocally(first: Connection, second: Connection) {
* @param orphanBlock The inferior block.
* @return The suitable connection point on 'block', or null.
*/
function getSingleConnection(block: Block, orphanBlock: Block): Connection |
null {
function getSingleConnection(block: Block, orphanBlock: Block): Connection|
null {
let foundConnection = null;
const output = orphanBlock.outputConnection;
const typeChecker = output.getConnectionChecker();
@@ -673,7 +674,7 @@ function getSingleConnection(block: Block, orphanBlock: Block): Connection |
* @return The suitable connection point on the chain of blocks, or null.
*/
function getConnectionForOrphanedOutput(
startBlock: Block, orphanBlock: Block): Connection | null {
startBlock: Block, orphanBlock: Block): Connection|null {
let newBlock = startBlock;
let connection;
while (connection = getSingleConnection((newBlock), orphanBlock)) {
+29 -29
View File
@@ -17,14 +17,14 @@
*/
import * as common from './common.js';
import { Connection } from './connection.js';
import { ConnectionType } from './connection_type.js';
import {Connection} from './connection.js';
import {ConnectionType} from './connection_type.js';
/* eslint-disable-next-line no-unused-vars */
import { IConnectionChecker } from './interfaces/i_connection_checker.js';
import {IConnectionChecker} from './interfaces/i_connection_checker.js';
import * as internalConstants from './internal_constants.js';
import * as registry from './registry.js';
/* eslint-disable-next-line no-unused-vars */
import { RenderedConnection } from './rendered_connection.js';
import {RenderedConnection} from './rendered_connection.js';
/**
@@ -43,10 +43,10 @@ export class ConnectionChecker implements IConnectionChecker {
* @return Whether the connection is legal.
*/
canConnect(
a: Connection | null, b: Connection | null, isDragging: boolean,
opt_distance?: number): boolean {
a: Connection|null, b: Connection|null, isDragging: boolean,
opt_distance?: number): boolean {
return this.canConnectWithReason(a, b, isDragging, opt_distance) ===
Connection.CAN_CONNECT;
Connection.CAN_CONNECT;
}
/**
@@ -61,8 +61,8 @@ export class ConnectionChecker implements IConnectionChecker {
* otherwise.
*/
canConnectWithReason(
a: Connection | null, b: Connection | null, isDragging: boolean,
opt_distance?: number): number {
a: Connection|null, b: Connection|null, isDragging: boolean,
opt_distance?: number): number {
const safety = this.doSafetyChecks(a, b);
if (safety !== Connection.CAN_CONNECT) {
return safety;
@@ -76,9 +76,9 @@ export class ConnectionChecker implements IConnectionChecker {
}
if (isDragging &&
!this.doDragChecks(
a as RenderedConnection, b as RenderedConnection,
opt_distance || 0)) {
!this.doDragChecks(
a as RenderedConnection, b as RenderedConnection,
opt_distance || 0)) {
return Connection.REASON_DRAG_CHECKS_FAILED;
}
@@ -92,8 +92,8 @@ export class ConnectionChecker implements IConnectionChecker {
* @param b The second of the two connections being checked.
* @return A developer-readable error string.
*/
getErrorMessage(errorCode: number, a: Connection | null, b: Connection | null):
string {
getErrorMessage(errorCode: number, a: Connection|null, b: Connection|null):
string {
switch (errorCode) {
case Connection.REASON_SELF_CONNECTION:
return 'Attempted to connect a block to itself.';
@@ -109,7 +109,7 @@ export class ConnectionChecker implements IConnectionChecker {
const connTwo = b!;
let msg = 'Connection checks failed. ';
msg += connOne + ' expected ' + connOne.getCheck() + ', found ' +
connTwo.getCheck();
connTwo.getCheck();
return msg;
}
case Connection.REASON_SHADOW_PARENT:
@@ -130,7 +130,7 @@ export class ConnectionChecker implements IConnectionChecker {
* @param b The second of the connections to check.
* @return An enum with the reason this connection is safe or unsafe.
*/
doSafetyChecks(a: Connection | null, b: Connection | null): number {
doSafetyChecks(a: Connection|null, b: Connection|null): number {
if (!a || !b) {
return Connection.REASON_TARGET_NULL;
}
@@ -152,22 +152,22 @@ export class ConnectionChecker implements IConnectionChecker {
if (superiorBlock === inferiorBlock) {
return Connection.REASON_SELF_CONNECTION;
} else if (
inferiorConnection.type !==
internalConstants.OPPOSITE_TYPE[superiorConnection.type]) {
inferiorConnection.type !==
internalConstants.OPPOSITE_TYPE[superiorConnection.type]) {
return Connection.REASON_WRONG_TYPE;
} else if (superiorBlock.workspace !== inferiorBlock.workspace) {
return Connection.REASON_DIFFERENT_WORKSPACES;
} else if (superiorBlock.isShadow() && !inferiorBlock.isShadow()) {
return Connection.REASON_SHADOW_PARENT;
} else if (
inferiorConnection.type === ConnectionType.OUTPUT_VALUE &&
inferiorBlock.previousConnection &&
inferiorBlock.previousConnection.isConnected()) {
inferiorConnection.type === ConnectionType.OUTPUT_VALUE &&
inferiorBlock.previousConnection &&
inferiorBlock.previousConnection.isConnected()) {
return Connection.REASON_PREVIOUS_AND_OUTPUT;
} else if (
inferiorConnection.type === ConnectionType.PREVIOUS_STATEMENT &&
inferiorBlock.outputConnection &&
inferiorBlock.outputConnection.isConnected()) {
inferiorConnection.type === ConnectionType.PREVIOUS_STATEMENT &&
inferiorBlock.outputConnection &&
inferiorBlock.outputConnection.isConnected()) {
return Connection.REASON_PREVIOUS_AND_OUTPUT;
}
return Connection.CAN_CONNECT;
@@ -207,7 +207,7 @@ export class ConnectionChecker implements IConnectionChecker {
* @return True if the connection is allowed during a drag.
*/
doDragChecks(a: RenderedConnection, b: RenderedConnection, distance: number):
boolean {
boolean {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is not
// assignable to parameter of type 'Connection'.
if (a.distanceFrom(b as AnyDuringMigration) > distance) {
@@ -228,7 +228,7 @@ export class ConnectionChecker implements IConnectionChecker {
// Don't offer to connect an already connected left (male) value plug to
// an available right (female) value plug.
if (b.isConnected() && !b.targetBlock()!.isInsertionMarker() ||
a.isConnected()) {
a.isConnected()) {
return false;
}
break;
@@ -238,7 +238,7 @@ export class ConnectionChecker implements IConnectionChecker {
// connected value pair is ok, we'll splice it in.
// However, don't offer to splice into an immovable block.
if (b.isConnected() && !b.targetBlock()!.isMovable() &&
!b.targetBlock()!.isShadow()) {
!b.targetBlock()!.isShadow()) {
return false;
}
break;
@@ -249,7 +249,7 @@ export class ConnectionChecker implements IConnectionChecker {
// is fine. Similarly, replacing a terminal statement with another
// terminal statement is allowed.
if (b.isConnected() && !a.getSourceBlock().nextConnection &&
!b.targetBlock()!.isShadow() && b.targetBlock()!.nextConnection) {
!b.targetBlock()!.isShadow() && b.targetBlock()!.nextConnection) {
return false;
}
break;
@@ -305,4 +305,4 @@ export class ConnectionChecker implements IConnectionChecker {
}
registry.register(
registry.Type.CONNECTION_CHECKER, registry.DEFAULT, ConnectionChecker);
registry.Type.CONNECTION_CHECKER, registry.DEFAULT, ConnectionChecker);
+12 -12
View File
@@ -21,13 +21,13 @@
// Unused import preserved for side-effects. Remove if unneeded.
import './constants';
import { ConnectionType } from './connection_type.js';
import {ConnectionType} from './connection_type.js';
/* eslint-disable-next-line no-unused-vars */
import { IConnectionChecker } from './interfaces/i_connection_checker.js';
import {IConnectionChecker} from './interfaces/i_connection_checker.js';
/* eslint-disable-next-line no-unused-vars */
import { RenderedConnection } from './rendered_connection.js';
import {RenderedConnection} from './rendered_connection.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
/**
@@ -66,7 +66,7 @@ export class ConnectionDB {
* @return The index of the connection, or -1 if the connection was not found.
*/
private findIndexOfConnection_(conn: RenderedConnection, yPos: number):
number {
number {
if (!this.connections_.length) {
return -1;
}
@@ -89,7 +89,7 @@ export class ConnectionDB {
pointer = bestGuess;
while (pointer < this.connections_.length &&
this.connections_[pointer].y === yPos) {
this.connections_[pointer].y === yPos) {
if (this.connections_[pointer] === conn) {
return pointer;
}
@@ -145,7 +145,7 @@ export class ConnectionDB {
* @return List of connections.
*/
getNeighbours(connection: RenderedConnection, maxRadius: number):
RenderedConnection[] {
RenderedConnection[] {
const db = this.connections_;
const currentX = connection.x;
const currentY = connection.y;
@@ -206,7 +206,7 @@ export class ConnectionDB {
* @return True if connection is in range.
*/
private isInYRange_(index: number, baseY: number, maxRadius: number):
boolean {
boolean {
return Math.abs(this.connections_[index].y - baseY) <= maxRadius;
}
@@ -220,13 +220,13 @@ export class ConnectionDB {
* connection or null, and 'radius' which is the distance.
*/
searchForClosest(
conn: RenderedConnection, maxRadius: number,
dxy: Coordinate): { connection: RenderedConnection, radius: number } {
conn: RenderedConnection, maxRadius: number,
dxy: Coordinate): {connection: RenderedConnection, radius: number} {
if (!this.connections_.length) {
// Don't bother.
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'RenderedConnection'.
return { connection: null as AnyDuringMigration, radius: maxRadius };
return {connection: null as AnyDuringMigration, radius: maxRadius};
}
// Stash the values of x and y from before the drag.
@@ -260,7 +260,7 @@ export class ConnectionDB {
let pointerMax = closestIndex;
while (pointerMax < this.connections_.length &&
this.isInYRange_(pointerMax, conn.y, maxRadius)) {
this.isInYRange_(pointerMax, conn.y, maxRadius)) {
temp = this.connections_[pointerMax];
if (this.checker.canConnect(conn, temp, true, bestRadius)) {
bestConnection = temp;
+37 -37
View File
@@ -33,36 +33,36 @@
* @namespace Blockly.ContextMenu
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import {Block} from './block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as clipboard from './clipboard.js';
import { config } from './config.js';
import { ContextMenuOption, ContextMenuRegistry, LegacyContextMenuOption } from './contextmenu_registry.js';
import {config} from './config.js';
import {ContextMenuOption, ContextMenuRegistry, LegacyContextMenuOption} from './contextmenu_registry.js';
import * as BlockCreate from './events/events_block_create.js';
import * as eventUtils from './events/utils.js';
import { Menu } from './menu.js';
import { MenuItem } from './menuitem.js';
import { Msg } from './msg.js';
import {Menu} from './menu.js';
import {MenuItem} from './menuitem.js';
import {Msg} from './msg.js';
import * as aria from './utils/aria.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as deprecation from './utils/deprecation.js';
import * as dom from './utils/dom.js';
import { Rect } from './utils/rect.js';
import {Rect} from './utils/rect.js';
import * as svgMath from './utils/svg_math.js';
import * as userAgent from './utils/useragent.js';
import * as WidgetDiv from './widgetdiv.js';
import { WorkspaceCommentSvg } from './workspace_comment_svg.js';
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
import * as Xml from './xml.js';
/**
* Which block is the context menu attached to?
*/
let currentBlock: Block | null = null;
let currentBlock: Block|null = null;
let dummyOwner = {};
@@ -71,7 +71,7 @@ let dummyOwner = {};
* @return The block the context menu is attached to.
* @alias Blockly.ContextMenu.getCurrentBlock
*/
export function getCurrentBlock(): Block | null {
export function getCurrentBlock(): Block|null {
return currentBlock;
}
@@ -80,14 +80,14 @@ export function getCurrentBlock(): Block | null {
* @param block The block the context menu is attached to.
* @alias Blockly.ContextMenu.setCurrentBlock
*/
export function setCurrentBlock(block: Block | null) {
export function setCurrentBlock(block: Block|null) {
currentBlock = block;
}
/**
* Menu object.
*/
let menu_: Menu | null = null;
let menu_: Menu|null = null;
/**
* Construct the menu based on the list of options and show the menu.
@@ -97,8 +97,8 @@ let menu_: Menu | null = null;
* @alias Blockly.ContextMenu.show
*/
export function show(
e: Event, options: (ContextMenuOption | LegacyContextMenuOption)[],
rtl: boolean) {
e: Event, options: (ContextMenuOption|LegacyContextMenuOption)[],
rtl: boolean) {
WidgetDiv.show(dummyOwner, rtl, dispose);
if (!options.length) {
hide();
@@ -110,7 +110,7 @@ export function show(
position_(menu, e, rtl);
// 1ms delay is required for focusing on context menus because some other
// mouse event is still waiting in the queue and clears focus.
setTimeout(function () {
setTimeout(function() {
menu.focus();
}, 1);
currentBlock = null;
@@ -124,8 +124,8 @@ export function show(
* @return The menu that will be shown on right click.
*/
function populate_(
options: (ContextMenuOption | LegacyContextMenuOption)[],
rtl: boolean): Menu {
options: (ContextMenuOption|LegacyContextMenuOption)[],
rtl: boolean): Menu {
/* Here's what one option object looks like:
{text: 'Make It So',
enabled: true,
@@ -141,7 +141,7 @@ function populate_(
menu.addChild(menuItem);
menuItem.setEnabled(option.enabled);
if (option.enabled) {
const actionHandler = function (this: ContextMenuOption) {
const actionHandler = function(this: ContextMenuOption) {
hide();
this.callback(this.scope);
};
@@ -165,10 +165,10 @@ function position_(menu: Menu, e: Event, rtl: boolean) {
// This one is just a point, but we'll pretend that it's a rect so we can use
// some helper functions.
const anchorBBox = new Rect(
mouseEvent.clientY + viewportBBox.top,
mouseEvent.clientY + viewportBBox.top,
mouseEvent.clientX + viewportBBox.left,
mouseEvent.clientX + viewportBBox.left);
mouseEvent.clientY + viewportBBox.top,
mouseEvent.clientY + viewportBBox.top,
mouseEvent.clientX + viewportBBox.left,
mouseEvent.clientX + viewportBBox.left);
createWidget_(menu);
const menuSize = menu.getSize();
@@ -201,7 +201,7 @@ function createWidget_(menu: Menu) {
dom.addClass((menuDom as Element), 'blocklyContextMenu');
// Prevent system context menu when right-clicking a Blockly context menu.
browserEvents.conditionalBind(
(menuDom as EventTarget), 'contextmenu', null, haltPropagation);
(menuDom as EventTarget), 'contextmenu', null, haltPropagation);
// Focus only after the initial render to avoid issue #1329.
menu.focus();
}
@@ -279,11 +279,11 @@ export function callbackFactory(block: Block, xml: Element): Function {
* @alias Blockly.ContextMenu.commentDeleteOption
*/
export function commentDeleteOption(comment: WorkspaceCommentSvg):
LegacyContextMenuOption {
LegacyContextMenuOption {
const deleteOption = {
text: Msg['REMOVE_COMMENT'],
enabled: true,
callback: function () {
callback: function() {
eventUtils.setGroup(true);
comment.dispose();
eventUtils.setGroup(false);
@@ -301,11 +301,11 @@ export function commentDeleteOption(comment: WorkspaceCommentSvg):
* @alias Blockly.ContextMenu.commentDuplicateOption
*/
export function commentDuplicateOption(comment: WorkspaceCommentSvg):
LegacyContextMenuOption {
LegacyContextMenuOption {
const duplicateOption = {
text: Msg['DUPLICATE_COMMENT'],
enabled: true,
callback: function () {
callback: function() {
clipboard.duplicate(comment);
},
};
@@ -323,13 +323,13 @@ export function commentDuplicateOption(comment: WorkspaceCommentSvg):
* @alias Blockly.ContextMenu.workspaceCommentOption
*/
export function workspaceCommentOption(
ws: WorkspaceSvg, e: Event): ContextMenuOption {
ws: WorkspaceSvg, e: Event): ContextMenuOption {
// Helper function to create and position a comment correctly based on the
// location of the mouse event.
function addWsComment() {
const comment = new WorkspaceCommentSvg(
ws, Msg['WORKSPACE_COMMENT_DEFAULT_TEXT'],
WorkspaceCommentSvg.DEFAULT_SIZE, WorkspaceCommentSvg.DEFAULT_SIZE);
ws, Msg['WORKSPACE_COMMENT_DEFAULT_TEXT'],
WorkspaceCommentSvg.DEFAULT_SIZE, WorkspaceCommentSvg.DEFAULT_SIZE);
const injectionDiv = ws.getInjectionDiv();
// Bounding rect coordinates are in client coordinates, meaning that they
@@ -340,8 +340,8 @@ export function workspaceCommentOption(
// The client coordinates offset by the injection div's upper left corner.
const mouseEvent = e as MouseEvent;
const clientOffsetPixels = new Coordinate(
mouseEvent.clientX - boundingRect.left,
mouseEvent.clientY - boundingRect.top);
mouseEvent.clientX - boundingRect.left,
mouseEvent.clientY - boundingRect.top);
// The offset in pixels between the main workspace's origin and the upper
// left corner of the injection div.
@@ -350,7 +350,7 @@ export function workspaceCommentOption(
// The position of the new comment in pixels relative to the origin of the
// main workspace.
const finalOffset =
Coordinate.difference(clientOffsetPixels, mainOffsetPixels);
Coordinate.difference(clientOffsetPixels, mainOffsetPixels);
// The position of the new comment in main workspace coordinates.
finalOffset.scale(1 / ws.scale);
@@ -370,7 +370,7 @@ export function workspaceCommentOption(
enabled: !userAgent.IE,
} as ContextMenuOption;
wsCommentOption.text = Msg['ADD_COMMENT'];
wsCommentOption.callback = function () {
wsCommentOption.callback = function() {
addWsComment();
};
return wsCommentOption;
+24 -24
View File
@@ -12,18 +12,18 @@
* @namespace Blockly.ContextMenuItems
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as clipboard from './clipboard.js';
import { ContextMenuRegistry, RegistryItem, Scope } from './contextmenu_registry.js';
import {ContextMenuRegistry, RegistryItem, Scope} from './contextmenu_registry.js';
import * as dialog from './dialog.js';
import * as Events from './events/events.js';
import * as eventUtils from './events/utils.js';
import { inputTypes } from './input_types.js';
import { Msg } from './msg.js';
import {inputTypes} from './input_types.js';
import {Msg} from './msg.js';
import * as idGenerator from './utils/idgenerator.js';
import * as userAgent from './utils/useragent.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -275,7 +275,7 @@ export function registerDeleteAll() {
return Msg['DELETE_BLOCK'];
} else {
return Msg['DELETE_X_BLOCKS'].replace(
'%1', String(deletableBlocksLength));
'%1', String(deletableBlocksLength));
}
},
preconditionFn(scope: Scope) {
@@ -296,13 +296,13 @@ export function registerDeleteAll() {
deleteNext_(deletableBlocks, eventGroup);
} else {
dialog.confirm(
Msg['DELETE_ALL_BLOCKS'].replace(
'%1', String(deletableBlocks.length)),
function (ok) {
if (ok) {
deleteNext_(deletableBlocks, eventGroup);
}
});
Msg['DELETE_ALL_BLOCKS'].replace(
'%1', String(deletableBlocks.length)),
function(ok) {
if (ok) {
deleteNext_(deletableBlocks, eventGroup);
}
});
}
},
scopeType: ContextMenuRegistry.ScopeType.WORKSPACE,
@@ -370,8 +370,8 @@ export function registerComment() {
const block = scope.block;
// IE doesn't support necessary features for comment editing.
if (!userAgent.IE && !block!.isInFlyout &&
block!.workspace.options.comments && !block!.isCollapsed() &&
block!.isEditable()) {
block!.workspace.options.comments && !block!.isCollapsed() &&
block!.isEditable()) {
return 'enabled';
}
return 'hidden';
@@ -399,7 +399,7 @@ export function registerInline() {
const inlineOption: RegistryItem = {
displayText(scope: Scope) {
return scope.block!.getInputsInline() ? Msg['EXTERNAL_INPUTS'] :
Msg['INLINE_INPUTS'];
Msg['INLINE_INPUTS'];
},
preconditionFn(scope: Scope) {
const block = scope.block;
@@ -408,7 +408,7 @@ export function registerInline() {
// Only display this option if there are two value or dummy inputs
// next to each other.
if (block!.inputList[i - 1].type !== inputTypes.STATEMENT &&
block!.inputList[i].type !== inputTypes.STATEMENT) {
block!.inputList[i].type !== inputTypes.STATEMENT) {
return 'enabled';
}
}
@@ -433,12 +433,12 @@ export function registerCollapseExpandBlock() {
const collapseExpandOption: RegistryItem = {
displayText(scope: Scope) {
return scope.block!.isCollapsed() ? Msg['EXPAND_BLOCK'] :
Msg['COLLAPSE_BLOCK'];
Msg['COLLAPSE_BLOCK'];
},
preconditionFn(scope: Scope) {
const block = scope.block;
if (!block!.isInFlyout && block!.isMovable() &&
block!.workspace.options.collapse) {
block!.workspace.options.collapse) {
return 'enabled';
}
return 'hidden';
@@ -461,12 +461,12 @@ export function registerDisable() {
const disableOption: RegistryItem = {
displayText(scope: Scope) {
return scope.block!.isEnabled() ? Msg['DISABLE_BLOCK'] :
Msg['ENABLE_BLOCK'];
Msg['ENABLE_BLOCK'];
},
preconditionFn(scope: Scope) {
const block = scope.block;
if (!block!.isInFlyout && block!.workspace.options.disable &&
block!.isEditable()) {
block!.isEditable()) {
if (block!.getInheritedDisabled()) {
return 'disabled';
}
@@ -508,8 +508,8 @@ export function registerDelete() {
descendantCount -= nextBlock.getDescendants(false).length;
}
return descendantCount === 1 ?
Msg['DELETE_BLOCK'] :
Msg['DELETE_X_BLOCKS'].replace('%1', String(descendantCount));
Msg['DELETE_BLOCK'] :
Msg['DELETE_X_BLOCKS'].replace('%1', String(descendantCount));
},
preconditionFn(scope: Scope) {
if (!scope.block!.isInFlyout && scope.block!.isDeletable()) {
@@ -541,7 +541,7 @@ export function registerHelp() {
preconditionFn(scope: Scope) {
const block = scope.block;
const url = typeof block!.helpUrl === 'function' ? block!.helpUrl() :
block!.helpUrl;
block!.helpUrl;
if (url) {
return 'enabled';
}
+12 -12
View File
@@ -13,9 +13,9 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
enum ScopeType {
@@ -38,7 +38,7 @@ export class ContextMenuRegistry {
static ScopeType = ScopeType;
static registry: ContextMenuRegistry;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
private registry_!: { [key: string]: RegistryItem };
private registry_!: {[key: string]: RegistryItem};
/** Resets the existing singleton instance of ContextMenuRegistry. */
constructor() {
@@ -79,7 +79,7 @@ export class ContextMenuRegistry {
* @param id The ID of the RegistryItem to get.
* @return RegistryItem or null if not found
*/
getItem(id: string): RegistryItem | null {
getItem(id: string): RegistryItem|null {
return this.registry_[id] || null;
}
@@ -94,17 +94,17 @@ export class ContextMenuRegistry {
* @return the list of ContextMenuOptions
*/
getContextMenuOptions(scopeType: ScopeType, scope: Scope):
ContextMenuOption[] {
ContextMenuOption[] {
const menuOptions: AnyDuringMigration[] = [];
const registry = this.registry_;
Object.keys(registry).forEach(function (id) {
Object.keys(registry).forEach(function(id) {
const item = registry[id];
if (scopeType === item.scopeType) {
const precondition = item.preconditionFn(scope);
if (precondition !== 'hidden') {
const displayText = typeof item.displayText === 'function' ?
item.displayText(scope) :
item.displayText;
item.displayText(scope) :
item.displayText;
const menuOption: ContextMenuOption = {
text: displayText,
enabled: precondition === 'enabled',
@@ -116,20 +116,20 @@ export class ContextMenuRegistry {
}
}
});
menuOptions.sort(function (a, b) {
menuOptions.sort(function(a, b) {
return a.weight - b.weight;
});
return menuOptions;
}
}
export interface Scope {
block: BlockSvg | undefined;
workspace: WorkspaceSvg | undefined;
block: BlockSvg|undefined;
workspace: WorkspaceSvg|undefined;
}
export interface RegistryItem {
callback: (p1: Scope) => AnyDuringMigration;
scopeType: ScopeType;
displayText: ((p1: Scope) => string) | string;
displayText: ((p1: Scope) => string)|string;
preconditionFn: (p1: Scope) => string;
weight: number;
id: string;
+3 -3
View File
@@ -24,15 +24,15 @@ let injected = false;
* @param cssContent Multiline CSS string or an array of single lines of CSS.
* @alias Blockly.Css.register
*/
export function register(cssContent: string | string[]) {
export function register(cssContent: string|string[]) {
if (injected) {
throw Error('CSS already injected');
}
if (Array.isArray(cssContent)) {
deprecation.warn(
'Registering CSS by passing an array of strings', 'September 2021',
'September 2022', 'css.register passing a multiline string');
'Registering CSS by passing an array of strings', 'September 2021',
'September 2022', 'css.register passing a multiline string');
content += '\n' + cssContent.join('\n');
} else {
// Add new cssContent in the global content.
+4 -4
View File
@@ -17,12 +17,12 @@
* @class
*/
import { BlockSvg } from './block_svg.js';
import { DragTarget } from './drag_target.js';
import {BlockSvg} from './block_svg.js';
import {DragTarget} from './drag_target.js';
/* eslint-disable-next-line no-unused-vars */
import { IDeleteArea } from './interfaces/i_delete_area.js';
import {IDeleteArea} from './interfaces/i_delete_area.js';
/* eslint-disable-next-line no-unused-vars */
import { IDraggable } from './interfaces/i_draggable.js';
import {IDraggable} from './interfaces/i_draggable.js';
/**
+18 -18
View File
@@ -16,22 +16,22 @@
* @namespace Blockly.dialog
*/
let alertImplementation = function (
message: AnyDuringMigration, opt_callback: AnyDuringMigration) {
let alertImplementation = function(
message: AnyDuringMigration, opt_callback: AnyDuringMigration) {
window.alert(message);
if (opt_callback) {
opt_callback();
}
};
let confirmImplementation = function (
message: AnyDuringMigration, callback: AnyDuringMigration) {
let confirmImplementation = function(
message: AnyDuringMigration, callback: AnyDuringMigration) {
callback(window.confirm(message));
};
let promptImplementation = function (
message: AnyDuringMigration, defaultValue: AnyDuringMigration,
callback: AnyDuringMigration) {
let promptImplementation = function(
message: AnyDuringMigration, defaultValue: AnyDuringMigration,
callback: AnyDuringMigration) {
callback(window.prompt(message, defaultValue));
};
@@ -43,7 +43,7 @@ let promptImplementation = function (
* @alias Blockly.dialog.alert
*/
export function alert(
message: string, opt_callback?: () => AnyDuringMigration) {
message: string, opt_callback?: () => AnyDuringMigration) {
alertImplementation(message, opt_callback);
}
@@ -54,8 +54,8 @@ export function alert(
* @alias Blockly.dialog.setAlert
*/
export function setAlert(
alertFunction: (p1: string, p2?: () => AnyDuringMigration) =>
AnyDuringMigration) {
alertFunction: (p1: string, p2?: () => AnyDuringMigration) =>
AnyDuringMigration) {
alertImplementation = alertFunction;
}
@@ -67,7 +67,7 @@ export function setAlert(
* @alias Blockly.dialog.confirm
*/
export function confirm(
message: string, callback: (p1: boolean) => AnyDuringMigration) {
message: string, callback: (p1: boolean) => AnyDuringMigration) {
confirmImplementation(message, callback);
}
@@ -78,8 +78,8 @@ export function confirm(
* @alias Blockly.dialog.setConfirm
*/
export function setConfirm(
confirmFunction: (p1: string, p2: (p1: boolean) => AnyDuringMigration) =>
AnyDuringMigration) {
confirmFunction: (p1: string, p2: (p1: boolean) => AnyDuringMigration) =>
AnyDuringMigration) {
confirmImplementation = confirmFunction;
}
@@ -94,8 +94,8 @@ export function setConfirm(
* @alias Blockly.dialog.prompt
*/
export function prompt(
message: string, defaultValue: string,
callback: (p1: string | null) => AnyDuringMigration) {
message: string, defaultValue: string,
callback: (p1: string|null) => AnyDuringMigration) {
promptImplementation(message, defaultValue, callback);
}
@@ -106,8 +106,8 @@ export function prompt(
* @alias Blockly.dialog.setPrompt
*/
export function setPrompt(
promptFunction:
(p1: string, p2: string, p3: (p1: string | null) => AnyDuringMigration) =>
AnyDuringMigration) {
promptFunction:
(p1: string, p2: string, p3: (p1: string|null) => AnyDuringMigration) =>
AnyDuringMigration) {
promptImplementation = promptFunction;
}
+4 -4
View File
@@ -18,11 +18,11 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { IDragTarget } from './interfaces/i_drag_target.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
/* eslint-disable-next-line no-unused-vars */
import { IDraggable } from './interfaces/i_draggable.js';
import {IDraggable} from './interfaces/i_draggable.js';
/* eslint-disable-next-line no-unused-vars */
import { Rect } from './utils/rect.js';
import {Rect} from './utils/rect.js';
/**
@@ -79,7 +79,7 @@ export class DragTarget implements IDragTarget {
* @return The component's bounding box. Null if drag target area should be
* ignored.
*/
getClientRect(): Rect | null {
getClientRect(): Rect|null {
return null;
}
+58 -58
View File
@@ -17,18 +17,18 @@
* @class
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as common from './common.js';
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import {Field} from './field.js';
import * as dom from './utils/dom.js';
import * as math from './utils/math.js';
import { Rect } from './utils/rect.js';
import {Rect} from './utils/rect.js';
/* eslint-disable-next-line no-unused-vars */
import { Size } from './utils/size.js';
import {Size} from './utils/size.js';
import * as style from './utils/style.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -59,10 +59,10 @@ export const ANIMATION_TIME = 0.25;
* Timer for animation out, to be cleared if we need to immediately hide
* without disrupting new shows.
*/
let animateOutTimer: number | null = null;
let animateOutTimer: number|null = null;
/** Callback for when the drop-down is hidden. */
let onHide: Function | null = null;
let onHide: Function|null = null;
/** A class name representing the current owner's workspace renderer. */
let renderedClassName = '';
@@ -83,13 +83,13 @@ let arrow: HTMLDivElement;
* Drop-downs will appear within the bounds of this element if possible.
* Set in setBoundsElement.
*/
let boundsElement: Element | null = null;
let boundsElement: Element|null = null;
/** The object currently using the drop-down. */
let owner: AnyDuringMigration | null = null;
let owner: AnyDuringMigration|null = null;
/** Whether the dropdown was positioned to a field or the source block. */
let positionToField: boolean | null = null;
let positionToField: boolean|null = null;
/**
* Dropdown bounds info object used to encapsulate sizing information about a
@@ -110,9 +110,9 @@ export interface PositionMetrics {
initialY: number;
finalX: number;
finalY: number;
arrowX: number | null;
arrowY: number | null;
arrowAtTop: boolean | null;
arrowX: number|null;
arrowY: number|null;
arrowAtTop: boolean|null;
arrowVisible: boolean;
}
@@ -140,14 +140,14 @@ export function createDom() {
div.style.opacity = 0 as AnyDuringMigration;
// Transition animation for transform: translate() and opacity.
div.style.transition = 'transform ' + ANIMATION_TIME + 's, ' +
'opacity ' + ANIMATION_TIME + 's';
'opacity ' + ANIMATION_TIME + 's';
// Handle focusin/out events to add a visual indicator when
// a child is focused or blurred.
div.addEventListener('focusin', function () {
div.addEventListener('focusin', function() {
dom.addClass(div, 'blocklyFocused');
});
div.addEventListener('focusout', function () {
div.addEventListener('focusout', function() {
dom.removeClass(div, 'blocklyFocused');
});
}
@@ -157,7 +157,7 @@ export function createDom() {
* within the box of this element if possible.
* @param boundsElem Element to bind drop-down to.
*/
export function setBoundsElement(boundsElem: Element | null) {
export function setBoundsElement(boundsElem: Element|null) {
boundsElement = boundsElem;
}
@@ -197,10 +197,10 @@ export function setColour(backgroundColour: string, borderColour: string) {
* @return True if the menu rendered below block; false if above.
*/
export function showPositionedByBlock(
field: Field, block: BlockSvg, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
field: Field, block: BlockSvg, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
return showPositionedByRect(
getScaledBboxOfBlock(block), field, opt_onHide, opt_secondaryYOffset);
getScaledBboxOfBlock(block), field, opt_onHide, opt_secondaryYOffset);
}
/**
@@ -214,11 +214,11 @@ export function showPositionedByBlock(
* @return True if the menu rendered below block; false if above.
*/
export function showPositionedByField(
field: Field, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
field: Field, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
positionToField = true;
return showPositionedByRect(
getScaledBboxOfField(field), field, opt_onHide, opt_secondaryYOffset);
getScaledBboxOfField(field), field, opt_onHide, opt_secondaryYOffset);
}
/**
* Get the scaled bounding box of a block.
@@ -256,8 +256,8 @@ function getScaledBboxOfField(field: Field): Rect {
* @return True if the menu rendered below block; false if above.
*/
function showPositionedByRect(
bBox: Rect, field: Field, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
bBox: Rect, field: Field, opt_onHide?: Function,
opt_secondaryYOffset?: number): boolean {
// If we can fit it, render below the block.
const primaryX = bBox.left + (bBox.right - bBox.left) / 2;
const primaryY = bBox.bottom;
@@ -275,8 +275,8 @@ function showPositionedByRect(
}
setBoundsElement(workspace.getParentSvg().parentNode as Element | null);
return show(
field, sourceBlock.RTL, primaryX, primaryY, secondaryX, secondaryY,
opt_onHide);
field, sourceBlock.RTL, primaryX, primaryY, secondaryX, secondaryY,
opt_onHide);
}
/**
@@ -297,9 +297,9 @@ function showPositionedByRect(
* @return True if the menu rendered at the primary origin point.
*/
export function show(
newOwner: AnyDuringMigration | null, rtl: boolean, primaryX: number,
primaryY: number, secondaryX: number, secondaryY: number,
opt_onHide?: Function): boolean {
newOwner: AnyDuringMigration|null, rtl: boolean, primaryX: number,
primaryY: number, secondaryX: number, secondaryY: number,
opt_onHide?: Function): boolean {
owner = newOwner;
onHide = opt_onHide || null;
// Set direction.
@@ -331,7 +331,7 @@ const internal = {};
*/
// AnyDuringMigration because: Property 'getBoundsInfo' does not exist on type
// '{}'.
(internal as AnyDuringMigration).getBoundsInfo = function (): BoundsInfo {
(internal as AnyDuringMigration).getBoundsInfo = function(): BoundsInfo {
const boundPosition = style.getPageOffset(boundsElement as Element);
const boundSize = style.getSize(boundsElement as Element);
@@ -357,9 +357,9 @@ const internal = {};
*/
// AnyDuringMigration because: Property 'getPositionMetrics' does not exist on
// type '{}'.
(internal as AnyDuringMigration).getPositionMetrics = function (
primaryX: number, primaryY: number, secondaryX: number,
secondaryY: number): PositionMetrics {
(internal as AnyDuringMigration).getPositionMetrics = function(
primaryX: number, primaryY: number, secondaryX: number,
secondaryY: number): PositionMetrics {
// AnyDuringMigration because: Property 'getBoundsInfo' does not exist on
// type '{}'.
const boundsInfo = (internal as AnyDuringMigration).getBoundsInfo();
@@ -398,10 +398,10 @@ const internal = {};
* arrow.
*/
function getPositionBelowMetrics(
primaryX: number, primaryY: number, boundsInfo: BoundsInfo,
divSize: Size): PositionMetrics {
primaryX: number, primaryY: number, boundsInfo: BoundsInfo,
divSize: Size): PositionMetrics {
const xCoords =
getPositionX(primaryX, boundsInfo.left, boundsInfo.right, divSize.width);
getPositionX(primaryX, boundsInfo.left, boundsInfo.right, divSize.width);
const arrowY = -(ARROW_SIZE / 2 + BORDER_SIZE);
const finalY = primaryY + PADDING_Y;
@@ -430,10 +430,10 @@ function getPositionBelowMetrics(
* arrow.
*/
function getPositionAboveMetrics(
secondaryX: number, secondaryY: number, boundsInfo: BoundsInfo,
divSize: Size): PositionMetrics {
secondaryX: number, secondaryY: number, boundsInfo: BoundsInfo,
divSize: Size): PositionMetrics {
const xCoords = getPositionX(
secondaryX, boundsInfo.left, boundsInfo.right, divSize.width);
secondaryX, boundsInfo.left, boundsInfo.right, divSize.width);
const arrowY = divSize.height - BORDER_SIZE * 2 - ARROW_SIZE / 2;
const finalY = secondaryY - divSize.height - PADDING_Y;
@@ -463,9 +463,9 @@ function getPositionAboveMetrics(
* arrow.
*/
function getPositionTopOfPageMetrics(
sourceX: number, boundsInfo: BoundsInfo, divSize: Size): PositionMetrics {
sourceX: number, boundsInfo: BoundsInfo, divSize: Size): PositionMetrics {
const xCoords =
getPositionX(sourceX, boundsInfo.left, boundsInfo.right, divSize.width);
getPositionX(sourceX, boundsInfo.left, boundsInfo.right, divSize.width);
// No need to provide arrow-specific information because it won't be visible.
return {
@@ -491,8 +491,8 @@ function getPositionTopOfPageMetrics(
* the DropDownDiv and the arrow.
*/
export function getPositionX(
sourceX: number, boundsLeft: number, boundsRight: number,
divWidth: number): { divX: number, arrowX: number } {
sourceX: number, boundsLeft: number, boundsRight: number,
divWidth: number): {divX: number, arrowX: number} {
let divX = sourceX;
// Offset the topLeft coord so that the dropdowndiv is centered.
divX -= divWidth / 2;
@@ -507,9 +507,9 @@ export function getPositionX(
const horizPadding = ARROW_HORIZONTAL_PADDING;
// Clamp the arrow position so that it stays attached to the dropdowndiv.
relativeArrowX = math.clamp(
horizPadding, relativeArrowX, divWidth - horizPadding - ARROW_SIZE);
horizPadding, relativeArrowX, divWidth - horizPadding - ARROW_SIZE);
return { arrowX: relativeArrowX, divX };
return {arrowX: relativeArrowX, divX};
}
/**
@@ -528,8 +528,8 @@ export function isVisible(): boolean {
* @return True if hidden.
*/
export function hideIfOwner(
divOwner: AnyDuringMigration | null,
opt_withoutAnimation?: boolean): boolean {
divOwner: AnyDuringMigration|null,
opt_withoutAnimation?: boolean): boolean {
if (owner === divOwner) {
if (opt_withoutAnimation) {
hideWithoutAnimation();
@@ -550,7 +550,7 @@ export function hide() {
// 'string'.
div.style.opacity = 0 as AnyDuringMigration;
// Finish animation - reset all values to default.
animateOutTimer = setTimeout(function () {
animateOutTimer = setTimeout(function() {
hideWithoutAnimation();
}, ANIMATION_TIME * 1000);
if (onHide) {
@@ -607,23 +607,23 @@ export function hideWithoutAnimation() {
* @return True if the menu rendered at the primary origin point.
*/
function positionInternal(
primaryX: number, primaryY: number, secondaryX: number,
secondaryY: number): boolean {
primaryX: number, primaryY: number, secondaryX: number,
secondaryY: number): boolean {
// AnyDuringMigration because: Property 'getPositionMetrics' does not exist
// on type '{}'.
const metrics =
(internal as AnyDuringMigration)
.getPositionMetrics(primaryX, primaryY, secondaryX, secondaryY);
(internal as AnyDuringMigration)
.getPositionMetrics(primaryX, primaryY, secondaryX, secondaryY);
// Update arrow CSS.
if (metrics.arrowVisible) {
arrow.style.display = '';
arrow.style.transform = 'translate(' + metrics.arrowX + 'px,' +
metrics.arrowY + 'px) rotate(45deg)';
metrics.arrowY + 'px) rotate(45deg)';
arrow.setAttribute(
'class',
metrics.arrowAtTop ? 'blocklyDropDownArrow blocklyArrowTop' :
'blocklyDropDownArrow blocklyArrowBottom');
'class',
metrics.arrowAtTop ? 'blocklyDropDownArrow blocklyArrowTop' :
'blocklyDropDownArrow blocklyArrowBottom');
} else {
arrow.style.display = 'none';
}
@@ -666,7 +666,7 @@ export function repositionForWindowResize() {
const field = owner as Field;
const block = field.getSourceBlock() as BlockSvg;
const bBox = positionToField ? getScaledBboxOfField(field) :
getScaledBboxOfBlock(block);
getScaledBboxOfBlock(block);
// If we can fit it, render below the block.
const primaryX = bBox.left + (bBox.right - bBox.left) / 2;
const primaryY = bBox.bottom;
+53 -53
View File
@@ -14,64 +14,64 @@
import * as deprecation from '../utils/deprecation.js';
import { Abstract as AbstractEvent } from './events_abstract.js';
import { BlockBase } from './events_block_base.js';
import { BlockChange } from './events_block_change.js';
import { BlockCreate } from './events_block_create.js';
import { BlockDelete } from './events_block_delete.js';
import { BlockDrag } from './events_block_drag.js';
import { BlockMove } from './events_block_move.js';
import { BubbleOpen } from './events_bubble_open.js';
import { Click } from './events_click.js';
import { CommentBase } from './events_comment_base.js';
import { CommentChange } from './events_comment_change.js';
import { CommentCreate } from './events_comment_create.js';
import { CommentDelete } from './events_comment_delete.js';
import { CommentMove } from './events_comment_move.js';
import { MarkerMove } from './events_marker_move.js';
import { Selected } from './events_selected.js';
import { ThemeChange } from './events_theme_change.js';
import { ToolboxItemSelect } from './events_toolbox_item_select.js';
import { TrashcanOpen } from './events_trashcan_open.js';
import { Ui } from './events_ui.js';
import { UiBase } from './events_ui_base.js';
import { VarBase } from './events_var_base.js';
import { VarCreate } from './events_var_create.js';
import { VarDelete } from './events_var_delete.js';
import { VarRename } from './events_var_rename.js';
import { ViewportChange } from './events_viewport.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
import {BlockBase} from './events_block_base.js';
import {BlockChange} from './events_block_change.js';
import {BlockCreate} from './events_block_create.js';
import {BlockDelete} from './events_block_delete.js';
import {BlockDrag} from './events_block_drag.js';
import {BlockMove} from './events_block_move.js';
import {BubbleOpen} from './events_bubble_open.js';
import {Click} from './events_click.js';
import {CommentBase} from './events_comment_base.js';
import {CommentChange} from './events_comment_change.js';
import {CommentCreate} from './events_comment_create.js';
import {CommentDelete} from './events_comment_delete.js';
import {CommentMove} from './events_comment_move.js';
import {MarkerMove} from './events_marker_move.js';
import {Selected} from './events_selected.js';
import {ThemeChange} from './events_theme_change.js';
import {ToolboxItemSelect} from './events_toolbox_item_select.js';
import {TrashcanOpen} from './events_trashcan_open.js';
import {Ui} from './events_ui.js';
import {UiBase} from './events_ui_base.js';
import {VarBase} from './events_var_base.js';
import {VarCreate} from './events_var_create.js';
import {VarDelete} from './events_var_delete.js';
import {VarRename} from './events_var_rename.js';
import {ViewportChange} from './events_viewport.js';
import * as eventUtils from './utils.js';
import { FinishedLoading } from './workspace_events.js';
import {FinishedLoading} from './workspace_events.js';
// Events.
export const Abstract = AbstractEvent;
export { BubbleOpen };
export { BlockBase };
export { BlockChange };
export { BlockCreate };
export { BlockDelete };
export { BlockDrag };
export { BlockMove };
export { Click };
export { CommentBase };
export { CommentChange };
export { CommentCreate };
export { CommentDelete };
export { CommentMove };
export { FinishedLoading };
export { MarkerMove };
export { Selected };
export { ThemeChange };
export { ToolboxItemSelect };
export { TrashcanOpen };
export { Ui };
export { UiBase };
export { VarBase };
export { VarCreate };
export { VarDelete };
export { VarRename };
export { ViewportChange };
export {BubbleOpen};
export {BlockBase};
export {BlockChange};
export {BlockCreate};
export {BlockDelete};
export {BlockDrag};
export {BlockMove};
export {Click};
export {CommentBase};
export {CommentChange};
export {CommentCreate};
export {CommentDelete};
export {CommentMove};
export {FinishedLoading};
export {MarkerMove};
export {Selected};
export {ThemeChange};
export {ToolboxItemSelect};
export {TrashcanOpen};
export {Ui};
export {UiBase};
export {VarBase};
export {VarCreate};
export {VarDelete};
export {VarRename};
export {ViewportChange};
// Event types.
export const BLOCK_CHANGE = eventUtils.BLOCK_CHANGE;
+5 -5
View File
@@ -17,7 +17,7 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from '../workspace.js';
import {Workspace} from '../workspace.js';
import * as eventUtils from './utils.js';
@@ -28,7 +28,7 @@ import * as eventUtils from './utils.js';
*/
export abstract class Abstract {
/** Whether or not the event is blank (to be populated by fromJson). */
isBlank: boolean | null = null;
isBlank: boolean|null = null;
/** The workspace identifier for this event. */
workspaceId?: string = undefined;
@@ -59,7 +59,7 @@ export abstract class Abstract {
* @return JSON representation.
*/
toJson(): AnyDuringMigration {
const json = { 'type': this.type };
const json = {'type': this.type};
if (this.group) {
(json as AnyDuringMigration)['group'] = this.group;
}
@@ -102,8 +102,8 @@ export abstract class Abstract {
}
if (!workspace) {
throw Error(
'Workspace is null. Event must have been generated from real' +
' Blockly events.');
'Workspace is null. Event must have been generated from real' +
' Blockly events.');
}
return workspace;
}
+2 -2
View File
@@ -13,9 +13,9 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import { Abstract as AbstractEvent } from './events_abstract.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
/**
+7 -7
View File
@@ -13,13 +13,13 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from '../block_svg.js';
import {BlockSvg} from '../block_svg.js';
import * as registry from '../registry.js';
import * as Xml from '../xml.js';
import { BlockBase } from './events_block_base.js';
import {BlockBase} from './events_block_base.js';
import * as eventUtils from './utils.js';
@@ -32,7 +32,7 @@ export class BlockChange extends BlockBase {
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
element!: string;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
name!: string | null;
name!: string|null;
oldValue: AnyDuringMigration;
newValue: AnyDuringMigration;
@@ -44,8 +44,8 @@ export class BlockChange extends BlockBase {
* @param opt_newValue New value of element.
*/
constructor(
opt_block?: Block, opt_element?: string, opt_name?: string | null,
opt_oldValue?: AnyDuringMigration, opt_newValue?: AnyDuringMigration) {
opt_block?: Block, opt_element?: string, opt_name?: string|null,
opt_oldValue?: AnyDuringMigration, opt_newValue?: AnyDuringMigration) {
super(opt_block);
/** Type of this event. */
@@ -143,7 +143,7 @@ export class BlockChange extends BlockBase {
block.domToMutation(Xml.textToDom(value as string || '<mutation/>'));
}
eventUtils.fire(
new BlockChange(block, 'mutation', null, oldState, value));
new BlockChange(block, 'mutation', null, oldState, value));
break;
}
default:
+3 -3
View File
@@ -13,12 +13,12 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import * as blocks from '../serialization/blocks.js';
import * as Xml from '../xml.js';
import { BlockBase } from './events_block_base.js';
import {BlockBase} from './events_block_base.js';
import * as eventUtils from './utils.js';
@@ -54,7 +54,7 @@ export class BlockCreate extends BlockBase {
this.ids = eventUtils.getDescendantIds(opt_block);
/** JSON representation of the block that was just created. */
this.json = blocks.save(opt_block, { addCoordinates: true }) as blocks.State;
this.json = blocks.save(opt_block, {addCoordinates: true}) as blocks.State;
}
/**
+4 -4
View File
@@ -13,12 +13,12 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import * as blocks from '../serialization/blocks.js';
import * as Xml from '../xml.js';
import { BlockBase } from './events_block_base.js';
import {BlockBase} from './events_block_base.js';
import * as eventUtils from './utils.js';
@@ -63,7 +63,7 @@ export class BlockDelete extends BlockBase {
/** JSON representation of the block that was just deleted. */
this.oldJson =
blocks.save(opt_block, { addCoordinates: true }) as blocks.State;
blocks.save(opt_block, {addCoordinates: true}) as blocks.State;
}
/**
@@ -91,7 +91,7 @@ export class BlockDelete extends BlockBase {
this.oldXml = Xml.textToDom(json['oldXml']);
this.ids = json['ids'];
this.wasShadow =
json['wasShadow'] || this.oldXml.tagName.toLowerCase() === 'shadow';
json['wasShadow'] || this.oldXml.tagName.toLowerCase() === 'shadow';
this.oldJson = json['oldJson'] as blocks.State;
if (json['recordUndo'] !== undefined) {
this.recordUndo = json['recordUndo'];
+2 -2
View File
@@ -13,10 +13,10 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
+14 -14
View File
@@ -13,18 +13,18 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import { ConnectionType } from '../connection_type.js';
import {Block} from '../block.js';
import {ConnectionType} from '../connection_type.js';
import * as registry from '../registry.js';
import { Coordinate } from '../utils/coordinate.js';
import {Coordinate} from '../utils/coordinate.js';
import { BlockBase } from './events_block_base.js';
import {BlockBase} from './events_block_base.js';
import * as eventUtils from './utils.js';
interface BlockLocation {
parentId: string;
inputName: string;
coordinate: Coordinate | null;
coordinate: Coordinate|null;
} // eslint-disable-line no-unused-vars
/**
@@ -40,11 +40,11 @@ export class BlockMove extends BlockBase {
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
oldInputName!: string;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
oldCoordinate!: Coordinate | null;
oldCoordinate!: Coordinate|null;
newParentId: string | null = null;
newInputName: string | null = null;
newCoordinate: Coordinate | null = null;
newParentId: string|null = null;
newInputName: string|null = null;
newCoordinate: Coordinate|null = null;
/** @param opt_block The moved block. Undefined for a blank event. */
constructor(opt_block?: Block) {
@@ -80,7 +80,7 @@ export class BlockMove extends BlockBase {
}
if (this.newCoordinate) {
json['newCoordinate'] = Math.round(this.newCoordinate.x) + ',' +
Math.round(this.newCoordinate.y);
Math.round(this.newCoordinate.y);
}
if (!this.recordUndo) {
json['recordUndo'] = this.recordUndo;
@@ -143,8 +143,8 @@ export class BlockMove extends BlockBase {
*/
override isNull(): boolean {
return this.oldParentId === this.newParentId &&
this.oldInputName === this.newInputName &&
Coordinate.equals(this.oldCoordinate, this.newCoordinate);
this.oldInputName === this.newInputName &&
Coordinate.equals(this.oldCoordinate, this.newCoordinate);
}
/**
@@ -161,7 +161,7 @@ export class BlockMove extends BlockBase {
const parentId = forward ? this.newParentId : this.oldParentId;
const inputName = forward ? this.newInputName : this.oldInputName;
const coordinate = forward ? this.newCoordinate : this.oldCoordinate;
let parentBlock: Block | null;
let parentBlock: Block|null;
if (parentId) {
parentBlock = workspace.getBlockById(parentId);
if (!parentBlock) {
@@ -178,7 +178,7 @@ export class BlockMove extends BlockBase {
} else {
let blockConnection = block.outputConnection;
if (!blockConnection ||
block.previousConnection && block.previousConnection.isConnected()) {
block.previousConnection && block.previousConnection.isConnected()) {
blockConnection = block.previousConnection;
}
let parentConnection;
+4 -4
View File
@@ -13,10 +13,10 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from '../block_svg.js';
import {BlockSvg} from '../block_svg.js';
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -25,7 +25,7 @@ import * as eventUtils from './utils.js';
* @alias Blockly.Events.BubbleOpen
*/
export class BubbleOpen extends UiBase {
blockId: string | null;
blockId: string|null;
isOpen?: boolean;
bubbleType?: string;
override type: string;
@@ -38,7 +38,7 @@ export class BubbleOpen extends UiBase {
* 'warning'. Undefined for a blank event.
*/
constructor(
opt_block: BlockSvg, opt_isOpen?: boolean, opt_bubbleType?: string) {
opt_block: BlockSvg, opt_isOpen?: boolean, opt_bubbleType?: string) {
const workspaceId = opt_block ? opt_block.workspace.id : undefined;
super(workspaceId);
this.blockId = opt_block ? opt_block.id : null;
+4 -4
View File
@@ -13,10 +13,10 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -39,8 +39,8 @@ export class Click extends UiBase {
* Undefined for a blank event.
*/
constructor(
opt_block?: Block | null, opt_workspaceId?: string | null,
opt_targetType?: string) {
opt_block?: Block|null, opt_workspaceId?: string|null,
opt_targetType?: string) {
let workspaceId = opt_block ? opt_block.workspace.id : opt_workspaceId;
if (workspaceId === null) {
workspaceId = undefined;
+6 -6
View File
@@ -14,14 +14,14 @@
import * as utilsXml from '../utils/xml.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceComment } from '../workspace_comment.js';
import {WorkspaceComment} from '../workspace_comment.js';
import * as Xml from '../xml.js';
import { Abstract as AbstractEvent } from './events_abstract.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
/* eslint-disable-next-line no-unused-vars */
import { CommentCreate } from './events_comment_create.js';
import {CommentCreate} from './events_comment_create.js';
/* eslint-disable-next-line no-unused-vars */
import { CommentDelete } from './events_comment_delete.js';
import {CommentDelete} from './events_comment_delete.js';
import * as eventUtils from './utils.js';
@@ -87,7 +87,7 @@ export class CommentBase extends AbstractEvent {
* @param create if True then Create, if False then Delete
*/
static CommentCreateDeleteHelper(
event: CommentCreate | CommentDelete, create: boolean) {
event: CommentCreate|CommentDelete, create: boolean) {
const workspace = event.getEventWorkspace_();
if (create) {
const xmlElement = utilsXml.createElement('xml');
@@ -100,7 +100,7 @@ export class CommentBase extends AbstractEvent {
} else {
// Only complain about root-level block.
console.warn(
'Can\'t uncreate non-existent comment: ' + event.commentId);
'Can\'t uncreate non-existent comment: ' + event.commentId);
}
}
}
+9 -9
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceComment } from '../workspace_comment.js';
import {WorkspaceComment} from '../workspace_comment.js';
import { CommentBase } from './events_comment_base.js';
import {CommentBase} from './events_comment_base.js';
import * as eventUtils from './utils.js';
@@ -39,21 +39,21 @@ export class CommentChange extends CommentBase {
* @param opt_newContents New contents of the comment.
*/
constructor(
opt_comment?: WorkspaceComment, opt_oldContents?: string,
opt_newContents?: string) {
opt_comment?: WorkspaceComment, opt_oldContents?: string,
opt_newContents?: string) {
super(opt_comment);
/** Type of this event. */
this.type = eventUtils.COMMENT_CHANGE;
if (!opt_comment) {
return; // Blank event to be populated by fromJson.
return; // Blank event to be populated by fromJson.
}
this.oldContents_ =
typeof opt_oldContents === 'undefined' ? '' : opt_oldContents;
typeof opt_oldContents === 'undefined' ? '' : opt_oldContents;
this.newContents_ =
typeof opt_newContents === 'undefined' ? '' : opt_newContents;
typeof opt_newContents === 'undefined' ? '' : opt_newContents;
}
/**
@@ -103,4 +103,4 @@ export class CommentChange extends CommentBase {
}
registry.register(
registry.Type.EVENT, eventUtils.COMMENT_CHANGE, CommentChange);
registry.Type.EVENT, eventUtils.COMMENT_CHANGE, CommentChange);
+3 -3
View File
@@ -14,10 +14,10 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceComment } from '../workspace_comment.js';
import {WorkspaceComment} from '../workspace_comment.js';
import * as Xml from '../xml.js';
import { CommentBase } from './events_comment_base.js';
import {CommentBase} from './events_comment_base.js';
import * as eventUtils from './utils.js';
@@ -77,4 +77,4 @@ export class CommentCreate extends CommentBase {
}
registry.register(
registry.Type.EVENT, eventUtils.COMMENT_CREATE, CommentCreate);
registry.Type.EVENT, eventUtils.COMMENT_CREATE, CommentCreate);
+3 -3
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceComment } from '../workspace_comment.js';
import {WorkspaceComment} from '../workspace_comment.js';
import { CommentBase } from './events_comment_base.js';
import {CommentBase} from './events_comment_base.js';
import * as eventUtils from './utils.js';
@@ -72,4 +72,4 @@ export class CommentDelete extends CommentBase {
}
registry.register(
registry.Type.EVENT, eventUtils.COMMENT_DELETE, CommentDelete);
registry.Type.EVENT, eventUtils.COMMENT_DELETE, CommentDelete);
+7 -7
View File
@@ -13,11 +13,11 @@
*/
import * as registry from '../registry.js';
import { Coordinate } from '../utils/coordinate.js';
import {Coordinate} from '../utils/coordinate.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceComment } from '../workspace_comment.js';
import {WorkspaceComment} from '../workspace_comment.js';
import { CommentBase } from './events_comment_base.js';
import {CommentBase} from './events_comment_base.js';
import * as eventUtils from './utils.js';
@@ -69,8 +69,8 @@ export class CommentMove extends CommentBase {
recordNew() {
if (!this.comment_) {
throw Error(
'Tried to record the new position of a comment on the ' +
'same event twice.');
'Tried to record the new position of a comment on the ' +
'same event twice.');
}
this.newCoordinate_ = this.comment_.getXY();
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -96,11 +96,11 @@ export class CommentMove extends CommentBase {
const json = super.toJson();
if (this.oldCoordinate_) {
json['oldCoordinate'] = Math.round(this.oldCoordinate_.x) + ',' +
Math.round(this.oldCoordinate_.y);
Math.round(this.oldCoordinate_.y);
}
if (this.newCoordinate_) {
json['newCoordinate'] = Math.round(this.newCoordinate_.x) + ',' +
Math.round(this.newCoordinate_.y);
Math.round(this.newCoordinate_.y);
}
return json;
}
+8 -8
View File
@@ -13,13 +13,13 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import { ASTNode } from '../keyboard_nav/ast_node.js';
import {Block} from '../block.js';
import {ASTNode} from '../keyboard_nav/ast_node.js';
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from '../workspace.js';
import {Workspace} from '../workspace.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -28,8 +28,8 @@ import * as eventUtils from './utils.js';
* @alias Blockly.Events.MarkerMove
*/
export class MarkerMove extends UiBase {
blockId: string | null;
oldNode?: ASTNode | null;
blockId: string|null;
oldNode?: ASTNode|null;
newNode?: ASTNode;
isCursor?: boolean;
override type: string;
@@ -45,8 +45,8 @@ export class MarkerMove extends UiBase {
* Undefined for a blank event.
*/
constructor(
opt_block?: Block | null, isCursor?: boolean, opt_oldNode?: ASTNode | null,
opt_newNode?: ASTNode) {
opt_block?: Block|null, isCursor?: boolean, opt_oldNode?: ASTNode|null,
opt_newNode?: ASTNode) {
let workspaceId = opt_block ? opt_block.workspace.id : undefined;
if (opt_newNode && opt_newNode.getType() === ASTNode.types.WORKSPACE) {
workspaceId = (opt_newNode.getLocation() as Workspace).id;
+5 -5
View File
@@ -14,7 +14,7 @@
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -23,8 +23,8 @@ import * as eventUtils from './utils.js';
* @alias Blockly.Events.Selected
*/
export class Selected extends UiBase {
oldElementId?: string | null;
newElementId?: string | null;
oldElementId?: string|null;
newElementId?: string|null;
override type: string;
/**
@@ -36,8 +36,8 @@ export class Selected extends UiBase {
* Null if no element previously selected. Undefined for a blank event.
*/
constructor(
opt_oldElementId?: string | null, opt_newElementId?: string | null,
opt_workspaceId?: string) {
opt_oldElementId?: string|null, opt_newElementId?: string|null,
opt_workspaceId?: string) {
super(opt_workspaceId);
/** The id of the last selected element. */
+1 -1
View File
@@ -14,7 +14,7 @@
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
+6 -6
View File
@@ -16,7 +16,7 @@
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -25,8 +25,8 @@ import * as eventUtils from './utils.js';
* @alias Blockly.Events.ToolboxItemSelect
*/
export class ToolboxItemSelect extends UiBase {
oldItem?: string | null;
newItem?: string | null;
oldItem?: string|null;
newItem?: string|null;
override type: string;
/**
@@ -38,8 +38,8 @@ export class ToolboxItemSelect extends UiBase {
* Undefined for a blank event.
*/
constructor(
opt_oldItem?: string | null, opt_newItem?: string | null,
opt_workspaceId?: string) {
opt_oldItem?: string|null, opt_newItem?: string|null,
opt_workspaceId?: string) {
super(opt_workspaceId);
/** The previously selected toolbox item. */
@@ -75,4 +75,4 @@ export class ToolboxItemSelect extends UiBase {
}
registry.register(
registry.Type.EVENT, eventUtils.TOOLBOX_ITEM_SELECT, ToolboxItemSelect);
registry.Type.EVENT, eventUtils.TOOLBOX_ITEM_SELECT, ToolboxItemSelect);
+1 -1
View File
@@ -14,7 +14,7 @@
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
+4 -4
View File
@@ -17,10 +17,10 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -44,8 +44,8 @@ export class Ui extends UiBase {
* @param opt_newValue New value of element.
*/
constructor(
opt_block?: Block | null, opt_element?: string,
opt_oldValue?: AnyDuringMigration, opt_newValue?: AnyDuringMigration) {
opt_block?: Block|null, opt_element?: string,
opt_oldValue?: AnyDuringMigration, opt_newValue?: AnyDuringMigration) {
const workspaceId = opt_block ? opt_block.workspace.id : undefined;
super(workspaceId);
+1 -1
View File
@@ -15,7 +15,7 @@
* Blockly's editor.
* @class
*/
import { Abstract as AbstractEvent } from './events_abstract.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
/**
+2 -2
View File
@@ -13,9 +13,9 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { VariableModel } from '../variable_model.js';
import {VariableModel} from '../variable_model.js';
import { Abstract as AbstractEvent } from './events_abstract.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
/**
+2 -2
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { VariableModel } from '../variable_model.js';
import {VariableModel} from '../variable_model.js';
import { VarBase } from './events_var_base.js';
import {VarBase} from './events_var_base.js';
import * as eventUtils from './utils.js';
+2 -2
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { VariableModel } from '../variable_model.js';
import {VariableModel} from '../variable_model.js';
import { VarBase } from './events_var_base.js';
import {VarBase} from './events_var_base.js';
import * as eventUtils from './utils.js';
+2 -2
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { VariableModel } from '../variable_model.js';
import {VariableModel} from '../variable_model.js';
import { VarBase } from './events_var_base.js';
import {VarBase} from './events_var_base.js';
import * as eventUtils from './utils.js';
+4 -4
View File
@@ -14,7 +14,7 @@
import * as registry from '../registry.js';
import { UiBase } from './events_ui_base.js';
import {UiBase} from './events_ui_base.js';
import * as eventUtils from './utils.js';
@@ -41,8 +41,8 @@ export class ViewportChange extends UiBase {
* event.
*/
constructor(
opt_top?: number, opt_left?: number, opt_scale?: number,
opt_workspaceId?: string, opt_oldScale?: number) {
opt_top?: number, opt_left?: number, opt_scale?: number,
opt_workspaceId?: string, opt_oldScale?: number) {
super(opt_workspaceId);
/**
@@ -94,4 +94,4 @@ export class ViewportChange extends UiBase {
}
registry.register(
registry.Type.EVENT, eventUtils.VIEWPORT_CHANGE, ViewportChange);
registry.Type.EVENT, eventUtils.VIEWPORT_CHANGE, ViewportChange);
+25 -25
View File
@@ -17,28 +17,28 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from '../block.js';
import {Block} from '../block.js';
import * as registry from '../registry.js';
import * as idGenerator from '../utils/idgenerator.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from '../workspace.js';
import {Workspace} from '../workspace.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from '../workspace_svg.js';
import {WorkspaceSvg} from '../workspace_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { Abstract } from './events_abstract.js';
import {Abstract} from './events_abstract.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockChange } from './events_block_change.js';
import {BlockChange} from './events_block_change.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockCreate } from './events_block_create.js';
import {BlockCreate} from './events_block_create.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockMove } from './events_block_move.js';
import {BlockMove} from './events_block_move.js';
/* eslint-disable-next-line no-unused-vars */
import { CommentCreate } from './events_comment_create.js';
import {CommentCreate} from './events_comment_create.js';
/* eslint-disable-next-line no-unused-vars */
import { CommentMove } from './events_comment_move.js';
import {CommentMove} from './events_comment_move.js';
/* eslint-disable-next-line no-unused-vars */
import { ViewportChange } from './events_viewport.js';
import {ViewportChange} from './events_viewport.js';
/** Group ID for new events. Grouped events are indivisible. */
@@ -232,7 +232,7 @@ export const FINISHED_LOADING = 'finished_loading';
* appear connected.
* @alias Blockly.Events.utils.BumpEvent
*/
export type BumpEvent = BlockCreate | BlockMove | CommentCreate | CommentMove;
export type BumpEvent = BlockCreate|BlockMove|CommentCreate|CommentMove;
/**
* List of events that cause objects to be bumped back into the visible
@@ -243,7 +243,7 @@ export type BumpEvent = BlockCreate | BlockMove | CommentCreate | CommentMove;
* @alias Blockly.Events.utils.BUMP_EVENTS
*/
export const BUMP_EVENTS: string[] =
[BLOCK_CREATE, BLOCK_MOVE, COMMENT_CREATE, COMMENT_MOVE];
[BLOCK_CREATE, BLOCK_MOVE, COMMENT_CREATE, COMMENT_MOVE];
/** List of events queued for firing. */
const FIRE_QUEUE: Abstract[] = [];
@@ -310,7 +310,7 @@ export function filter(queueIn: Abstract[], forward: boolean): Abstract[] {
// Each item in the hash table has the event and the index of that event
// in the input array. This lets us make sure we only merge adjacent
// move events.
hash[key] = { event, index: i };
hash[key] = {event, index: i};
mergedQueue.push(event);
} else if (event.type === MOVE && lastEntry.index === i - 1) {
const moveEvent = event as BlockMove;
@@ -320,9 +320,9 @@ export function filter(queueIn: Abstract[], forward: boolean): Abstract[] {
lastEvent.newCoordinate = moveEvent.newCoordinate;
lastEntry.index = i;
} else if (
event.type === CHANGE &&
(event as BlockChange).element === lastEvent.element &&
(event as BlockChange).name === lastEvent.name) {
event.type === CHANGE &&
(event as BlockChange).element === lastEvent.element &&
(event as BlockChange).name === lastEvent.name) {
const changeEvent = event as BlockChange;
// Merge change events.
lastEvent.newValue = changeEvent.newValue;
@@ -339,13 +339,13 @@ export function filter(queueIn: Abstract[], forward: boolean): Abstract[] {
{
// Collision: newer events should merge into this event to maintain
// order.
hash[key] = { event, index: i };
hash[key] = {event, index: i};
mergedQueue.push(event);
}
}
}
// Filter out any events that have become null due to merging.
queue = mergedQueue.filter(function (e) {
queue = mergedQueue.filter(function(e) {
return !e.isNull();
});
if (!forward) {
@@ -358,7 +358,7 @@ export function filter(queueIn: Abstract[], forward: boolean): Abstract[] {
// AnyDuringMigration because: Property 'element' does not exist on type
// 'Abstract'.
if (event.type === CHANGE &&
(event as AnyDuringMigration).element === 'mutation') {
(event as AnyDuringMigration).element === 'mutation') {
queue.unshift(queue.splice(i, 1)[0]);
}
}
@@ -417,7 +417,7 @@ export function getGroup(): string {
* String to set group explicitly.
* @alias Blockly.Events.utils.setGroup
*/
export function setGroup(state: boolean | string) {
export function setGroup(state: boolean|string) {
if (typeof state === 'boolean') {
group = state ? idGenerator.genUid() : '';
} else {
@@ -449,7 +449,7 @@ export function getDescendantIds(block: Block): string[] {
* @alias Blockly.Events.utils.fromJson
*/
export function fromJson(
json: AnyDuringMigration, workspace: Workspace): Abstract {
json: AnyDuringMigration, workspace: Workspace): Abstract {
const eventClass = get(json['type']);
if (!eventClass) {
throw Error('Unknown event type.');
@@ -467,7 +467,7 @@ export function fromJson(
* @alias Blockly.Events.utils.get
*/
export function get(eventType: string):
(new (...p1: AnyDuringMigration[]) => Abstract) | null {
(new (...p1: AnyDuringMigration[]) => Abstract)|null {
return registry.getClass(registry.Type.EVENT, eventType);
}
@@ -486,7 +486,7 @@ export function disableOrphans(event: Abstract) {
return;
}
const eventWorkspace =
Workspace.getById(blockEvent.workspaceId) as WorkspaceSvg;
Workspace.getById(blockEvent.workspaceId) as WorkspaceSvg;
let block = eventWorkspace.getBlockById(blockEvent.blockId);
if (block) {
// Changing blocks as part of this event shouldn't be undoable.
@@ -500,8 +500,8 @@ export function disableOrphans(event: Abstract) {
child.setEnabled(true);
}
} else if (
(block.outputConnection || block.previousConnection) &&
!eventWorkspace.isDragging()) {
(block.outputConnection || block.previousConnection) &&
!eventWorkspace.isDragging()) {
do {
block.setEnabled(false);
block = block.getNextBlock();
+3 -3
View File
@@ -14,9 +14,9 @@
import * as registry from '../registry.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from '../workspace.js';
import {Workspace} from '../workspace.js';
import { Abstract as AbstractEvent } from './events_abstract.js';
import {Abstract as AbstractEvent} from './events_abstract.js';
import * as eventUtils from './utils.js';
@@ -81,4 +81,4 @@ export class FinishedLoading extends AbstractEvent {
}
registry.register(
registry.Type.EVENT, eventUtils.FINISHED_LOADING, FinishedLoading);
registry.Type.EVENT, eventUtils.FINISHED_LOADING, FinishedLoading);
+44 -44
View File
@@ -23,16 +23,16 @@
import './mutator';
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import { BlockSvg } from './block_svg.js';
import { FieldDropdown } from './field_dropdown.js';
import { Mutator } from './mutator.js';
import {Block} from './block.js';
import {BlockSvg} from './block_svg.js';
import {FieldDropdown} from './field_dropdown.js';
import {Mutator} from './mutator.js';
import * as parsing from './utils/parsing.js';
/** The set of all registered extensions, keyed by extension name/id. */
const allExtensions = Object.create(null);
export const TEST_ONLY = { allExtensions };
export const TEST_ONLY = {allExtensions};
/**
* Registers a new extension function. Extensions are functions that help
@@ -70,7 +70,7 @@ export function registerMixin(name: string, mixinObj: AnyDuringMigration) {
if (!mixinObj || typeof mixinObj !== 'object') {
throw Error('Error: Mixin "' + name + '" must be a object');
}
register(name, function (this: Block) {
register(name, function(this: Block) {
this.mixin(mixinObj);
});
}
@@ -89,8 +89,8 @@ export function registerMixin(name: string, mixinObj: AnyDuringMigration) {
* @alias Blockly.Extensions.registerMutator
*/
export function registerMutator(
name: string, mixinObj: AnyDuringMigration,
opt_helperFn?: () => AnyDuringMigration, opt_blockList?: string[]) {
name: string, mixinObj: AnyDuringMigration,
opt_helperFn?: () => AnyDuringMigration, opt_blockList?: string[]) {
const errorPrefix = 'Error when registering mutator "' + name + '": ';
checkHasMutatorProperties(errorPrefix, mixinObj);
@@ -101,7 +101,7 @@ export function registerMutator(
}
// Sanity checks passed.
register(name, function (this: Block) {
register(name, function(this: Block) {
if (hasMutatorDialog) {
this.setMutator(new Mutator(this as BlockSvg, opt_blockList || []));
}
@@ -124,7 +124,7 @@ export function unregister(name: string) {
delete allExtensions[name];
} else {
console.warn(
'No extension mapping for name "' + name + '" found to unregister');
'No extension mapping for name "' + name + '" found to unregister');
}
}
@@ -168,10 +168,10 @@ export function apply(name: string, block: Block, isMutator: boolean) {
checkHasMutatorProperties(errorPrefix, block);
} else {
if (!mutatorPropertiesMatch(
mutatorProperties as AnyDuringMigration[], block)) {
mutatorProperties as AnyDuringMigration[], block)) {
throw Error(
'Error when applying extension "' + name + '": ' +
'mutation properties changed when applying a non-mutator extension.');
'Error when applying extension "' + name + '": ' +
'mutation properties changed when applying a non-mutator extension.');
}
}
}
@@ -188,9 +188,9 @@ function checkNoMutatorProperties(mutationName: string, block: Block) {
const properties = getMutatorProperties(block);
if (properties.length) {
throw Error(
'Error: tried to apply mutation "' + mutationName +
'" to a block that already has mutator functions.' +
' Block id: ' + block.id);
'Error: tried to apply mutation "' + mutationName +
'" to a block that already has mutator functions.' +
' Block id: ' + block.id);
}
}
@@ -205,10 +205,10 @@ function checkNoMutatorProperties(mutationName: string, block: Block) {
* actually a function.
*/
function checkXmlHooks(
object: AnyDuringMigration, errorPrefix: string): boolean {
object: AnyDuringMigration, errorPrefix: string): boolean {
return checkHasFunctionPair(
object.mutationToDom, object.domToMutation,
errorPrefix + ' mutationToDom/domToMutation');
object.mutationToDom, object.domToMutation,
errorPrefix + ' mutationToDom/domToMutation');
}
/**
* Checks if the given object has both the 'saveExtraState' and 'loadExtraState'
@@ -221,10 +221,10 @@ function checkXmlHooks(
* actually a function.
*/
function checkJsonHooks(
object: AnyDuringMigration, errorPrefix: string): boolean {
object: AnyDuringMigration, errorPrefix: string): boolean {
return checkHasFunctionPair(
object.saveExtraState, object.loadExtraState,
errorPrefix + ' saveExtraState/loadExtraState');
object.saveExtraState, object.loadExtraState,
errorPrefix + ' saveExtraState/loadExtraState');
}
/**
@@ -237,9 +237,9 @@ function checkJsonHooks(
* actually a function.
*/
function checkMutatorDialog(
object: AnyDuringMigration, errorPrefix: string): boolean {
object: AnyDuringMigration, errorPrefix: string): boolean {
return checkHasFunctionPair(
object.compose, object.decompose, errorPrefix + ' compose/decompose');
object.compose, object.decompose, errorPrefix + ' compose/decompose');
}
/**
@@ -254,8 +254,8 @@ function checkMutatorDialog(
* actually a function.
*/
function checkHasFunctionPair(
func1: AnyDuringMigration, func2: AnyDuringMigration,
errorPrefix: string): boolean {
func1: AnyDuringMigration, func2: AnyDuringMigration,
errorPrefix: string): boolean {
if (func1 && func2) {
if (typeof func1 !== 'function' || typeof func2 !== 'function') {
throw Error(errorPrefix + ' must be a function');
@@ -273,13 +273,13 @@ function checkHasFunctionPair(
* @param object The object to inspect.
*/
function checkHasMutatorProperties(
errorPrefix: string, object: AnyDuringMigration) {
errorPrefix: string, object: AnyDuringMigration) {
const hasXmlHooks = checkXmlHooks(object, errorPrefix);
const hasJsonHooks = checkJsonHooks(object, errorPrefix);
if (!hasXmlHooks && !hasJsonHooks) {
throw Error(
errorPrefix +
'Mutations must contain either XML hooks, or JSON hooks, or both');
errorPrefix +
'Mutations must contain either XML hooks, or JSON hooks, or both');
}
// A block with a mutator isn't required to have a mutation dialog, but
// it should still have both or neither of compose and decompose.
@@ -326,7 +326,7 @@ function getMutatorProperties(block: Block): AnyDuringMigration[] {
* @return True if the property lists match.
*/
function mutatorPropertiesMatch(
oldProperties: AnyDuringMigration[], block: Block): boolean {
oldProperties: AnyDuringMigration[], block: Block): boolean {
const newProperties = getMutatorProperties(block);
if (newProperties.length !== oldProperties.length) {
return false;
@@ -353,7 +353,7 @@ export function runAfterPageLoad(fn: () => AnyDuringMigration) {
fn();
} else {
// Poll readyState.
const readyStateCheckInterval = setInterval(function () {
const readyStateCheckInterval = setInterval(function() {
if (document.readyState === 'complete') {
clearInterval(readyStateCheckInterval);
fn();
@@ -382,7 +382,7 @@ export function runAfterPageLoad(fn: () => AnyDuringMigration) {
* @alias Blockly.Extensions.buildTooltipForDropdown
*/
export function buildTooltipForDropdown(
dropdownName: string, lookupTable: { [key: string]: string }): Function {
dropdownName: string, lookupTable: {[key: string]: string}): Function {
// List of block types already validated, to minimize duplicate warnings.
const blockTypesChecked: AnyDuringMigration[] = [];
@@ -392,7 +392,7 @@ export function buildTooltipForDropdown(
// of document object, in which case skip the validation.
if (typeof document === 'object') {
// Relies on document.readyState
runAfterPageLoad(function () {
runAfterPageLoad(function() {
for (const key in lookupTable) {
// Will print warnings if reference is missing.
parsing.checkMessageReferences(lookupTable[key]);
@@ -407,14 +407,14 @@ export function buildTooltipForDropdown(
blockTypesChecked.push(this.type);
}
this.setTooltip(function (this: Block) {
this.setTooltip(function(this: Block) {
const value = String(this.getFieldValue(dropdownName));
let tooltip = lookupTable[value];
if (tooltip === null) {
if (blockTypesChecked.indexOf(this.type) === -1) {
// Warn for missing values on generated tooltips.
let warning = 'No tooltip mapping for value ' + value + ' of field ' +
dropdownName;
dropdownName;
if (this.type !== null) {
warning += ' of block type ' + this.type;
}
@@ -437,7 +437,7 @@ export function buildTooltipForDropdown(
* @param lookupTable The string lookup table
*/
function checkDropdownOptionsInTable(
block: Block, dropdownName: string, lookupTable: { [key: string]: string }) {
block: Block, dropdownName: string, lookupTable: {[key: string]: string}) {
// Validate all dropdown options have values.
const dropdown = block.getField(dropdownName);
if (dropdown instanceof FieldDropdown && !dropdown.isOptionListDynamic()) {
@@ -447,8 +447,8 @@ function checkDropdownOptionsInTable(
// label, then value
if (lookupTable[optionKey] === null) {
console.warn(
'No tooltip mapping for value ' + optionKey + ' of field ' +
dropdownName + ' of block type ' + block.type);
'No tooltip mapping for value ' + optionKey + ' of field ' +
dropdownName + ' of block type ' + block.type);
}
}
}
@@ -465,14 +465,14 @@ function checkDropdownOptionsInTable(
* @alias Blockly.Extensions.buildTooltipWithFieldText
*/
export function buildTooltipWithFieldText(
msgTemplate: string, fieldName: string): Function {
msgTemplate: string, fieldName: string): Function {
// Check the tooltip string messages for invalid references.
// Wait for load, in case Blockly.Msg is not yet populated.
// runAfterPageLoad() does not run in a Node.js environment due to lack
// of document object, in which case skip the validation.
if (typeof document === 'object') {
// Relies on document.readyState
runAfterPageLoad(function () {
runAfterPageLoad(function() {
// Will print warnings if reference is missing.
parsing.checkMessageReferences(msgTemplate);
});
@@ -480,10 +480,10 @@ export function buildTooltipWithFieldText(
/** The actual extension. */
function extensionFn(this: Block) {
this.setTooltip(function (this: Block) {
this.setTooltip(function(this: Block) {
const field = this.getField(fieldName);
return parsing.replaceMessageReferences(msgTemplate)
.replace('%1', field ? field.getText() : '');
.replace('%1', field ? field.getText() : '');
}.bind(this));
}
return extensionFn;
@@ -497,10 +497,10 @@ export function buildTooltipWithFieldText(
*/
function extensionParentTooltip(this: Block) {
const tooltipWhenNotConnected = this.tooltip;
this.setTooltip(function (this: Block) {
this.setTooltip(function(this: Block) {
const parent = this.getParent();
return parent && parent.getInputsInline() && parent.tooltip ||
tooltipWhenNotConnected;
tooltipWhenNotConnected;
}.bind(this));
}
register('parent_tooltip_when_inline', extensionParentTooltip);
+82 -82
View File
@@ -26,41 +26,41 @@ import './events/events_block_change';
import './gesture';
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import {Block} from './block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as dropDownDiv from './dropdowndiv.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { Input } from './input.js';
import {Input} from './input.js';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocationSvg } from './interfaces/i_ast_node_location_svg.js';
import {IASTNodeLocationSvg} from './interfaces/i_ast_node_location_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocationWithBlock } from './interfaces/i_ast_node_location_with_block.js';
import {IASTNodeLocationWithBlock} from './interfaces/i_ast_node_location_with_block.js';
/* eslint-disable-next-line no-unused-vars */
import { IKeyboardAccessible } from './interfaces/i_keyboard_accessible.js';
import {IKeyboardAccessible} from './interfaces/i_keyboard_accessible.js';
/* eslint-disable-next-line no-unused-vars */
import { IRegistrable } from './interfaces/i_registrable.js';
import { MarkerManager } from './marker_manager.js';
import {IRegistrable} from './interfaces/i_registrable.js';
import {MarkerManager} from './marker_manager.js';
/* eslint-disable-next-line no-unused-vars */
import { ConstantProvider } from './renderers/common/constants.js';
import { KeyboardShortcut } from './shortcut_registry.js';
import {ConstantProvider} from './renderers/common/constants.js';
import {KeyboardShortcut} from './shortcut_registry.js';
import * as Tooltip from './tooltip.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as parsing from './utils/parsing.js';
import { Rect } from './utils/rect.js';
import { Sentinel } from './utils/sentinel.js';
import { Size } from './utils/size.js';
import {Rect} from './utils/rect.js';
import {Sentinel} from './utils/sentinel.js';
import {Size} from './utils/size.js';
import * as style from './utils/style.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
import * as utilsXml from './utils/xml.js';
import * as WidgetDiv from './widgetdiv.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
import * as Xml from './xml.js';
@@ -69,8 +69,8 @@ import * as Xml from './xml.js';
* @alias Blockly.Field
*/
export abstract class Field implements IASTNodeLocationSvg,
IASTNodeLocationWithBlock,
IKeyboardAccessible, IRegistrable {
IASTNodeLocationWithBlock,
IKeyboardAccessible, IRegistrable {
/** The default value for this field. */
protected DEFAULT_VALUE: any = null;
@@ -100,7 +100,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* Used to cache the field's tooltip value if setTooltip is called when the
* field is not yet initialized. Is *not* guaranteed to be accurate.
*/
private tooltip_: Tooltip.TipInfo | null = null;
private tooltip_: Tooltip.TipInfo|null = null;
protected size_: Size;
/**
@@ -139,7 +139,7 @@ export abstract class Field implements IASTNodeLocationSvg,
protected textContent_: Text = null as AnyDuringMigration;
/** Mouse down event listener data. */
private mouseDownWrapper_: browserEvents.Data | null = null;
private mouseDownWrapper_: browserEvents.Data|null = null;
/** Constants associated with the source block's renderer. */
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -173,10 +173,10 @@ export abstract class Field implements IASTNodeLocationSvg,
protected clickTarget_: Element = null as AnyDuringMigration;
/** The prefix field. */
prefixField: string | null = null;
prefixField: string|null = null;
/** The suffix field. */
suffixField: string | null = null;
suffixField: string|null = null;
/**
* Editable fields usually show some sort of UI indicating they are
@@ -207,8 +207,8 @@ export abstract class Field implements IASTNodeLocationSvg,
* this parameter supports.
*/
constructor(
value: AnyDuringMigration, opt_validator?: Function | null,
opt_config?: AnyDuringMigration) {
value: AnyDuringMigration, opt_validator?: Function|null,
opt_config?: AnyDuringMigration) {
/**
* A generic value possessed by the field.
* Should generally be non-null, only null when the field is created.
@@ -262,12 +262,12 @@ export abstract class Field implements IASTNodeLocationSvg,
* Get the renderer constant provider.
* @return The renderer constant provider.
*/
getConstants(): ConstantProvider | null {
getConstants(): ConstantProvider|null {
if (!this.constants_ && this.sourceBlock_ && this.sourceBlock_.workspace &&
this.sourceBlock_.workspace.rendered) {
this.sourceBlock_.workspace.rendered) {
this.constants_ = (this.sourceBlock_.workspace as WorkspaceSvg)
.getRenderer()
.getConstants();
.getRenderer()
.getConstants();
}
return this.constants_;
}
@@ -322,16 +322,16 @@ export abstract class Field implements IASTNodeLocationSvg,
*/
protected createBorderRect_() {
this.borderRect_ = dom.createSvgElement(
Svg.RECT, {
'rx': this.getConstants()!.FIELD_BORDER_RECT_RADIUS,
'ry': this.getConstants()!.FIELD_BORDER_RECT_RADIUS,
'x': 0,
'y': 0,
'height': this.size_.height,
'width': this.size_.width,
'class': 'blocklyFieldRect',
},
this.fieldGroup_);
Svg.RECT, {
'rx': this.getConstants()!.FIELD_BORDER_RECT_RADIUS,
'ry': this.getConstants()!.FIELD_BORDER_RECT_RADIUS,
'x': 0,
'y': 0,
'height': this.size_.height,
'width': this.size_.width,
'class': 'blocklyFieldRect',
},
this.fieldGroup_);
}
/**
@@ -341,10 +341,10 @@ export abstract class Field implements IASTNodeLocationSvg,
*/
protected createTextElement_() {
this.textElement_ = dom.createSvgElement(
Svg.TEXT, {
'class': 'blocklyText',
},
this.fieldGroup_);
Svg.TEXT, {
'class': 'blocklyText',
},
this.fieldGroup_);
if (this.getConstants()!.FIELD_TEXT_BASELINE_CENTER) {
this.textElement_.setAttribute('dominant-baseline', 'central');
}
@@ -359,7 +359,7 @@ export abstract class Field implements IASTNodeLocationSvg,
protected bindEvents_() {
Tooltip.bindMouseEvents(this.getClickTarget_());
this.mouseDownWrapper_ = browserEvents.conditionalBind(
this.getClickTarget_(), 'mousedown', this, this.onMouseDown_);
this.getClickTarget_(), 'mousedown', this, this.onMouseDown_);
}
/**
@@ -418,14 +418,14 @@ export abstract class Field implements IASTNodeLocationSvg,
* Used to see if `this` has overridden any relevant hooks.
* @return The stringified version of the XML state, or null.
*/
protected saveLegacyState(callingClass: AnyDuringMigration): string | null {
protected saveLegacyState(callingClass: AnyDuringMigration): string|null {
if (callingClass.prototype.saveState === this.saveState &&
callingClass.prototype.toXml !== this.toXml) {
callingClass.prototype.toXml !== this.toXml) {
const elem = utilsXml.createElement('field');
elem.setAttribute('name', this.name || '');
const text = Xml.domToText(this.toXml(elem));
return text.replace(
' xmlns="https://developers.google.com/blockly/xml"', '');
' xmlns="https://developers.google.com/blockly/xml"', '');
}
// Either they called this on purpose from their saveState, or they have
// no implementations of either hook. Just do our thing.
@@ -441,9 +441,9 @@ export abstract class Field implements IASTNodeLocationSvg,
* @return Whether the state was applied or not.
*/
loadLegacyState(callingClass: AnyDuringMigration, state: AnyDuringMigration):
boolean {
boolean {
if (callingClass.prototype.loadState === this.loadState &&
callingClass.prototype.fromXml !== this.fromXml) {
callingClass.prototype.fromXml !== this.fromXml) {
this.fromXml(Xml.textToDom(state as string));
return true;
}
@@ -511,8 +511,8 @@ export abstract class Field implements IASTNodeLocationSvg,
*/
isClickable(): boolean {
return this.enabled_ && !!this.sourceBlock_ &&
this.sourceBlock_.isEditable() &&
this.showEditor_ !== Field.prototype.showEditor_;
this.sourceBlock_.isEditable() &&
this.showEditor_ !== Field.prototype.showEditor_;
}
/**
@@ -524,7 +524,7 @@ export abstract class Field implements IASTNodeLocationSvg,
*/
isCurrentlyEditable(): boolean {
return this.enabled_ && this.EDITABLE && !!this.sourceBlock_ &&
this.sourceBlock_.isEditable();
this.sourceBlock_.isEditable();
}
/**
@@ -539,9 +539,9 @@ export abstract class Field implements IASTNodeLocationSvg,
isSerializable = true;
} else if (this.EDITABLE) {
console.warn(
'Detected an editable field that was not serializable.' +
' Please define SERIALIZABLE property as true on all editable custom' +
' fields. Proceeding with serialization.');
'Detected an editable field that was not serializable.' +
' Please define SERIALIZABLE property as true on all editable custom' +
' fields. Proceeding with serialization.');
isSerializable = true;
}
}
@@ -595,7 +595,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* Gets the validation function for editable fields, or null if not set.
* @return Validation function, or null.
*/
getValidator(): Function | null {
getValidator(): Function|null {
return this.validator_;
}
@@ -657,16 +657,16 @@ export abstract class Field implements IASTNodeLocationSvg,
protected updateSize_(opt_margin?: number) {
const constants = this.getConstants();
const xOffset = opt_margin !== undefined ? opt_margin :
this.borderRect_ ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING :
0;
this.borderRect_ ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING :
0;
let totalWidth = xOffset * 2;
let totalHeight = constants!.FIELD_TEXT_HEIGHT;
let contentWidth = 0;
if (this.textElement_) {
contentWidth = dom.getFastTextWidth(
this.textElement_, constants!.FIELD_TEXT_FONTSIZE,
constants!.FIELD_TEXT_FONTWEIGHT, constants!.FIELD_TEXT_FONTFAMILY);
this.textElement_, constants!.FIELD_TEXT_FONTSIZE,
constants!.FIELD_TEXT_FONTWEIGHT, constants!.FIELD_TEXT_FONTFAMILY);
totalWidth += contentWidth;
}
if (this.borderRect_) {
@@ -696,17 +696,17 @@ export abstract class Field implements IASTNodeLocationSvg,
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.textElement_.setAttribute(
'x',
(this.sourceBlock_.RTL ? this.size_.width - contentWidth - xOffset :
xOffset) as AnyDuringMigration);
'x',
(this.sourceBlock_.RTL ? this.size_.width - contentWidth - xOffset :
xOffset) as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.textElement_.setAttribute(
'y',
(constants!.FIELD_TEXT_BASELINE_CENTER ?
halfHeight :
halfHeight - constants!.FIELD_TEXT_HEIGHT / 2 +
constants!.FIELD_TEXT_BASELINE) as AnyDuringMigration);
'y',
(constants!.FIELD_TEXT_BASELINE_CENTER ?
halfHeight :
halfHeight - constants!.FIELD_TEXT_HEIGHT / 2 +
constants!.FIELD_TEXT_BASELINE) as AnyDuringMigration);
}
/** Position a field's border rect after a size change. */
@@ -717,21 +717,21 @@ export abstract class Field implements IASTNodeLocationSvg,
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.borderRect_.setAttribute(
'width', this.size_.width as AnyDuringMigration);
'width', this.size_.width as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.borderRect_.setAttribute(
'height', this.size_.height as AnyDuringMigration);
'height', this.size_.height as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.borderRect_.setAttribute(
'rx',
this.getConstants()!.FIELD_BORDER_RECT_RADIUS as AnyDuringMigration);
'rx',
this.getConstants()!.FIELD_BORDER_RECT_RADIUS as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.borderRect_.setAttribute(
'ry',
this.getConstants()!.FIELD_BORDER_RECT_RADIUS as AnyDuringMigration);
'ry',
this.getConstants()!.FIELD_BORDER_RECT_RADIUS as AnyDuringMigration);
}
/**
@@ -752,8 +752,8 @@ export abstract class Field implements IASTNodeLocationSvg,
// If the field is not visible the width will be 0 as well, one of the
// problems with the old system.
console.warn(
'Deprecated use of setting size_.width to 0 to rerender a' +
' field. Set field.isDirty_ to true instead.');
'Deprecated use of setting size_.width to 0 to rerender a' +
' field. Set field.isDirty_ to true instead.');
this.render_();
}
return this.size_;
@@ -849,7 +849,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* Return null to resort to a string cast.
* @return Current text or null.
*/
protected getText_(): string | null {
protected getText_(): string|null {
return null;
}
@@ -930,7 +930,7 @@ export abstract class Field implements IASTNodeLocationSvg,
this.doValueUpdate_(newValue);
if (source && eventUtils.isEnabled()) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(source, 'field', this.name || null, oldValue, newValue));
(source, 'field', this.name || null, oldValue, newValue));
}
if (this.isDirty_) {
this.forceRerender();
@@ -945,8 +945,8 @@ export abstract class Field implements IASTNodeLocationSvg,
* @return New value, or an Error object.
*/
private processValidation_(
newValue: AnyDuringMigration,
validatedValue: AnyDuringMigration): AnyDuringMigration {
newValue: AnyDuringMigration,
validatedValue: AnyDuringMigration): AnyDuringMigration {
if (validatedValue === null) {
this.doValueInvalid_(newValue);
if (this.isDirty_) {
@@ -975,7 +975,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* @return The validated value, same as input by default.
*/
protected doClassValidation_(opt_newValue?: AnyDuringMigration):
AnyDuringMigration {
AnyDuringMigration {
if (opt_newValue === null || opt_newValue === undefined) {
return null;
}
@@ -1022,7 +1022,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* display the tooltip of the parent block. To not display a tooltip pass
* the empty string.
*/
setTooltip(newTip: Tooltip.TipInfo | null) {
setTooltip(newTip: Tooltip.TipInfo|null) {
if (!newTip && newTip !== '') {
// If null or undefined.
newTip = this.sourceBlock_;
@@ -1046,7 +1046,7 @@ export abstract class Field implements IASTNodeLocationSvg,
return Tooltip.getTooltipOfObject(clickTarget);
}
// Field has not been initialized yet. Return stashed this.tooltip_ value.
return Tooltip.getTooltipOfObject({ tooltip: this.tooltip_ });
return Tooltip.getTooltipOfObject({tooltip: this.tooltip_});
}
/**
+50 -51
View File
@@ -12,19 +12,19 @@
* @class
*/
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as Css from './css.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { FieldTextInput } from './field_textinput.js';
import {FieldTextInput} from './field_textinput.js';
import * as dom from './utils/dom.js';
import { KeyCodes } from './utils/keycodes.js';
import {KeyCodes} from './utils/keycodes.js';
import * as math from './utils/math.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import { Svg } from './utils/svg.js';
import {Sentinel} from './utils/sentinel.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
import * as WidgetDiv from './widgetdiv.js';
@@ -76,13 +76,13 @@ export class FieldAngle extends FieldTextInput {
private round_: number;
/** The angle picker's SVG element. */
private editor_: SVGElement | null = null;
private editor_: SVGElement|null = null;
/** The angle picker's gauge path depending on the value. */
gauge_: SVGElement | null = null;
gauge_: SVGElement|null = null;
/** The angle picker's line drawn representing the value's angle. */
line_: SVGElement | null = null;
line_: SVGElement|null = null;
/** The degree symbol for this field. */
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -90,13 +90,13 @@ export class FieldAngle extends FieldTextInput {
protected symbol_: SVGTSpanElement = null as AnyDuringMigration;
/** Wrapper click event data. */
private clickWrapper_: browserEvents.Data | null = null;
private clickWrapper_: browserEvents.Data|null = null;
/** Surface click event data. */
private clickSurfaceWrapper_: browserEvents.Data | null = null;
private clickSurfaceWrapper_: browserEvents.Data|null = null;
/** Surface mouse move event data. */
private moveSurfaceWrapper_: browserEvents.Data | null = null;
private moveSurfaceWrapper_: browserEvents.Data|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -118,8 +118,8 @@ export class FieldAngle extends FieldTextInput {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | number | Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
opt_value?: string|number|Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
/**
@@ -242,22 +242,21 @@ export class FieldAngle extends FieldTextInput {
if (this.sourceBlock_ instanceof BlockSvg) {
dropDownDiv.setColour(
this.sourceBlock_.style.colourPrimary,
this.sourceBlock_.style.colourTertiary);
this.sourceBlock_.style.colourPrimary,
this.sourceBlock_.style.colourTertiary);
}
// AnyDuringMigration because: Argument of type 'this' is not assignable to
// parameter of type 'Field'.
dropDownDiv.showPositionedByField(
this as AnyDuringMigration, this.dropdownDispose_.bind(this));
this as AnyDuringMigration, this.dropdownDispose_.bind(this));
this.updateGraph_();
}
/** Create the angle dropdown editor. */
private dropdownCreate_() {
const svg = dom.createSvgElement(
Svg.SVG, {
const svg = dom.createSvgElement(Svg.SVG, {
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
@@ -267,50 +266,50 @@ export class FieldAngle extends FieldTextInput {
'style': 'touch-action: none',
});
const circle = dom.createSvgElement(
Svg.CIRCLE, {
'cx': FieldAngle.HALF,
'cy': FieldAngle.HALF,
'r': FieldAngle.RADIUS,
'class': 'blocklyAngleCircle',
},
svg);
Svg.CIRCLE, {
'cx': FieldAngle.HALF,
'cy': FieldAngle.HALF,
'r': FieldAngle.RADIUS,
'class': 'blocklyAngleCircle',
},
svg);
this.gauge_ =
dom.createSvgElement(Svg.PATH, { 'class': 'blocklyAngleGauge' }, svg);
dom.createSvgElement(Svg.PATH, {'class': 'blocklyAngleGauge'}, svg);
this.line_ = dom.createSvgElement(
Svg.LINE, {
'x1': FieldAngle.HALF,
'y1': FieldAngle.HALF,
'class': 'blocklyAngleLine',
},
svg);
Svg.LINE, {
'x1': FieldAngle.HALF,
'y1': FieldAngle.HALF,
'class': 'blocklyAngleLine',
},
svg);
// Draw markers around the edge.
for (let angle = 0; angle < 360; angle += 15) {
dom.createSvgElement(
Svg.LINE, {
'x1': FieldAngle.HALF + FieldAngle.RADIUS,
'y1': FieldAngle.HALF,
'x2': FieldAngle.HALF + FieldAngle.RADIUS -
(angle % 45 === 0 ? 10 : 5),
'y2': FieldAngle.HALF,
'class': 'blocklyAngleMarks',
'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' +
FieldAngle.HALF + ')',
},
svg);
Svg.LINE, {
'x1': FieldAngle.HALF + FieldAngle.RADIUS,
'y1': FieldAngle.HALF,
'x2': FieldAngle.HALF + FieldAngle.RADIUS -
(angle % 45 === 0 ? 10 : 5),
'y2': FieldAngle.HALF,
'class': 'blocklyAngleMarks',
'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' +
FieldAngle.HALF + ')',
},
svg);
}
// The angle picker is different from other fields in that it updates on
// mousemove even if it's not in the middle of a drag. In future we may
// change this behaviour.
this.clickWrapper_ =
browserEvents.conditionalBind(svg, 'click', this, this.hide_);
browserEvents.conditionalBind(svg, 'click', this, this.hide_);
// On touch devices, the picker's value is only updated with a drag. Add
// a click handler on the drag surface to update the value if the surface
// is clicked.
this.clickSurfaceWrapper_ = browserEvents.conditionalBind(
circle, 'click', this, this.onMouseMove_, true, true);
circle, 'click', this, this.onMouseMove_, true, true);
this.moveSurfaceWrapper_ = browserEvents.conditionalBind(
circle, 'mousemove', this, this.onMouseMove_, true, true);
circle, 'mousemove', this, this.onMouseMove_, true, true);
this.editor_ = svg;
}
@@ -414,13 +413,13 @@ export class FieldAngle extends FieldTextInput {
y2 -= Math.sin(angleRadians) * FieldAngle.RADIUS;
// Don't ask how the flag calculations work. They just do.
let largeFlag =
Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2);
Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2);
if (clockwiseFlag) {
largeFlag = 1 - largeFlag;
}
path.push(
' l ', x1, ',', y1, ' A ', FieldAngle.RADIUS, ',', FieldAngle.RADIUS,
' 0 ', largeFlag, ' ', clockwiseFlag, ' ', x2, ',', y2, ' z');
' l ', x1, ',', y1, ' A ', FieldAngle.RADIUS, ',', FieldAngle.RADIUS,
' 0 ', largeFlag, ' ', clockwiseFlag, ' ', x2, ',', y2, ' z');
}
this.gauge_.setAttribute('d', path.join(''));
// AnyDuringMigration because: Argument of type 'number' is not assignable
@@ -474,7 +473,7 @@ export class FieldAngle extends FieldTextInput {
* @return A valid angle, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
number | null {
number|null {
const value = Number(opt_newValue);
if (isNaN(value) || !isFinite(value)) {
return null;
+6 -6
View File
@@ -15,11 +15,11 @@
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_block_change';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import * as dom from './utils/dom.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import {Sentinel} from './utils/sentinel.js';
/**
@@ -61,8 +61,8 @@ export class FieldCheckbox extends Field {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | boolean | Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
opt_value?: string|boolean|Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
/**
@@ -130,7 +130,7 @@ export class FieldCheckbox extends Field {
* @param character The character to use for the check mark, or null to use
* the default.
*/
setCheckCharacter(character: string | null) {
setCheckCharacter(character: string|null) {
this.checkChar_ = character || FieldCheckbox.CHECK_CHAR;
this.forceRerender();
}
@@ -146,7 +146,7 @@ export class FieldCheckbox extends Field {
* @return A valid value ('TRUE' or 'FALSE), or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
if (opt_newValue === true || opt_newValue === 'TRUE') {
return 'TRUE';
}
+33 -33
View File
@@ -15,20 +15,20 @@
// Unused import preserved for side-effects. Remove if unneeded.
import './events/events_block_change';
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as Css from './css.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import * as aria from './utils/aria.js';
import * as colour from './utils/colour.js';
import * as dom from './utils/dom.js';
import * as idGenerator from './utils/idgenerator.js';
import { KeyCodes } from './utils/keycodes.js';
import {KeyCodes} from './utils/keycodes.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import { Size } from './utils/size.js';
import {Sentinel} from './utils/sentinel.js';
import {Size} from './utils/size.js';
/**
@@ -80,25 +80,25 @@ export class FieldColour extends Field {
static COLUMNS = 7;
/** The field's colour picker element. */
private picker_: Element | null = null;
private picker_: Element|null = null;
/** Index of the currently highlighted element. */
private highlightedIndex_: number | null = null;
private highlightedIndex_: number|null = null;
/** Mouse click event data. */
private onClickWrapper_: browserEvents.Data | null = null;
private onClickWrapper_: browserEvents.Data|null = null;
/** Mouse move event data. */
private onMouseMoveWrapper_: browserEvents.Data | null = null;
private onMouseMoveWrapper_: browserEvents.Data|null = null;
/** Mouse enter event data. */
private onMouseEnterWrapper_: browserEvents.Data | null = null;
private onMouseEnterWrapper_: browserEvents.Data|null = null;
/** Mouse leave event data. */
private onMouseLeaveWrapper_: browserEvents.Data | null = null;
private onMouseLeaveWrapper_: browserEvents.Data|null = null;
/** Key down event data. */
private onKeyDownWrapper_: browserEvents.Data | null = null;
private onKeyDownWrapper_: browserEvents.Data|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -153,8 +153,8 @@ export class FieldColour extends Field {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
opt_value?: string|Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
if (opt_value === Field.SKIP_SETUP) {
@@ -187,8 +187,8 @@ export class FieldColour extends Field {
/** Create the block UI for this colour field. */
override initView() {
this.size_ = new Size(
this.getConstants()!.FIELD_COLOUR_DEFAULT_WIDTH,
this.getConstants()!.FIELD_COLOUR_DEFAULT_HEIGHT);
this.getConstants()!.FIELD_COLOUR_DEFAULT_WIDTH,
this.getConstants()!.FIELD_COLOUR_DEFAULT_HEIGHT);
if (!this.getConstants()!.FIELD_COLOUR_FULL_BLOCK) {
this.createBorderRect_();
this.borderRect_.style['fillOpacity'] = '1';
@@ -204,7 +204,7 @@ export class FieldColour extends Field {
}
} else if (this.sourceBlock_ instanceof BlockSvg) {
this.sourceBlock_.pathObject.svgPath.setAttribute(
'fill', this.getValue() as string);
'fill', this.getValue() as string);
this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff');
}
}
@@ -215,7 +215,7 @@ export class FieldColour extends Field {
* @return A valid colour, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
if (typeof opt_newValue !== 'string') {
return null;
}
@@ -232,10 +232,10 @@ export class FieldColour extends Field {
if (this.borderRect_) {
this.borderRect_.style.fill = newValue as string;
} else if (
this.sourceBlock_ && this.sourceBlock_.rendered &&
this.sourceBlock_ instanceof BlockSvg) {
this.sourceBlock_ && this.sourceBlock_.rendered &&
this.sourceBlock_ instanceof BlockSvg) {
this.sourceBlock_.pathObject.svgPath.setAttribute(
'fill', newValue as string);
'fill', newValue as string);
this.sourceBlock_.pathObject.svgPath.setAttribute('stroke', '#fff');
}
}
@@ -292,7 +292,7 @@ export class FieldColour extends Field {
// Focus so we can start receiving keyboard events.
// AnyDuringMigration because: Property 'focus' does not exist on type
// 'Element'.
(this.picker_ as AnyDuringMigration)!.focus({ preventScroll: true });
(this.picker_ as AnyDuringMigration)!.focus({preventScroll: true});
}
/**
@@ -417,7 +417,7 @@ export class FieldColour extends Field {
private onMouseEnter_() {
// AnyDuringMigration because: Property 'focus' does not exist on type
// 'Element'.
(this.picker_ as AnyDuringMigration)!.focus({ preventScroll: true });
(this.picker_ as AnyDuringMigration)!.focus({preventScroll: true});
}
/**
@@ -438,7 +438,7 @@ export class FieldColour extends Field {
* Returns the currently highlighted item (if any).
* @return Highlighted item (null if none).
*/
private getHighlighted_(): HTMLElement | null {
private getHighlighted_(): HTMLElement|null {
if (!this.highlightedIndex_) {
return null;
}
@@ -474,8 +474,8 @@ export class FieldColour extends Field {
// AnyDuringMigration because: Argument of type 'string | null' is not
// assignable to parameter of type 'string | number | boolean | string[]'.
aria.setState(
this.picker_ as Element, aria.State.ACTIVEDESCENDANT,
cell.getAttribute('id') as AnyDuringMigration);
this.picker_ as Element, aria.State.ACTIVEDESCENDANT,
cell.getAttribute('id') as AnyDuringMigration);
}
/** Create a colour picker dropdown editor. */
@@ -492,7 +492,7 @@ export class FieldColour extends Field {
aria.setRole(table, aria.Role.GRID);
aria.setState(table, aria.State.EXPANDED, true);
aria.setState(
table, aria.State.ROWCOUNT, Math.floor(colours.length / columns));
table, aria.State.ROWCOUNT, Math.floor(colours.length / columns));
aria.setState(table, aria.State.COLCOUNT, columns);
let row: Element;
for (let i = 0; i < colours.length; i++) {
@@ -522,15 +522,15 @@ export class FieldColour extends Field {
// Configure event handler on the table to listen for any event in a cell.
this.onClickWrapper_ = browserEvents.conditionalBind(
table, 'click', this, this.onClick_, true);
table, 'click', this, this.onClick_, true);
this.onMouseMoveWrapper_ = browserEvents.conditionalBind(
table, 'mousemove', this, this.onMouseMove_, true);
table, 'mousemove', this, this.onMouseMove_, true);
this.onMouseEnterWrapper_ = browserEvents.conditionalBind(
table, 'mouseenter', this, this.onMouseEnter_, true);
table, 'mouseenter', this, this.onMouseEnter_, true);
this.onMouseLeaveWrapper_ = browserEvents.conditionalBind(
table, 'mouseleave', this, this.onMouseLeave_, true);
table, 'mouseleave', this, this.onMouseLeave_, true);
this.onKeyDownWrapper_ =
browserEvents.conditionalBind(table, 'keydown', this, this.onKeyDown_);
browserEvents.conditionalBind(table, 'keydown', this, this.onKeyDown_);
this.picker_ = table;
}
@@ -578,7 +578,7 @@ export class FieldColour extends Field {
// AnyDuringMigration because: Property 'DEFAULT_VALUE' is protected and only
// accessible within class 'FieldColour' and its subclasses.
(FieldColour.prototype as AnyDuringMigration).DEFAULT_VALUE =
FieldColour.COLOURS[0];
FieldColour.COLOURS[0];
/** CSS for colour picker. See css.js for use. */
Css.register(`
+82 -81
View File
@@ -19,20 +19,20 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { Menu } from './menu.js';
import { MenuItem } from './menuitem.js';
import {Menu} from './menu.js';
import {MenuItem} from './menuitem.js';
import * as aria from './utils/aria.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import {Sentinel} from './utils/sentinel.js';
import * as utilsString from './utils/string.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
@@ -52,21 +52,21 @@ export class FieldDropdown extends Field {
static ARROW_CHAR: AnyDuringMigration;
/** A reference to the currently selected menu item. */
private selectedMenuItem_: MenuItem | null = null;
private selectedMenuItem_: MenuItem|null = null;
/** The dropdown menu. */
protected menu_: Menu | null = null;
protected menu_: Menu|null = null;
/**
* SVG image element if currently selected option is an image, or null.
*/
private imageElement_: SVGImageElement | null = null;
private imageElement_: SVGImageElement|null = null;
/** Tspan based arrow element. */
private arrow_: SVGTSpanElement | null = null;
private arrow_: SVGTSpanElement|null = null;
/** SVG based arrow element. */
private svgArrow_: SVGElement | null = null;
private svgArrow_: SVGElement|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -77,8 +77,8 @@ export class FieldDropdown extends Field {
/** Mouse cursor style when over the hotspot that initiates the editor. */
override CURSOR = 'default';
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
protected menuGenerator_!: AnyDuringMigration[][] |
((this: FieldDropdown) => AnyDuringMigration[][]);
protected menuGenerator_!: AnyDuringMigration[][]|
((this: FieldDropdown) => AnyDuringMigration[][]);
/** A cache of the most recently generated options. */
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -88,14 +88,14 @@ export class FieldDropdown extends Field {
/**
* The prefix field label, of common words set after options are trimmed.
*/
override prefixField: string | null = null;
override prefixField: string|null = null;
/**
* The suffix field label, of common words set after options are trimmed.
*/
override suffixField: string | null = null;
override suffixField: string|null = null;
// TODO(b/109816955): remove '!', see go/strict-prop-init-fix.
private selectedOption_!: Array<string | ImageProperties>;
private selectedOption_!: Array<string|ImageProperties>;
override clickTarget_: AnyDuringMigration;
/**
@@ -115,8 +115,8 @@ export class FieldDropdown extends Field {
* @throws {TypeError} If `menuGenerator` options are incorrectly structured.
*/
constructor(
menuGenerator: AnyDuringMigration[][] | Function | Sentinel,
opt_validator?: Function, opt_config?: AnyDuringMigration) {
menuGenerator: AnyDuringMigration[][]|Function|Sentinel,
opt_validator?: Function, opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
@@ -134,7 +134,7 @@ export class FieldDropdown extends Field {
* or a function which generates these options.
*/
this.menuGenerator_ = menuGenerator as AnyDuringMigration[][] |
((this: FieldDropdown) => AnyDuringMigration[][]);
((this: FieldDropdown) => AnyDuringMigration[][]);
this.trimOptions_();
@@ -207,21 +207,21 @@ export class FieldDropdown extends Field {
*/
protected shouldAddBorderRect_(): boolean {
return !this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW ||
this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW &&
!this.sourceBlock_.isShadow();
this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW &&
!this.sourceBlock_.isShadow();
}
/** Create a tspan based arrow. */
protected createTextArrow_() {
this.arrow_ = dom.createSvgElement(Svg.TSPAN, {}, this.textElement_);
this.arrow_!.appendChild(document.createTextNode(
this.sourceBlock_.RTL ? FieldDropdown.ARROW_CHAR + ' ' :
' ' + FieldDropdown.ARROW_CHAR));
this.sourceBlock_.RTL ? FieldDropdown.ARROW_CHAR + ' ' :
' ' + FieldDropdown.ARROW_CHAR));
if (this.sourceBlock_.RTL) {
// AnyDuringMigration because: Argument of type 'SVGTSpanElement | null'
// is not assignable to parameter of type 'Node'.
this.textElement_.insertBefore(
this.arrow_ as AnyDuringMigration, this.textContent_);
this.arrow_ as AnyDuringMigration, this.textContent_);
} else {
// AnyDuringMigration because: Argument of type 'SVGTSpanElement | null'
// is not assignable to parameter of type 'Node'.
@@ -232,14 +232,14 @@ export class FieldDropdown extends Field {
/** Create an SVG based arrow. */
protected createSVGArrow_() {
this.svgArrow_ = dom.createSvgElement(
Svg.IMAGE, {
'height': this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px',
'width': this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px',
},
this.fieldGroup_);
Svg.IMAGE, {
'height': this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px',
'width': this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE + 'px',
},
this.fieldGroup_);
this.svgArrow_!.setAttributeNS(
dom.XLINK_NS, 'xlink:href',
this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_DATAURI);
dom.XLINK_NS, 'xlink:href',
this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_DATAURI);
}
/**
@@ -256,8 +256,8 @@ export class FieldDropdown extends Field {
// 'Event'. AnyDuringMigration because: Property 'clientX' does not exist
// on type 'Event'.
this.menu_!.openingCoords = new Coordinate(
(opt_e as AnyDuringMigration).clientX,
(opt_e as AnyDuringMigration).clientY);
(opt_e as AnyDuringMigration).clientX,
(opt_e as AnyDuringMigration).clientY);
} else {
this.menu_!.openingCoords = null;
}
@@ -271,11 +271,11 @@ export class FieldDropdown extends Field {
if (this.getConstants()!.FIELD_DROPDOWN_COLOURED_DIV) {
const primaryColour = this.sourceBlock_.isShadow() ?
this.sourceBlock_.getParent()!.getColour() :
this.sourceBlock_.getColour();
this.sourceBlock_.getParent()!.getColour() :
this.sourceBlock_.getColour();
const borderColour = this.sourceBlock_.isShadow() ?
(this.sourceBlock_.getParent() as BlockSvg).style.colourTertiary :
(this.sourceBlock_ as BlockSvg).style.colourTertiary;
(this.sourceBlock_.getParent() as BlockSvg).style.colourTertiary :
(this.sourceBlock_ as BlockSvg).style.colourTertiary;
dropDownDiv.setColour(primaryColour, borderColour);
}
@@ -405,7 +405,7 @@ export class FieldDropdown extends Field {
}
this.menuGenerator_ =
FieldDropdown.applyTrim_(options, prefixLength, suffixLength);
FieldDropdown.applyTrim_(options, prefixLength, suffixLength);
}
/**
@@ -430,7 +430,7 @@ export class FieldDropdown extends Field {
// AnyDuringMigration because: Property 'call' does not exist on type
// 'any[][] | ((this: FieldDropdown) => any[][])'.
this.generatedOptions_ =
(this.menuGenerator_ as AnyDuringMigration).call(this);
(this.menuGenerator_ as AnyDuringMigration).call(this);
validateOptions(this.generatedOptions_);
}
return this.generatedOptions_;
@@ -444,7 +444,7 @@ export class FieldDropdown extends Field {
* @return A valid language-neutral option, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
let isValueValid = false;
const options = this.getOptions(true);
for (let i = 0, option; option = options[i]; i++) {
@@ -457,9 +457,9 @@ export class FieldDropdown extends Field {
if (!isValueValid) {
if (this.sourceBlock_) {
console.warn(
'Cannot set the dropdown\'s value to an unavailable option.' +
' Block type: ' + this.sourceBlock_.type +
', Field name: ' + this.name + ', Value: ' + opt_newValue);
'Cannot set the dropdown\'s value to an unavailable option.' +
' Block type: ' + this.sourceBlock_.type +
', Field name: ' + this.name + ', Value: ' + opt_newValue);
}
return null;
}
@@ -526,15 +526,15 @@ export class FieldDropdown extends Field {
private renderSelectedImage_(imageJson: ImageProperties) {
this.imageElement_!.style.display = '';
this.imageElement_!.setAttributeNS(
dom.XLINK_NS, 'xlink:href', imageJson.src);
dom.XLINK_NS, 'xlink:href', imageJson.src);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.imageElement_!.setAttribute(
'height', imageJson.height as AnyDuringMigration);
'height', imageJson.height as AnyDuringMigration);
// AnyDuringMigration because: Argument of type 'number' is not assignable
// to parameter of type 'string'.
this.imageElement_!.setAttribute(
'width', imageJson.width as AnyDuringMigration);
'width', imageJson.width as AnyDuringMigration);
const imageHeight = Number(imageJson.height);
const imageWidth = Number(imageJson.width);
@@ -542,21 +542,21 @@ export class FieldDropdown extends Field {
// Height and width include the border rect.
const hasBorder = !!this.borderRect_;
const height = Math.max(
hasBorder ? this.getConstants()!.FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0,
imageHeight + IMAGE_Y_PADDING);
hasBorder ? this.getConstants()!.FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0,
imageHeight + IMAGE_Y_PADDING);
const xPadding =
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
let arrowWidth = 0;
if (this.svgArrow_) {
arrowWidth = this.positionSVGArrow_(
imageWidth + xPadding,
height / 2 - this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE / 2);
imageWidth + xPadding,
height / 2 - this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE / 2);
} else {
arrowWidth = dom.getFastTextWidth(
this.arrow_ as SVGTSpanElement,
this.getConstants()!.FIELD_TEXT_FONTSIZE,
this.getConstants()!.FIELD_TEXT_FONTWEIGHT,
this.getConstants()!.FIELD_TEXT_FONTFAMILY);
this.arrow_ as SVGTSpanElement,
this.getConstants()!.FIELD_TEXT_FONTSIZE,
this.getConstants()!.FIELD_TEXT_FONTWEIGHT,
this.getConstants()!.FIELD_TEXT_FONTFAMILY);
}
this.size_.width = imageWidth + arrowWidth + xPadding * 2;
this.size_.height = height;
@@ -570,7 +570,8 @@ export class FieldDropdown extends Field {
this.textElement_.setAttribute('text-anchor', 'end');
this.imageElement_!.setAttribute('x', xPadding.toString());
}
this.imageElement_!.setAttribute('y', (height / 2 - imageHeight / 2).toString());
this.imageElement_!.setAttribute(
'y', (height / 2 - imageHeight / 2).toString());
this.positionTextElement_(arrowX + xPadding, imageWidth + arrowWidth);
}
@@ -585,19 +586,19 @@ export class FieldDropdown extends Field {
// Height and width include the border rect.
const hasBorder = !!this.borderRect_;
const height = Math.max(
hasBorder ? this.getConstants()!.FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0,
this.getConstants()!.FIELD_TEXT_HEIGHT);
hasBorder ? this.getConstants()!.FIELD_DROPDOWN_BORDER_RECT_HEIGHT : 0,
this.getConstants()!.FIELD_TEXT_HEIGHT);
const textWidth = dom.getFastTextWidth(
this.textElement_, this.getConstants()!.FIELD_TEXT_FONTSIZE,
this.getConstants()!.FIELD_TEXT_FONTWEIGHT,
this.getConstants()!.FIELD_TEXT_FONTFAMILY);
this.textElement_, this.getConstants()!.FIELD_TEXT_FONTSIZE,
this.getConstants()!.FIELD_TEXT_FONTWEIGHT,
this.getConstants()!.FIELD_TEXT_FONTFAMILY);
const xPadding =
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
let arrowWidth = 0;
if (this.svgArrow_) {
arrowWidth = this.positionSVGArrow_(
textWidth + xPadding,
height / 2 - this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE / 2);
textWidth + xPadding,
height / 2 - this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE / 2);
}
this.size_.width = textWidth + arrowWidth + xPadding * 2;
this.size_.height = height;
@@ -617,12 +618,12 @@ export class FieldDropdown extends Field {
}
const hasBorder = !!this.borderRect_;
const xPadding =
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
hasBorder ? this.getConstants()!.FIELD_BORDER_RECT_X_PADDING : 0;
const textPadding = this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_PADDING;
const svgArrowSize = this.getConstants()!.FIELD_DROPDOWN_SVG_ARROW_SIZE;
const arrowX = this.sourceBlock_.RTL ? xPadding : x + textPadding;
this.svgArrow_.setAttribute(
'transform', 'translate(' + arrowX + ',' + y + ')');
'transform', 'translate(' + arrowX + ',' + y + ')');
return svgArrowSize + textPadding;
}
@@ -632,7 +633,7 @@ export class FieldDropdown extends Field {
* image we return the image alt text.
* @return Selected option text.
*/
protected override getText_(): string | null {
protected override getText_(): string|null {
if (!this.selectedOption_) {
return null;
}
@@ -665,8 +666,8 @@ export class FieldDropdown extends Field {
* @return A new array with all of the option text trimmed.
*/
static applyTrim_(
options: AnyDuringMigration[][], prefixLength: number,
suffixLength: number): AnyDuringMigration[][] {
options: AnyDuringMigration[][], prefixLength: number,
suffixLength: number): AnyDuringMigration[][] {
const newOptions = [];
// Remove the prefix and suffix from the options.
for (let i = 0; i < options.length; i++) {
@@ -717,23 +718,23 @@ function validateOptions(options: AnyDuringMigration) {
if (!Array.isArray(tuple)) {
foundError = true;
console.error(
'Invalid option[' + i + ']: Each FieldDropdown option must be an ' +
'array. Found: ',
tuple);
'Invalid option[' + i + ']: Each FieldDropdown option must be an ' +
'array. Found: ',
tuple);
} else if (typeof tuple[1] !== 'string') {
foundError = true;
console.error(
'Invalid option[' + i + ']: Each FieldDropdown option id must be ' +
'a string. Found ' + tuple[1] + ' in: ',
tuple);
'Invalid option[' + i + ']: Each FieldDropdown option id must be ' +
'a string. Found ' + tuple[1] + ' in: ',
tuple);
} else if (
tuple[0] && typeof tuple[0] !== 'string' &&
typeof tuple[0].src !== 'string') {
tuple[0] && typeof tuple[0] !== 'string' &&
typeof tuple[0].src !== 'string') {
foundError = true;
console.error(
'Invalid option[' + i + ']: Each FieldDropdown option must have a ' +
'string label or image description. Found' + tuple[0] + ' in: ',
tuple);
'Invalid option[' + i + ']: Each FieldDropdown option must have a ' +
'string label or image description. Found' + tuple[0] + ' in: ',
tuple);
}
}
if (foundError) {
+26 -26
View File
@@ -12,14 +12,14 @@
* @class
*/
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import * as dom from './utils/dom.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import { Size } from './utils/size.js';
import { Svg } from './utils/svg.js';
import {Sentinel} from './utils/sentinel.js';
import {Size} from './utils/size.js';
import {Svg} from './utils/svg.js';
/**
@@ -39,7 +39,7 @@ export class FieldImage extends Field {
private readonly imageHeight_: number;
/** The function to be called when this field is clicked. */
private clickHandler_: ((p1: FieldImage) => AnyDuringMigration) | null = null;
private clickHandler_: ((p1: FieldImage) => AnyDuringMigration)|null = null;
/** The rendered field's image element. */
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -83,9 +83,9 @@ export class FieldImage extends Field {
* for a list of properties this parameter supports.
*/
constructor(
src: string | Sentinel, width: string | number, height: string | number,
opt_alt?: string, opt_onClick?: (p1: FieldImage) => AnyDuringMigration,
opt_flipRtl?: boolean, opt_config?: AnyDuringMigration) {
src: string|Sentinel, width: string|number, height: string|number,
opt_alt?: string, opt_onClick?: (p1: FieldImage) => AnyDuringMigration,
opt_flipRtl?: boolean, opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
// Return early.
@@ -96,13 +96,13 @@ export class FieldImage extends Field {
const imageWidth = Number(parsing.replaceMessageReferences(width));
if (isNaN(imageHeight) || isNaN(imageWidth)) {
throw Error(
'Height and width values of an image field must cast to' +
' numbers.');
'Height and width values of an image field must cast to' +
' numbers.');
}
if (imageHeight <= 0 || imageWidth <= 0) {
throw Error(
'Height and width values of an image field must be greater' +
' than 0.');
'Height and width values of an image field must be greater' +
' than 0.');
}
/** The size of the area rendered by the field. */
@@ -143,14 +143,14 @@ export class FieldImage extends Field {
/** Create the block UI for this image. */
override initView() {
this.imageElement_ = dom.createSvgElement(
Svg.IMAGE, {
'height': this.imageHeight_ + 'px',
'width': this.size_.width + 'px',
'alt': this.altText_,
},
this.fieldGroup_);
Svg.IMAGE, {
'height': this.imageHeight_ + 'px',
'width': this.size_.width + 'px',
'alt': this.altText_,
},
this.fieldGroup_);
this.imageElement_.setAttributeNS(
dom.XLINK_NS, 'xlink:href', this.value_ as string);
dom.XLINK_NS, 'xlink:href', this.value_ as string);
if (this.clickHandler_) {
this.imageElement_.style.cursor = 'pointer';
@@ -166,7 +166,7 @@ export class FieldImage extends Field {
* @return A string, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
if (typeof opt_newValue !== 'string') {
return null;
}
@@ -182,7 +182,7 @@ export class FieldImage extends Field {
this.value_ = newValue;
if (this.imageElement_) {
this.imageElement_.setAttributeNS(
dom.XLINK_NS, 'xlink:href', String(this.value_));
dom.XLINK_NS, 'xlink:href', String(this.value_));
}
}
@@ -198,7 +198,7 @@ export class FieldImage extends Field {
* Set the alt text of this image.
* @param alt New alt text.
*/
setAlt(alt: string | null) {
setAlt(alt: string|null) {
if (alt === this.altText_) {
return;
}
@@ -223,7 +223,7 @@ export class FieldImage extends Field {
* @param func The function that is called when the image is clicked, or null
* to remove.
*/
setOnClickHandler(func: ((p1: FieldImage) => AnyDuringMigration) | null) {
setOnClickHandler(func: ((p1: FieldImage) => AnyDuringMigration)|null) {
this.clickHandler_ = func;
}
@@ -233,7 +233,7 @@ export class FieldImage extends Field {
* Return the image alt text instead.
* @return The image alt text.
*/
protected override getText_(): string | null {
protected override getText_(): string|null {
return this.altText_;
}
@@ -249,8 +249,8 @@ export class FieldImage extends Field {
// `this` might be a subclass of FieldImage if that class doesn't override
// the static fromJson method.
return new this(
options['src'], options['width'], options['height'], undefined,
undefined, undefined, options);
options['src'], options['width'], options['height'], undefined,
undefined, undefined, options);
}
}
+7 -7
View File
@@ -16,12 +16,12 @@
* @class
*/
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import * as dom from './utils/dom.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import {Sentinel} from './utils/sentinel.js';
/**
@@ -33,7 +33,7 @@ export class FieldLabel extends Field {
protected override DEFAULT_VALUE = '';
/** The html class name to use for this field. */
private class_: string | null = null;
private class_: string|null = null;
/**
* Editable fields usually show some sort of UI indicating they are
@@ -54,8 +54,8 @@ export class FieldLabel extends Field {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | Sentinel, opt_class?: string,
opt_config?: AnyDuringMigration) {
opt_value?: string|Sentinel, opt_class?: string,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
if (opt_value === Field.SKIP_SETUP) {
@@ -88,7 +88,7 @@ export class FieldLabel extends Field {
* @return A valid string, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
if (opt_newValue === null || opt_newValue === undefined) {
return null;
}
@@ -99,7 +99,7 @@ export class FieldLabel extends Field {
* Set the CSS class applied to the field's textElement_.
* @param cssClass The new CSS class name, or null to remove.
*/
setClass(cssClass: string | null) {
setClass(cssClass: string|null) {
if (this.textElement_) {
// This check isn't necessary, but it's faster than letting removeClass
// figure it out.
+3 -3
View File
@@ -18,7 +18,7 @@
* @class
*/
import { FieldLabel } from './field_label.js';
import {FieldLabel} from './field_label.js';
import * as fieldRegistry from './field_registry.js';
import * as parsing from './utils/parsing.js';
@@ -51,7 +51,7 @@ export class FieldLabelSerializable extends FieldLabel {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string, opt_class?: string, opt_config?: AnyDuringMigration) {
opt_value?: string, opt_class?: string, opt_config?: AnyDuringMigration) {
super(String(opt_value ?? ''), opt_class, opt_config);
}
@@ -63,7 +63,7 @@ export class FieldLabelSerializable extends FieldLabel {
* @nocollapse
*/
static override fromJson(options: AnyDuringMigration):
FieldLabelSerializable {
FieldLabelSerializable {
const text = parsing.replaceMessageReferences(options['text']);
// `this` might be a subclass of FieldLabelSerializable if that class
// doesn't override the static fromJson method.
+32 -32
View File
@@ -13,16 +13,16 @@
*/
import * as Css from './css.js';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { FieldTextInput } from './field_textinput.js';
import {FieldTextInput} from './field_textinput.js';
import * as aria from './utils/aria.js';
import * as dom from './utils/dom.js';
import { KeyCodes } from './utils/keycodes.js';
import {KeyCodes} from './utils/keycodes.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import { Svg } from './utils/svg.js';
import {Sentinel} from './utils/sentinel.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
import * as WidgetDiv from './widgetdiv.js';
@@ -65,8 +65,8 @@ export class FieldMultilineInput extends FieldTextInput {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
opt_value?: string|Sentinel, opt_validator?: Function,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
if (opt_value === Field.SKIP_SETUP) {
@@ -98,7 +98,7 @@ export class FieldMultilineInput extends FieldTextInput {
// `Blockly.Xml.domToText` will appear on a single line (this is a
// limitation of the plain-text format).
fieldElement.textContent =
(this.getValue() as string).replace(/\n/g, '&#10;');
(this.getValue() as string).replace(/\n/g, '&#10;');
return fieldElement;
}
@@ -138,10 +138,10 @@ export class FieldMultilineInput extends FieldTextInput {
override initView() {
this.createBorderRect_();
this.textGroup_ = dom.createSvgElement(
Svg.G, {
'class': 'blocklyEditableText',
},
this.fieldGroup_);
Svg.G, {
'class': 'blocklyEditableText',
},
this.fieldGroup_);
}
/**
@@ -158,7 +158,7 @@ export class FieldMultilineInput extends FieldTextInput {
const lines = textLines.split('\n');
textLines = '';
const displayLinesNumber =
this.isOverflowedY_ ? this.maxLines_ : lines.length;
this.isOverflowedY_ ? this.maxLines_ : lines.length;
for (let i = 0; i < displayLinesNumber; i++) {
let text = lines[i];
if (text.length > this.maxDisplayLength) {
@@ -209,15 +209,15 @@ export class FieldMultilineInput extends FieldTextInput {
let y = 0;
for (let i = 0; i < lines.length; i++) {
const lineHeight = this.getConstants()!.FIELD_TEXT_HEIGHT +
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING;
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING;
const span = dom.createSvgElement(
Svg.TEXT, {
'class': 'blocklyText blocklyMultilineText',
'x': this.getConstants()!.FIELD_BORDER_RECT_X_PADDING,
'y': y + this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING,
'dy': this.getConstants()!.FIELD_TEXT_BASELINE,
},
this.textGroup_);
Svg.TEXT, {
'class': 'blocklyText blocklyMultilineText',
'x': this.getConstants()!.FIELD_BORDER_RECT_X_PADDING,
'y': y + this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING,
'dy': this.getConstants()!.FIELD_TEXT_BASELINE,
},
this.textGroup_);
span.appendChild(document.createTextNode(lines[i]));
y += lineHeight;
}
@@ -265,7 +265,7 @@ export class FieldMultilineInput extends FieldTextInput {
totalWidth = textWidth;
}
totalHeight += this.getConstants()!.FIELD_TEXT_HEIGHT +
(i > 0 ? this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING : 0);
(i > 0 ? this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING : 0);
}
if (this.isBeingEdited_) {
// The default width is based on the longest line in the display text,
@@ -275,7 +275,7 @@ export class FieldMultilineInput extends FieldTextInput {
// lines than this.maxLines_.
const actualEditorLines = this.value_.split('\n');
const dummyTextElement = dom.createSvgElement(
Svg.TEXT, { 'class': 'blocklyText blocklyMultilineText' });
Svg.TEXT, {'class': 'blocklyText blocklyMultilineText'});
const fontSize = this.getConstants()!.FIELD_TEXT_FONTSIZE;
const fontWeight = this.getConstants()!.FIELD_TEXT_FONTWEIGHT;
const fontFamily = this.getConstants()!.FIELD_TEXT_FONTFAMILY;
@@ -283,18 +283,18 @@ export class FieldMultilineInput extends FieldTextInput {
for (let i = 0; i < actualEditorLines.length; i++) {
if (actualEditorLines[i].length > this.maxDisplayLength) {
actualEditorLines[i] =
actualEditorLines[i].substring(0, this.maxDisplayLength);
actualEditorLines[i].substring(0, this.maxDisplayLength);
}
dummyTextElement.textContent = actualEditorLines[i];
const lineWidth = dom.getFastTextWidth(
dummyTextElement, fontSize, fontWeight, fontFamily);
dummyTextElement, fontSize, fontWeight, fontFamily);
if (lineWidth > totalWidth) {
totalWidth = lineWidth;
}
}
const scrollbarWidth =
this.htmlInput_!.offsetWidth - this.htmlInput_!.clientWidth;
this.htmlInput_!.offsetWidth - this.htmlInput_!.clientWidth;
totalWidth += scrollbarWidth;
}
if (this.borderRect_) {
@@ -306,7 +306,7 @@ export class FieldMultilineInput extends FieldTextInput {
// AnyDuringMigration because: Argument of type 'number' is not
// assignable to parameter of type 'string'.
this.borderRect_.setAttribute(
'height', totalHeight as AnyDuringMigration);
'height', totalHeight as AnyDuringMigration);
}
this.size_.width = totalWidth;
this.size_.height = totalHeight;
@@ -341,7 +341,7 @@ export class FieldMultilineInput extends FieldTextInput {
// AnyDuringMigration because: Argument of type 'boolean' is not assignable
// to parameter of type 'string'.
htmlInput.setAttribute(
'spellcheck', this.spellcheck_ as AnyDuringMigration);
'spellcheck', this.spellcheck_ as AnyDuringMigration);
const fontSize = this.getConstants()!.FIELD_TEXT_FONTSIZE * scale + 'pt';
div!.style.fontSize = fontSize;
htmlInput.style.fontSize = fontSize;
@@ -349,11 +349,11 @@ export class FieldMultilineInput extends FieldTextInput {
htmlInput.style.borderRadius = borderRadius;
const paddingX = this.getConstants()!.FIELD_BORDER_RECT_X_PADDING * scale;
const paddingY =
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING * scale / 2;
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING * scale / 2;
htmlInput.style.padding = paddingY + 'px ' + paddingX + 'px ' + paddingY +
'px ' + paddingX + 'px';
'px ' + paddingX + 'px';
const lineHeight = this.getConstants()!.FIELD_TEXT_HEIGHT +
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING;
this.getConstants()!.FIELD_BORDER_RECT_Y_PADDING;
htmlInput.style.lineHeight = lineHeight * scale + 'px';
div!.appendChild(htmlInput);
@@ -380,7 +380,7 @@ export class FieldMultilineInput extends FieldTextInput {
*/
setMaxLines(maxLines: number) {
if (typeof maxLines === 'number' && maxLines > 0 &&
maxLines !== this.maxLines_) {
maxLines !== this.maxLines_) {
this.maxLines_ = maxLines;
this.forceRerender();
}
+18 -18
View File
@@ -12,12 +12,12 @@
* @class
*/
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { FieldTextInput } from './field_textinput.js';
import {FieldTextInput} from './field_textinput.js';
import * as aria from './utils/aria.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import {Sentinel} from './utils/sentinel.js';
/**
@@ -41,7 +41,7 @@ export class FieldNumber extends FieldTextInput {
* The number of decimal places to allow, or null to allow any number of
* decimal digits.
*/
private decimalPlaces_: number | null = null;
private decimalPlaces_: number|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -69,9 +69,9 @@ export class FieldNumber extends FieldTextInput {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | number | Sentinel, opt_min?: string | number | null,
opt_max?: string | number | null, opt_precision?: string | number | null,
opt_validator?: Function | null, opt_config?: AnyDuringMigration) {
opt_value?: string|number|Sentinel, opt_min?: string|number|null,
opt_max?: string|number|null, opt_precision?: string|number|null,
opt_validator?: Function|null, opt_config?: AnyDuringMigration) {
// Pass SENTINEL so that we can define properties before value validation.
super(Field.SKIP_SETUP);
@@ -113,8 +113,8 @@ export class FieldNumber extends FieldTextInput {
* @param precision Precision for value.
*/
setConstraints(
min: number | string | undefined | null, max: number | string | undefined | null,
precision: number | string | undefined | null) {
min: number|string|undefined|null, max: number|string|undefined|null,
precision: number|string|undefined|null) {
this.setMinInternal_(min);
this.setMaxInternal_(max);
this.setPrecisionInternal_(precision);
@@ -126,7 +126,7 @@ export class FieldNumber extends FieldTextInput {
* reflect.
* @param min Minimum value.
*/
setMin(min: number | string | undefined | null) {
setMin(min: number|string|undefined|null) {
this.setMinInternal_(min);
this.setValue(this.getValue());
}
@@ -136,7 +136,7 @@ export class FieldNumber extends FieldTextInput {
* value updates.
* @param min Minimum value.
*/
private setMinInternal_(min: number | string | undefined | null) {
private setMinInternal_(min: number|string|undefined|null) {
if (min == null) {
this.min_ = -Infinity;
} else {
@@ -161,7 +161,7 @@ export class FieldNumber extends FieldTextInput {
* reflect.
* @param max Maximum value.
*/
setMax(max: number | string | undefined | null) {
setMax(max: number|string|undefined|null) {
this.setMaxInternal_(max);
this.setValue(this.getValue());
}
@@ -171,7 +171,7 @@ export class FieldNumber extends FieldTextInput {
* value updates.
* @param max Maximum value.
*/
private setMaxInternal_(max: number | string | undefined | null) {
private setMaxInternal_(max: number|string|undefined|null) {
if (max == null) {
this.max_ = Infinity;
} else {
@@ -196,7 +196,7 @@ export class FieldNumber extends FieldTextInput {
* value is rounded. Updates the field to reflect.
* @param precision The number to which the field's value is rounded.
*/
setPrecision(precision: number | string | undefined | null) {
setPrecision(precision: number|string|undefined|null) {
this.setPrecisionInternal_(precision);
this.setValue(this.getValue());
}
@@ -206,14 +206,14 @@ export class FieldNumber extends FieldTextInput {
* value updates.
* @param precision The number to which the field's value is rounded.
*/
private setPrecisionInternal_(precision: number | string | undefined | null) {
private setPrecisionInternal_(precision: number|string|undefined|null) {
this.precision_ = Number(precision) || 0;
let precisionString = String(this.precision_);
if (precisionString.indexOf('e') !== -1) {
// String() is fast. But it turns .0000001 into '1e-7'.
// Use the much slower toLocaleString to access all the digits.
precisionString =
this.precision_.toLocaleString('en-US', { maximumFractionDigits: 20 });
this.precision_.toLocaleString('en-US', {maximumFractionDigits: 20});
}
const decimalIndex = precisionString.indexOf('.');
if (decimalIndex === -1) {
@@ -242,7 +242,7 @@ export class FieldNumber extends FieldTextInput {
* @return A valid number, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
number | null {
number|null {
if (opt_newValue === null) {
return null;
}
@@ -302,7 +302,7 @@ export class FieldNumber extends FieldTextInput {
// `this` might be a subclass of FieldNumber if that class doesn't override
// the static fromJson method.
return new this(
options['value'], undefined, undefined, undefined, undefined, options);
options['value'], undefined, undefined, undefined, undefined, options);
}
}
+10 -10
View File
@@ -19,9 +19,9 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import {Field} from './field.js';
/* eslint-disable-next-line no-unused-vars */
import { IRegistrableField } from './interfaces/i_registrable_field.js';
import {IRegistrableField} from './interfaces/i_registrable_field.js';
import * as registry from './registry.js';
@@ -59,17 +59,17 @@ export function unregister(type: string) {
* type name
* @alias Blockly.fieldRegistry.fromJson
*/
export function fromJson(options: AnyDuringMigration): Field | null {
export function fromJson(options: AnyDuringMigration): Field|null {
const fieldObject =
registry.getObject(registry.Type.FIELD, options['type']) as
IRegistrableField |
null;
registry.getObject(registry.Type.FIELD, options['type']) as
IRegistrableField |
null;
if (!fieldObject) {
console.warn(
'Blockly could not create a field of type ' + options['type'] +
'. The field is probably not being registered. This could be because' +
' the file is not loaded, the field does not register itself (Issue' +
' #1584), or the registration is not being reached.');
'Blockly could not create a field of type ' + options['type'] +
'. The field is probably not being registered. This could be because' +
' the file is not loaded, the field does not register itself (Issue' +
' #1584), or the registration is not being reached.');
return null;
}
return fieldObject.fromJson(options);
+39 -39
View File
@@ -16,25 +16,25 @@
import './events/events_block_change';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as dialog from './dialog.js';
import * as dropDownDiv from './dropdowndiv.js';
import * as eventUtils from './events/utils.js';
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { Msg } from './msg.js';
import {Msg} from './msg.js';
import * as aria from './utils/aria.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import { KeyCodes } from './utils/keycodes.js';
import {KeyCodes} from './utils/keycodes.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import {Sentinel} from './utils/sentinel.js';
import * as userAgent from './utils/useragent.js';
import * as WidgetDiv from './widgetdiv.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -43,7 +43,7 @@ import { WorkspaceSvg } from './workspace_svg.js';
*/
export class FieldTextInput extends Field {
/** The default value for this field. */
protected override DEFAULT_VALUE: string | number = '';
protected override DEFAULT_VALUE: string|number = '';
/**
* Pixel size of input border radius.
@@ -55,7 +55,7 @@ export class FieldTextInput extends Field {
protected spellcheck_ = true;
/** The HTML input element. */
protected htmlInput_: HTMLInputElement | null = null;
protected htmlInput_: HTMLInputElement|null = null;
/** True if the field's value is currently being edited via the UI. */
protected isBeingEdited_ = false;
@@ -66,19 +66,19 @@ export class FieldTextInput extends Field {
protected isTextValid_ = false;
/** Key down event data. */
private onKeyDownWrapper_: browserEvents.Data | null = null;
private onKeyDownWrapper_: browserEvents.Data|null = null;
/** Key input event data. */
private onKeyInputWrapper_: browserEvents.Data | null = null;
private onKeyInputWrapper_: browserEvents.Data|null = null;
/**
* Whether the field should consider the whole parent block to be its click
* target.
*/
fullBlockClickTarget_: boolean | null = false;
fullBlockClickTarget_: boolean|null = false;
/** The workspace that this field belongs to. */
protected workspace_: WorkspaceSvg | null = null;
protected workspace_: WorkspaceSvg|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -107,8 +107,8 @@ export class FieldTextInput extends Field {
* for a list of properties this parameter supports.
*/
constructor(
opt_value?: string | Sentinel, opt_validator?: Function | null,
opt_config?: AnyDuringMigration) {
opt_value?: string|Sentinel, opt_validator?: Function|null,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
if (opt_value === Field.SKIP_SETUP) {
@@ -148,7 +148,7 @@ export class FieldTextInput extends Field {
// The special case is when this is the only non-label field on the block
// and it has an output but no inputs.
this.fullBlockClickTarget_ =
nFields <= 1 && this.sourceBlock_.outputConnection && !nConnections;
nFields <= 1 && this.sourceBlock_.outputConnection && !nConnections;
} else {
this.fullBlockClickTarget_ = false;
}
@@ -167,7 +167,7 @@ export class FieldTextInput extends Field {
* @return A valid string, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
AnyDuringMigration {
AnyDuringMigration {
if (opt_newValue === null || opt_newValue === undefined) {
return null;
}
@@ -190,8 +190,8 @@ export class FieldTextInput extends Field {
this.value_ = this.htmlInput_!.getAttribute('data-untyped-default-value');
if (this.sourceBlock_ && eventUtils.isEnabled()) {
eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))!
(this.sourceBlock_, 'field', this.name || null,
oldValue, this.value_));
(this.sourceBlock_, 'field', this.name || null,
oldValue, this.value_));
}
}
}
@@ -217,11 +217,11 @@ export class FieldTextInput extends Field {
if (this.sourceBlock_ && this.getConstants()!.FULL_BLOCK_FIELDS) {
if (this.borderRect_) {
this.borderRect_.setAttribute(
'stroke', (this.sourceBlock_ as BlockSvg).style.colourTertiary);
'stroke', (this.sourceBlock_ as BlockSvg).style.colourTertiary);
} else {
(this.sourceBlock_ as BlockSvg)
.pathObject.svgPath.setAttribute(
'fill', this.getConstants()!.FIELD_BORDER_RECT_COLOUR);
.pathObject.svgPath.setAttribute(
'fill', this.getConstants()!.FIELD_BORDER_RECT_COLOUR);
}
}
}
@@ -260,7 +260,7 @@ export class FieldTextInput extends Field {
// AnyDuringMigration because: Argument of type 'boolean' is not
// assignable to parameter of type 'string'.
this.htmlInput_.setAttribute(
'spellcheck', this.spellcheck_ as AnyDuringMigration);
'spellcheck', this.spellcheck_ as AnyDuringMigration);
}
}
@@ -275,7 +275,7 @@ export class FieldTextInput extends Field {
this.workspace_ = (this.sourceBlock_ as BlockSvg).workspace;
const quietInput = opt_quietInput || false;
if (!quietInput &&
(userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD)) {
(userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD)) {
this.showPromptEditor_();
} else {
this.showInlineEditor_(quietInput);
@@ -288,12 +288,12 @@ export class FieldTextInput extends Field {
*/
private showPromptEditor_() {
dialog.prompt(
Msg['CHANGE_VALUE_TITLE'], this.getText(), (text: string | null) => {
// Text is null if user pressed cancel button.
if (text !== null) {
this.setValue(this.getValueFromEditorText_(text));
}
});
Msg['CHANGE_VALUE_TITLE'], this.getText(), (text: string|null) => {
// Text is null if user pressed cancel button.
if (text !== null) {
this.setValue(this.getValueFromEditorText_(text));
}
});
}
/**
@@ -328,7 +328,7 @@ export class FieldTextInput extends Field {
// AnyDuringMigration because: Argument of type 'boolean' is not assignable
// to parameter of type 'string'.
htmlInput.setAttribute(
'spellcheck', this.spellcheck_ as AnyDuringMigration);
'spellcheck', this.spellcheck_ as AnyDuringMigration);
const scale = this.workspace_!.getScale();
const fontSize = this.getConstants()!.FIELD_TEXT_FONTSIZE * scale + 'pt';
div!.style.fontSize = fontSize;
@@ -342,14 +342,14 @@ export class FieldTextInput extends Field {
borderRadius = (bBox.bottom - bBox.top) / 2 + 'px';
// Pull stroke colour from the existing shadow block
const strokeColour = this.sourceBlock_.getParent() ?
(this.sourceBlock_.getParent() as BlockSvg).style.colourTertiary :
(this.sourceBlock_ as BlockSvg).style.colourTertiary;
(this.sourceBlock_.getParent() as BlockSvg).style.colourTertiary :
(this.sourceBlock_ as BlockSvg).style.colourTertiary;
htmlInput.style.border = 1 * scale + 'px solid ' + strokeColour;
div!.style.borderRadius = borderRadius;
div!.style.transition = 'box-shadow 0.25s ease 0s';
if (this.getConstants()!.FIELD_TEXTINPUT_BOX_SHADOW) {
div!.style.boxShadow =
'rgba(255, 255, 255, 0.3) 0 0 0 ' + 4 * scale + 'px';
'rgba(255, 255, 255, 0.3) 0 0 0 ' + 4 * scale + 'px';
}
}
htmlInput.style.borderRadius = borderRadius;
@@ -408,10 +408,10 @@ export class FieldTextInput extends Field {
protected bindInputEvents_(htmlInput: HTMLElement) {
// Trap Enter without IME and Esc to hide.
this.onKeyDownWrapper_ = browserEvents.conditionalBind(
htmlInput, 'keydown', this, this.onHtmlInputKeyDown_);
htmlInput, 'keydown', this, this.onHtmlInputKeyDown_);
// Resize after every input change.
this.onKeyInputWrapper_ = browserEvents.conditionalBind(
htmlInput, 'input', this, this.onHtmlInputChange_);
htmlInput, 'input', this, this.onHtmlInputChange_);
}
/** Unbind handlers for user input and workspace size changes. */
@@ -440,7 +440,7 @@ export class FieldTextInput extends Field {
// 'Event'.
} else if ((e as AnyDuringMigration).keyCode === KeyCodes.ESC) {
this.setValue(
this.htmlInput_!.getAttribute('data-untyped-default-value'));
this.htmlInput_!.getAttribute('data-untyped-default-value'));
WidgetDiv.hide();
dropDownDiv.hideWithoutAnimation();
// AnyDuringMigration because: Property 'keyCode' does not exist on type
@@ -452,7 +452,7 @@ export class FieldTextInput extends Field {
// 'Event'. AnyDuringMigration because: Argument of type 'this' is not
// assignable to parameter of type 'Field'.
(this.sourceBlock_ as BlockSvg)
.tab(this as AnyDuringMigration, !(e as AnyDuringMigration).shiftKey);
.tab(this as AnyDuringMigration, !(e as AnyDuringMigration).shiftKey);
e.preventDefault();
}
}
@@ -522,7 +522,7 @@ export class FieldTextInput extends Field {
* behaviour (which is a string cast of the field's value).
* @return The HTML value if we're editing, otherwise null.
*/
protected override getText_(): string | null {
protected override getText_(): string|null {
if (this.isBeingEdited_ && this.htmlInput_) {
// We are currently editing, return the HTML input value instead.
return this.htmlInput_.value;
+48 -48
View File
@@ -15,21 +15,21 @@
import './events/events_block_change';
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import { Field } from './field.js';
import { FieldDropdown } from './field_dropdown.js';
import {Block} from './block.js';
import {Field} from './field.js';
import {FieldDropdown} from './field_dropdown.js';
import * as fieldRegistry from './field_registry.js';
import * as internalConstants from './internal_constants.js';
/* eslint-disable-next-line no-unused-vars */
import { Menu } from './menu.js';
import {Menu} from './menu.js';
/* eslint-disable-next-line no-unused-vars */
import { MenuItem } from './menuitem.js';
import { Msg } from './msg.js';
import {MenuItem} from './menuitem.js';
import {Msg} from './msg.js';
import * as parsing from './utils/parsing.js';
/* eslint-disable-next-line no-unused-vars */
import { Sentinel } from './utils/sentinel.js';
import { Size } from './utils/size.js';
import { VariableModel } from './variable_model.js';
import {Sentinel} from './utils/sentinel.js';
import {Size} from './utils/size.js';
import {VariableModel} from './variable_model.js';
import * as Variables from './variables.js';
import * as Xml from './xml.js';
@@ -39,8 +39,8 @@ import * as Xml from './xml.js';
* @alias Blockly.FieldVariable
*/
export class FieldVariable extends FieldDropdown {
protected override menuGenerator_: AnyDuringMigration[][] |
((this: FieldDropdown) => AnyDuringMigration[][]);
protected override menuGenerator_: AnyDuringMigration[][]|
((this: FieldDropdown) => AnyDuringMigration[][]);
defaultVariableName: string;
/** The type of the default variable for this field. */
@@ -50,11 +50,11 @@ export class FieldVariable extends FieldDropdown {
* All of the types of variables that will be available in this field's
* dropdown.
*/
variableTypes: string[] | null = [];
variableTypes: string[]|null = [];
protected override size_: Size;
/** The variable model associated with this field. */
private variable_: VariableModel | null = null;
private variable_: VariableModel|null = null;
/**
* Serializable fields are saved by the serializer, non-serializable fields
@@ -82,9 +82,9 @@ export class FieldVariable extends FieldDropdown {
* for a list of properties this parameter supports.
*/
constructor(
varName: string | null | Sentinel, opt_validator?: Function,
opt_variableTypes?: string[], opt_defaultType?: string,
opt_config?: AnyDuringMigration) {
varName: string|null|Sentinel, opt_validator?: Function,
opt_variableTypes?: string[], opt_defaultType?: string,
opt_config?: AnyDuringMigration) {
super(Field.SKIP_SETUP);
/**
@@ -139,16 +139,16 @@ export class FieldVariable extends FieldDropdown {
}
// Initialization already happened.
const variable = Variables.getOrCreateVariablePackage(
this.sourceBlock_.workspace, null, this.defaultVariableName,
this.defaultType_);
this.sourceBlock_.workspace, null, this.defaultVariableName,
this.defaultType_);
// Don't call setValue because we don't want to cause a rerender.
this.doValueUpdate_(variable.getId());
}
override shouldAddBorderRect_() {
return super.shouldAddBorderRect_() &&
(!this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW ||
this.sourceBlock_.type !== 'variables_get');
(!this.getConstants()!.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW ||
this.sourceBlock_.type !== 'variables_get');
}
/**
@@ -162,21 +162,21 @@ export class FieldVariable extends FieldDropdown {
// 'variabletype' should be lowercase, but until July 2019 it was sometimes
// recorded as 'variableType'. Thus we need to check for both.
const variableType = fieldElement.getAttribute('variabletype') ||
fieldElement.getAttribute('variableType') || '';
fieldElement.getAttribute('variableType') || '';
// AnyDuringMigration because: Argument of type 'string | null' is not
// assignable to parameter of type 'string | undefined'.
const variable = Variables.getOrCreateVariablePackage(
this.sourceBlock_.workspace, id, variableName as AnyDuringMigration,
variableType);
this.sourceBlock_.workspace, id, variableName as AnyDuringMigration,
variableType);
// This should never happen :)
if (variableType !== null && variableType !== variable.type) {
throw Error(
'Serialized variable type with id \'' + variable.getId() +
'\' had type ' + variable.type + ', and ' +
'does not match variable field that references it: ' +
Xml.domToText(fieldElement) + '.');
'Serialized variable type with id \'' + variable.getId() +
'\' had type ' + variable.type + ', and ' +
'does not match variable field that references it: ' +
Xml.domToText(fieldElement) + '.');
}
this.setValue(variable.getId());
@@ -214,7 +214,7 @@ export class FieldVariable extends FieldDropdown {
}
// Make sure the variable is initialized.
this.initModel();
const state = { 'id': this.variable_!.getId() };
const state = {'id': this.variable_!.getId()};
if (doFullSerialization) {
(state as AnyDuringMigration)['name'] = this.variable_!.name;
(state as AnyDuringMigration)['type'] = this.variable_!.type;
@@ -232,8 +232,8 @@ export class FieldVariable extends FieldDropdown {
}
// This is necessary so that blocks in the flyout can have custom var names.
const variable = Variables.getOrCreateVariablePackage(
this.sourceBlock_.workspace, state['id'] || null, state['name'],
state['type'] || '');
this.sourceBlock_.workspace, state['id'] || null, state['name'],
state['type'] || '');
this.setValue(variable.getId());
}
@@ -252,7 +252,7 @@ export class FieldVariable extends FieldDropdown {
* Get the variable's ID.
* @return Current variable's ID.
*/
override getValue(): string | null {
override getValue(): string|null {
return this.variable_ ? this.variable_.getId() : null;
}
@@ -271,7 +271,7 @@ export class FieldVariable extends FieldDropdown {
* after the variable has been deleted).
* @return The selected variable, or null if none was selected.
*/
getVariable(): VariableModel | null {
getVariable(): VariableModel|null {
return this.variable_;
}
@@ -282,7 +282,7 @@ export class FieldVariable extends FieldDropdown {
* a block and workspace at that point.
* @return Validation function, or null.
*/
override getValidator(): Function | null {
override getValidator(): Function|null {
// Validators shouldn't operate on the initial setValue call.
// Normally this is achieved by calling setValidator after setValue, but
// this is not a possibility with variable fields.
@@ -298,7 +298,7 @@ export class FieldVariable extends FieldDropdown {
* @return The validated ID, or null if invalid.
*/
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
string | null {
string|null {
if (opt_newValue === null) {
return null;
}
@@ -306,15 +306,15 @@ export class FieldVariable extends FieldDropdown {
const variable = Variables.getVariable(this.sourceBlock_.workspace, newId);
if (!variable) {
console.warn(
'Variable id doesn\'t point to a real variable! ' +
'ID was ' + newId);
'Variable id doesn\'t point to a real variable! ' +
'ID was ' + newId);
return null;
}
// Type Checks.
const type = variable.type;
if (!this.typeIsAllowed_(type)) {
console.warn(
'Variable type doesn\'t match this field! Type was ' + type);
'Variable type doesn\'t match this field! Type was ' + type);
return null;
}
return newId;
@@ -329,7 +329,7 @@ export class FieldVariable extends FieldDropdown {
*/
protected override doValueUpdate_(newId: AnyDuringMigration) {
this.variable_ =
Variables.getVariable(this.sourceBlock_.workspace, newId as string);
Variables.getVariable(this.sourceBlock_.workspace, newId as string);
super.doValueUpdate_(newId);
}
@@ -371,7 +371,7 @@ export class FieldVariable extends FieldDropdown {
// Throw an error if variableTypes is an empty list.
const name = this.getText();
throw Error(
'\'variableTypes\' of field variable ' + name + ' was an empty list');
'\'variableTypes\' of field variable ' + name + ' was an empty list');
}
return variableTypes;
}
@@ -405,13 +405,13 @@ export class FieldVariable extends FieldDropdown {
}
if (!isInArray) {
throw Error(
'Invalid default type \'' + defaultType + '\' in ' +
'the definition of a FieldVariable');
'Invalid default type \'' + defaultType + '\' in ' +
'the definition of a FieldVariable');
}
} else {
throw Error(
'\'variableTypes\' was not an array in the definition of ' +
'a FieldVariable');
'\'variableTypes\' was not an array in the definition of ' +
'a FieldVariable');
}
// Only update the field once all checks pass.
this.defaultType_ = defaultType;
@@ -441,7 +441,7 @@ export class FieldVariable extends FieldDropdown {
if (id === internalConstants.RENAME_VARIABLE_ID) {
// Rename variable.
Variables.renameVariable(
this.sourceBlock_.workspace, this.variable_ as VariableModel);
this.sourceBlock_.workspace, this.variable_ as VariableModel);
return;
} else if (id === internalConstants.DELETE_VARIABLE_ID) {
// Delete variable.
@@ -485,8 +485,8 @@ export class FieldVariable extends FieldDropdown {
static dropdownCreate(this: FieldVariable): AnyDuringMigration[][] {
if (!this.variable_) {
throw Error(
'Tried to call dropdownCreate on a variable field with no' +
' variable selected.');
'Tried to call dropdownCreate on a variable field with no' +
' variable selected.');
}
const name = this.getText();
let variableModelList: AnyDuringMigration[] = [];
@@ -497,7 +497,7 @@ export class FieldVariable extends FieldDropdown {
for (let i = 0; i < variableTypes.length; i++) {
const variableType = variableTypes[i];
const variables =
this.sourceBlock_.workspace.getVariablesOfType(variableType);
this.sourceBlock_.workspace.getVariablesOfType(variableType);
variableModelList = variableModelList.concat(variables);
}
}
@@ -509,7 +509,7 @@ export class FieldVariable extends FieldDropdown {
options[i] = [variableModelList[i].name, variableModelList[i].getId()];
}
options.push(
[Msg['RENAME_VARIABLE'], internalConstants.RENAME_VARIABLE_ID]);
[Msg['RENAME_VARIABLE'], internalConstants.RENAME_VARIABLE_ID]);
if (Msg['DELETE_VARIABLE']) {
options.push([
Msg['DELETE_VARIABLE'].replace('%1', name),
+82 -81
View File
@@ -34,38 +34,38 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import {Block} from './block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import * as common from './common.js';
import { ComponentManager } from './component_manager.js';
import { DeleteArea } from './delete_area.js';
import {ComponentManager} from './component_manager.js';
import {DeleteArea} from './delete_area.js';
import * as BlockCreate from './events/events_block_create.js';
import * as VarCreate from './events/events_var_create.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { FlyoutButton } from './flyout_button.js';
import { FlyoutMetricsManager } from './flyout_metrics_manager.js';
import {FlyoutButton} from './flyout_button.js';
import {FlyoutMetricsManager} from './flyout_metrics_manager.js';
import * as Gesture from './gesture.js';
/* eslint-disable-next-line no-unused-vars */
import { IFlyout } from './interfaces/i_flyout.js';
import {IFlyout} from './interfaces/i_flyout.js';
/* eslint-disable-next-line no-unused-vars */
import { Options } from './options.js';
import {Options} from './options.js';
import * as blockRendering from './renderers/common/block_rendering.js';
import { ScrollbarPair } from './scrollbar_pair.js';
import {ScrollbarPair} from './scrollbar_pair.js';
import * as blocks from './serialization/blocks.js';
import * as Tooltip from './tooltip.js';
import * as Touch from './touch.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as idGenerator from './utils/idgenerator.js';
/* eslint-disable-next-line no-unused-vars */
import { Rect } from './utils/rect.js';
import { Svg } from './utils/svg.js';
import {Rect} from './utils/rect.js';
import {Svg} from './utils/svg.js';
import * as toolbox from './utils/toolbox.js';
import * as Variables from './variables.js';
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
import * as Xml from './xml.js';
@@ -100,7 +100,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* between 0 and 1 specifying the degree of scrolling and a
* similar x property.
*/
protected abstract setMetrics_(xyRatio: { x: number, y: number }): void;
protected abstract setMetrics_(xyRatio: {x: number, y: number}): void;
/**
* Lay out the blocks in the flyout.
@@ -161,14 +161,14 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* Function that will be registered as a change listener on the workspace
* to reflow when blocks in the flyout workspace change.
*/
private reflowWrapper_: Function | null = null;
private reflowWrapper_: Function|null = null;
/**
* Function that disables blocks in the flyout based on max block counts
* allowed in the target workspace. Registered as a change listener on the
* target workspace.
*/
private filterWrapper_: Function | null = null;
private filterWrapper_: Function|null = null;
/**
* List of background mats that lurk behind each block to catch clicks
@@ -259,12 +259,12 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* The path around the background of the flyout, which will be filled with a
* background colour.
*/
protected svgBackground_: SVGPathElement | null = null;
protected svgBackground_: SVGPathElement|null = null;
/**
* The root SVG group for the button or label.
*/
protected svgGroup_: SVGGElement | null = null;
protected svgGroup_: SVGGElement|null = null;
/**
* @param workspaceOptions Dictionary of options for the
* workspace.
@@ -275,7 +275,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
this.workspace_ = new WorkspaceSvg(workspaceOptions);
this.workspace_.setMetricsManager(
new FlyoutMetricsManager(this.workspace_, this));
new FlyoutMetricsManager(this.workspace_, this));
this.workspace_.isFlyout = true;
// Keep the workspace visibility consistent with the flyout's visibility.
@@ -335,7 +335,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* put the flyout in. This should be <svg> or <g>.
* @return The flyout's SVG group.
*/
createDom(tagName: string | Svg<SVGSVGElement> | Svg<SVGGElement>): SVGElement {
createDom(tagName: string|Svg<SVGSVGElement>|Svg<SVGGElement>): SVGElement {
/*
<svg | g>
<path class="blocklyFlyoutBackground"/>
@@ -345,14 +345,14 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
// Setting style to display:none to start. The toolbox and flyout
// hide/show code will set up proper visibility and size later.
this.svgGroup_ = dom.createSvgElement(
tagName, { 'class': 'blocklyFlyout', 'style': 'display: none' });
tagName, {'class': 'blocklyFlyout', 'style': 'display: none'});
this.svgBackground_ = dom.createSvgElement(
Svg.PATH, { 'class': 'blocklyFlyoutBackground' }, this.svgGroup_);
Svg.PATH, {'class': 'blocklyFlyoutBackground'}, this.svgGroup_);
this.svgGroup_.appendChild(this.workspace_.createDom());
this.workspace_.getThemeManager().subscribe(
this.svgBackground_, 'flyoutBackgroundColour', 'fill');
this.svgBackground_, 'flyoutBackgroundColour', 'fill');
this.workspace_.getThemeManager().subscribe(
this.svgBackground_, 'flyoutOpacity', 'fill-opacity');
this.svgBackground_, 'flyoutOpacity', 'fill-opacity');
return this.svgGroup_;
}
@@ -366,15 +366,15 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
this.workspace_.targetWorkspace = targetWorkspace;
this.workspace_.scrollbar = new ScrollbarPair(
this.workspace_, this.horizontalLayout, !this.horizontalLayout,
'blocklyFlyoutScrollbar', this.SCROLLBAR_MARGIN);
this.workspace_, this.horizontalLayout, !this.horizontalLayout,
'blocklyFlyoutScrollbar', this.SCROLLBAR_MARGIN);
this.hide();
Array.prototype.push.apply(
this.eventWrappers_,
browserEvents.conditionalBind(
(this.svgGroup_ as SVGGElement), 'wheel', this, this.wheel_));
this.eventWrappers_,
browserEvents.conditionalBind(
(this.svgGroup_ as SVGGElement), 'wheel', this, this.wheel_));
if (!this.autoClose) {
this.filterWrapper_ = this.filterForCapacity_.bind(this);
this.targetWorkspace.addChangeListener(this.filterWrapper_);
@@ -382,14 +382,14 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
// Dragging the flyout up and down.
Array.prototype.push.apply(
this.eventWrappers_,
browserEvents.conditionalBind(
(this.svgBackground_ as SVGPathElement), 'mousedown', this,
this.onMouseDown_));
this.eventWrappers_,
browserEvents.conditionalBind(
(this.svgBackground_ as SVGPathElement), 'mousedown', this,
this.onMouseDown_));
// A flyout connected to a workspace doesn't have its own current gesture.
this.workspace_.getGesture =
this.targetWorkspace.getGesture.bind(this.targetWorkspace);
this.targetWorkspace.getGesture.bind(this.targetWorkspace);
// Get variables from the main workspace rather than the target workspace.
this.workspace_.setVariableMap(this.targetWorkspace.getVariableMap());
@@ -554,11 +554,11 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
// reposition in resize, we need to call setPosition. See issue #4692.
if (scrollbar.hScroll) {
scrollbar.hScroll.setPosition(
scrollbar.hScroll.position.x, scrollbar.hScroll.position.y);
scrollbar.hScroll.position.x, scrollbar.hScroll.position.y);
}
if (scrollbar.vScroll) {
scrollbar.vScroll.setPosition(
scrollbar.vScroll.position.x, scrollbar.vScroll.position.y);
scrollbar.vScroll.position.x, scrollbar.vScroll.position.y);
}
}
}
@@ -590,7 +590,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* in the flyout. This is either an array of Nodes, a NodeList, a
* toolbox definition, or a string with the name of the dynamic category.
*/
show(flyoutDef: toolbox.FlyoutDefinition | string) {
show(flyoutDef: toolbox.FlyoutDefinition|string) {
this.workspace_.setResizesEnabled(false);
this.hide();
this.clearOldBlocks_();
@@ -617,8 +617,8 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
}
this.listeners_.push(browserEvents.conditionalBind(
(this.svgBackground_ as SVGPathElement), 'mouseover', this,
deselectAll));
(this.svgBackground_ as SVGPathElement), 'mouseover', this,
deselectAll));
if (this.horizontalLayout) {
this.height_ = 0;
@@ -645,7 +645,8 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* of objects to show in the flyout.
* @return The list of contents and gaps needed to lay out the flyout.
*/
private createFlyoutInfo_(parsedContent: toolbox.FlyoutItemInfoArray): { contents: FlyoutItem[], gaps: number[] } {
private createFlyoutInfo_(parsedContent: toolbox.FlyoutItemInfoArray):
{contents: FlyoutItem[], gaps: number[]} {
const contents: FlyoutItem[] = [];
const gaps: number[] = [];
this.permanentlyDisabled_.length = 0;
@@ -656,10 +657,10 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
const categoryName = customInfo['custom'];
const flyoutDef = this.getDynamicCategoryContents_(categoryName);
const parsedDynamicContent =
toolbox.convertFlyoutDefToJsonArray(flyoutDef);
toolbox.convertFlyoutDefToJsonArray(flyoutDef);
// Replace the element at i with the dynamic content it represents.
parsedContent.splice.apply(
parsedContent, [i, 1, ...parsedDynamicContent]);
parsedContent, [i, 1, ...parsedDynamicContent]);
contentInfo = parsedContent[i];
}
@@ -667,7 +668,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
case 'BLOCK': {
const blockInfo = (contentInfo as toolbox.BlockInfo);
const block = this.createFlyoutBlock_(blockInfo);
contents.push({ type: FlyoutItemType.BLOCK, block: block });
contents.push({type: FlyoutItemType.BLOCK, block: block});
this.addBlockGap_(blockInfo, gaps, defaultGap);
break;
}
@@ -680,20 +681,20 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
const labelInfo = (contentInfo as toolbox.LabelInfo);
// A label is a button with different styling.
const label = this.createButton_(labelInfo, /** isLabel */ true);
contents.push({ type: FlyoutItemType.BUTTON, button: label });
contents.push({type: FlyoutItemType.BUTTON, button: label});
gaps.push(defaultGap);
break;
}
case 'BUTTON': {
const buttonInfo = (contentInfo as toolbox.ButtonInfo);
const button = this.createButton_(buttonInfo, /** isLabel */ false);
contents.push({ type: FlyoutItemType.BUTTON, button: button });
contents.push({type: FlyoutItemType.BUTTON, button: button});
gaps.push(defaultGap);
break;
}
}
}
return { contents: contents, gaps: gaps };
return {contents: contents, gaps: gaps};
}
/**
@@ -703,16 +704,16 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* flyout in one of its many forms.
*/
private getDynamicCategoryContents_(categoryName: string):
toolbox.FlyoutDefinition {
toolbox.FlyoutDefinition {
// Look up the correct category generation function and call that to get a
// valid XML list.
const fnToApply =
this.workspace_.targetWorkspace.getToolboxCategoryCallback(
categoryName);
this.workspace_.targetWorkspace.getToolboxCategoryCallback(
categoryName);
if (typeof fnToApply !== 'function') {
throw TypeError(
'Couldn\'t find a callback function when opening' +
' a toolbox category.');
'Couldn\'t find a callback function when opening' +
' a toolbox category.');
}
return fnToApply(this.workspace_.targetWorkspace);
}
@@ -725,10 +726,10 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* flyout.
*/
private createButton_(btnInfo: toolbox.ButtonOrLabelInfo, isLabel: boolean):
FlyoutButton {
FlyoutButton {
const curButton = new FlyoutButton(
this.workspace_, (this.targetWorkspace as WorkspaceSvg), btnInfo,
isLabel);
this.workspace_, (this.targetWorkspace as WorkspaceSvg), btnInfo,
isLabel);
return curButton;
}
@@ -742,8 +743,8 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
let block;
if (blockInfo['blockxml']) {
const xml = (typeof blockInfo['blockxml'] === 'string' ?
Xml.textToDom(blockInfo['blockxml']) :
blockInfo['blockxml']) as Element;
Xml.textToDom(blockInfo['blockxml']) :
blockInfo['blockxml']) as Element;
block = this.getRecycledBlock_(xml.getAttribute('type')!);
if (!block) {
block = Xml.domToBlock(xml, this.workspace_);
@@ -753,7 +754,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
if (!block) {
if (blockInfo['enabled'] === undefined) {
blockInfo['enabled'] = blockInfo['disabled'] !== 'true' &&
blockInfo['disabled'] !== true;
blockInfo['disabled'] !== true;
}
block = blocks.append((blockInfo as blocks.State), this.workspace_);
}
@@ -774,7 +775,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* @return The recycled block, or undefined if
* one could not be recycled.
*/
private getRecycledBlock_(blockType: string): BlockSvg | undefined {
private getRecycledBlock_(blockType: string): BlockSvg|undefined {
let index = -1;
for (let i = 0; i < this.recycledBlocks_.length; i++) {
if (this.recycledBlocks_[i].type === blockType) {
@@ -793,14 +794,14 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* next.
*/
private addBlockGap_(
blockInfo: toolbox.BlockInfo, gaps: number[], defaultGap: number) {
blockInfo: toolbox.BlockInfo, gaps: number[], defaultGap: number) {
let gap;
if (blockInfo['gap']) {
gap = parseInt(blockInfo['gap'].toString(), 10);
} else if (blockInfo['blockxml']) {
const xml = (typeof blockInfo['blockxml'] === 'string' ?
Xml.textToDom(blockInfo['blockxml']) :
blockInfo['blockxml']) as Element;
Xml.textToDom(blockInfo['blockxml']) :
blockInfo['blockxml']) as Element;
gap = parseInt(xml.getAttribute('gap')!, 10);
}
gaps.push(!gap || isNaN(gap) ? defaultGap : gap);
@@ -815,7 +816,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* element.
*/
private addSeparatorGap_(
sepInfo: toolbox.SeparatorInfo, gaps: number[], defaultGap: number) {
sepInfo: toolbox.SeparatorInfo, gaps: number[], defaultGap: number) {
// Change the gap between two toolbox elements.
// <sep gap="36"></sep>
// The default gap is 24, can be set larger or smaller.
@@ -901,19 +902,19 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* as a mat for that block.
*/
protected addBlockListeners_(
root: SVGElement, block: BlockSvg, rect: SVGElement) {
root: SVGElement, block: BlockSvg, rect: SVGElement) {
this.listeners_.push(browserEvents.conditionalBind(
root, 'mousedown', null, this.blockMouseDown_(block)));
root, 'mousedown', null, this.blockMouseDown_(block)));
this.listeners_.push(browserEvents.conditionalBind(
rect, 'mousedown', null, this.blockMouseDown_(block)));
rect, 'mousedown', null, this.blockMouseDown_(block)));
this.listeners_.push(
browserEvents.bind(root, 'mouseenter', block, block.addSelect));
browserEvents.bind(root, 'mouseenter', block, block.addSelect));
this.listeners_.push(
browserEvents.bind(root, 'mouseleave', block, block.removeSelect));
browserEvents.bind(root, 'mouseleave', block, block.removeSelect));
this.listeners_.push(
browserEvents.bind(rect, 'mouseenter', block, block.addSelect));
browserEvents.bind(rect, 'mouseenter', block, block.addSelect));
this.listeners_.push(
browserEvents.bind(rect, 'mouseleave', block, block.removeSelect));
browserEvents.bind(rect, 'mouseleave', block, block.removeSelect));
}
/**
@@ -975,7 +976,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
this.targetWorkspace.hideChaff();
const newVariables = Variables.getAddedVariables(
this.targetWorkspace, variablesBeforeCreation);
this.targetWorkspace, variablesBeforeCreation);
if (eventUtils.isEnabled()) {
eventUtils.setGroup(true);
@@ -983,7 +984,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
for (let i = 0; i < newVariables.length; i++) {
const thisVariable = newVariables[i];
eventUtils.fire(new (eventUtils.get(eventUtils.VAR_CREATE))!
(thisVariable));
(thisVariable));
}
// Block events come after var events, in case they refer to newly created
@@ -1012,7 +1013,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
// Clicking on a flyout button or label is a lot like clicking on the
// flyout background.
this.listeners_.push(browserEvents.conditionalBind(
buttonSvg, 'mousedown', this, this.onMouseDown_));
buttonSvg, 'mousedown', this, this.onMouseDown_));
this.buttons_.push(button);
}
@@ -1030,8 +1031,8 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
* the block.
*/
protected createRect_(
block: BlockSvg, x: number, y: number,
blockHW: { height: number, width: number }, index: number): SVGElement {
block: BlockSvg, x: number, y: number,
blockHW: {height: number, width: number}, index: number): SVGElement {
// Create an invisible rectangle under the block to act as a button. Just
// using the block as a button is poor, since blocks have holes in them.
const rect = dom.createSvgElement(Svg.RECT, {
@@ -1065,7 +1066,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
const blockXY = block.getRelativeToSurfaceXY();
rect.setAttribute('y', blockXY.y.toString());
rect.setAttribute(
'x', (this.RTL ? blockXY.x - blockHW.width : blockXY.x).toString());
'x', (this.RTL ? blockXY.x - blockHW.width : blockXY.x).toString());
}
/**
@@ -1079,7 +1080,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
for (let i = 0, block; block = blocks[i]; i++) {
if (this.permanentlyDisabled_.indexOf(block) === -1) {
const enable = this.targetWorkspace.isCapacityAvailable(
common.getBlockTypeCounts(block));
common.getBlockTypeCounts(block));
while (block) {
block.setEnabled(enable);
block = block.getNextBlock();
@@ -1107,7 +1108,7 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
*/
isScrollable(): boolean {
return this.workspace_.scrollbar ? this.workspace_.scrollbar.isVisible() :
false;
false;
}
/**
@@ -1158,12 +1159,12 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
// The position of the old block in pixels relative to the upper left corner
// of the injection div.
const oldBlockOffsetPixels =
Coordinate.sum(flyoutOffsetPixels, oldBlockPos);
Coordinate.sum(flyoutOffsetPixels, oldBlockPos);
// The position of the old block in pixels relative to the origin of the
// main workspace.
const finalOffset =
Coordinate.difference(oldBlockOffsetPixels, mainOffsetPixels);
Coordinate.difference(oldBlockOffsetPixels, mainOffsetPixels);
// The position of the old block in main workspace coordinates.
finalOffset.scale(1 / targetWorkspace.scale);
@@ -1176,6 +1177,6 @@ export abstract class Flyout extends DeleteArea implements IFlyout {
*/
export interface FlyoutItem {
type: FlyoutItemType;
button?: FlyoutButton | undefined;
block?: BlockSvg | undefined;
button?: FlyoutButton|undefined;
block?: BlockSvg|undefined;
}
+51 -51
View File
@@ -14,15 +14,15 @@
import * as browserEvents from './browser_events.js';
import * as Css from './css.js';
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import * as parsing from './utils/parsing.js';
import * as style from './utils/style.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
/* eslint-disable-next-line no-unused-vars */
import * as toolbox from './utils/toolbox.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -38,10 +38,10 @@ export class FlyoutButton {
private readonly text_: string;
private readonly position_: Coordinate;
private readonly callbackKey_: string;
private readonly cssClass_: string | null;
private readonly cssClass_: string|null;
/** Mouse up event data. */
private onMouseUpWrapper_: browserEvents.Data | null = null;
private onMouseUpWrapper_: browserEvents.Data|null = null;
info: toolbox.ButtonOrLabelInfo;
/** The width of the button's rect. */
@@ -51,10 +51,10 @@ export class FlyoutButton {
height = 0;
/** The root SVG group for the button or label. */
private svgGroup_: SVGGElement | null = null;
private svgGroup_: SVGGElement|null = null;
/** The SVG element with the text of the label or button. */
private svgText_: SVGTextElement | null = null;
private svgText_: SVGTextElement|null = null;
/**
* @param workspace The workspace in which to place this button.
@@ -63,19 +63,19 @@ export class FlyoutButton {
* @param isLabel Whether this button should be styled as a label.
*/
constructor(
private readonly workspace: WorkspaceSvg,
private readonly targetWorkspace: WorkspaceSvg,
json: toolbox.ButtonOrLabelInfo, private readonly isLabel_: boolean) {
private readonly workspace: WorkspaceSvg,
private readonly targetWorkspace: WorkspaceSvg,
json: toolbox.ButtonOrLabelInfo, private readonly isLabel_: boolean) {
this.text_ = json['text'];
this.position_ = new Coordinate(0, 0);
/** The key to the function called when this button is clicked. */
this.callbackKey_ =
(json as
AnyDuringMigration)['callbackKey'] || /* Check the lower case version
too to satisfy IE */
(json as AnyDuringMigration)['callbackkey'];
(json as
AnyDuringMigration)['callbackKey'] || /* Check the lower case version
too to satisfy IE */
(json as AnyDuringMigration)['callbackkey'];
/** If specified, a CSS class to add to this button. */
this.cssClass_ = (json as AnyDuringMigration)['web-class'] || null;
@@ -95,39 +95,39 @@ export class FlyoutButton {
}
this.svgGroup_ = dom.createSvgElement(
Svg.G, { 'class': cssClass }, this.workspace.getCanvas());
Svg.G, {'class': cssClass}, this.workspace.getCanvas());
let shadow;
if (!this.isLabel_) {
// Shadow rectangle (light source does not mirror in RTL).
shadow = dom.createSvgElement(
Svg.RECT, {
'class': 'blocklyFlyoutButtonShadow',
'rx': 4,
'ry': 4,
'x': 1,
'y': 1,
},
this.svgGroup_!);
Svg.RECT, {
'class': 'blocklyFlyoutButtonShadow',
'rx': 4,
'ry': 4,
'x': 1,
'y': 1,
},
this.svgGroup_!);
}
// Background rectangle.
const rect = dom.createSvgElement(
Svg.RECT, {
'class': this.isLabel_ ? 'blocklyFlyoutLabelBackground' :
'blocklyFlyoutButtonBackground',
'rx': 4,
'ry': 4,
},
this.svgGroup_!);
Svg.RECT, {
'class': this.isLabel_ ? 'blocklyFlyoutLabelBackground' :
'blocklyFlyoutButtonBackground',
'rx': 4,
'ry': 4,
},
this.svgGroup_!);
const svgText = dom.createSvgElement(
Svg.TEXT, {
'class': this.isLabel_ ? 'blocklyFlyoutLabelText' : 'blocklyText',
'x': 0,
'y': 0,
'text-anchor': 'middle',
},
this.svgGroup_!);
Svg.TEXT, {
'class': this.isLabel_ ? 'blocklyFlyoutLabelText' : 'blocklyText',
'x': 0,
'y': 0,
'text-anchor': 'middle',
},
this.svgGroup_!);
let text = parsing.replaceMessageReferences(this.text_);
if (this.workspace.RTL) {
// Force text to be RTL by adding an RLM.
@@ -137,16 +137,16 @@ export class FlyoutButton {
if (this.isLabel_) {
this.svgText_ = svgText;
this.workspace.getThemeManager().subscribe(
this.svgText_, 'flyoutForegroundColour', 'fill');
this.svgText_, 'flyoutForegroundColour', 'fill');
}
const fontSize = style.getComputedStyle(svgText, 'fontSize');
const fontWeight = style.getComputedStyle(svgText, 'fontWeight');
const fontFamily = style.getComputedStyle(svgText, 'fontFamily');
this.width = dom.getFastTextWidthWithSizeString(
svgText, fontSize, fontWeight, fontFamily);
svgText, fontSize, fontWeight, fontFamily);
const fontMetrics =
dom.measureFontMetrics(text, fontSize, fontWeight, fontFamily);
dom.measureFontMetrics(text, fontSize, fontWeight, fontFamily);
this.height = fontMetrics.height;
if (!this.isLabel_) {
@@ -160,16 +160,16 @@ export class FlyoutButton {
svgText.setAttribute('x', (this.width / 2).toString());
svgText.setAttribute(
'y',
(this.height / 2 - fontMetrics.height / 2 + fontMetrics.baseline)
.toString());
'y',
(this.height / 2 - fontMetrics.height / 2 + fontMetrics.baseline)
.toString());
this.updateTransform_();
// AnyDuringMigration because: Argument of type 'SVGGElement | null' is not
// assignable to parameter of type 'EventTarget'.
this.onMouseUpWrapper_ = browserEvents.conditionalBind(
this.svgGroup_ as AnyDuringMigration, 'mouseup', this, this.onMouseUp_);
this.svgGroup_ as AnyDuringMigration, 'mouseup', this, this.onMouseUp_);
return this.svgGroup_!;
}
@@ -182,8 +182,8 @@ export class FlyoutButton {
/** Update SVG attributes to match internal state. */
private updateTransform_() {
this.svgGroup_!.setAttribute(
'transform',
'translate(' + this.position_.x + ',' + this.position_.y + ')');
'transform',
'translate(' + this.position_.x + ',' + this.position_.y + ')');
}
/**
@@ -248,15 +248,15 @@ export class FlyoutButton {
if (this.isLabel_ && this.callbackKey_) {
console.warn(
'Labels should not have callbacks. Label text: ' + this.text_);
'Labels should not have callbacks. Label text: ' + this.text_);
} else if (
!this.isLabel_ &&
!(this.callbackKey_ &&
this.targetWorkspace.getButtonCallback(this.callbackKey_))) {
!this.isLabel_ &&
!(this.callbackKey_ &&
this.targetWorkspace.getButtonCallback(this.callbackKey_))) {
console.warn('Buttons should have callbacks. Button text: ' + this.text_);
} else if (!this.isLabel_) {
const callback =
this.targetWorkspace.getButtonCallback(this.callbackKey_);
this.targetWorkspace.getButtonCallback(this.callbackKey_);
if (callback) {
callback(this);
}
+30 -30
View File
@@ -16,16 +16,16 @@
import * as browserEvents from './browser_events.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Flyout, FlyoutItem } from './flyout_base.js';
import {Flyout, FlyoutItem} from './flyout_base.js';
/* eslint-disable-next-line no-unused-vars */
import { FlyoutButton } from './flyout_button.js';
import {FlyoutButton} from './flyout_button.js';
/* eslint-disable-next-line no-unused-vars */
import { Options } from './options.js';
import {Options} from './options.js';
import * as registry from './registry.js';
import { Scrollbar } from './scrollbar.js';
import {Scrollbar} from './scrollbar.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import { Rect } from './utils/rect.js';
import {Coordinate} from './utils/coordinate.js';
import {Rect} from './utils/rect.js';
import * as toolbox from './utils/toolbox.js';
import * as WidgetDiv from './widgetdiv.js';
@@ -52,7 +52,7 @@ export class HorizontalFlyout extends Flyout {
* @param xyRatio Contains a y property which is a float between 0 and 1
* specifying the degree of scrolling and a similar x property.
*/
protected override setMetrics_(xyRatio: { x: number, y: number }) {
protected override setMetrics_(xyRatio: {x: number, y: number}) {
if (!this.isVisible()) {
return;
}
@@ -64,13 +64,13 @@ export class HorizontalFlyout extends Flyout {
if (typeof xyRatio.x === 'number') {
this.workspace_.scrollX =
-(scrollMetrics.left +
(scrollMetrics.width - viewMetrics.width) * xyRatio.x);
-(scrollMetrics.left +
(scrollMetrics.width - viewMetrics.width) * xyRatio.x);
}
this.workspace_.translate(
this.workspace_.scrollX + absoluteMetrics.left,
this.workspace_.scrollY + absoluteMetrics.top);
this.workspace_.scrollX + absoluteMetrics.left,
this.workspace_.scrollY + absoluteMetrics.top);
}
/**
@@ -158,7 +158,7 @@ export class HorizontalFlyout extends Flyout {
private setBackgroundPath_(width: number, height: number) {
const atTop = this.toolboxPosition_ === toolbox.Position.TOP;
// Start at top left.
const path: (string | number)[] = ['M 0,' + (atTop ? 0 : this.CORNER_RADIUS)];
const path: (string|number)[] = ['M 0,' + (atTop ? 0 : this.CORNER_RADIUS)];
if (atTop) {
// Top.
@@ -167,24 +167,24 @@ export class HorizontalFlyout extends Flyout {
path.push('v', height);
// Bottom.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
-this.CORNER_RADIUS, this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
-this.CORNER_RADIUS, this.CORNER_RADIUS);
path.push('h', -width);
// Left.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
-this.CORNER_RADIUS, -this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
-this.CORNER_RADIUS, -this.CORNER_RADIUS);
path.push('z');
} else {
// Top.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
this.CORNER_RADIUS, -this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
this.CORNER_RADIUS, -this.CORNER_RADIUS);
path.push('h', width);
// Right.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
this.CORNER_RADIUS, this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, 1,
this.CORNER_RADIUS, this.CORNER_RADIUS);
path.push('v', height);
// Bottom.
path.push('h', -width - 2 * this.CORNER_RADIUS);
@@ -265,7 +265,7 @@ export class HorizontalFlyout extends Flyout {
// AnyDuringMigration because: Argument of type 'BlockSvg | undefined'
// is not assignable to parameter of type 'BlockSvg'.
const rect = this.createRect_(
block as AnyDuringMigration, moveX, cursorY, blockHW, i);
block as AnyDuringMigration, moveX, cursorY, blockHW, i);
cursorX += blockHW.width + gaps[i];
// AnyDuringMigration because: Argument of type 'BlockSvg | undefined'
@@ -296,7 +296,7 @@ export class HorizontalFlyout extends Flyout {
const range = this.dragAngleRange_;
// Check for up or down dragging.
if (dragDirection < 90 + range && dragDirection > 90 - range ||
dragDirection > -90 - range && dragDirection < -90 + range) {
dragDirection > -90 - range && dragDirection < -90 + range) {
return true;
}
return false;
@@ -308,7 +308,7 @@ export class HorizontalFlyout extends Flyout {
* @return The component's bounding box. Null if drag target area should be
* ignored.
*/
override getClientRect(): Rect | null {
override getClientRect(): Rect|null {
if (!this.svgGroup_ || this.autoClose || !this.isVisible()) {
// The bounding rectangle won't compute correctly if the flyout is closed
// and auto-close flyouts aren't valid drag targets (or delete areas).
@@ -357,19 +357,19 @@ export class HorizontalFlyout extends Flyout {
// AnyDuringMigration because: Argument of type 'SVGElement |
// undefined' is not assignable to parameter of type 'SVGElement'.
this.moveRectToBlock_(
this.rectMap_.get(block) as AnyDuringMigration, block);
this.rectMap_.get(block) as AnyDuringMigration, block);
}
}
if (this.targetWorkspace!.toolboxPosition === this.toolboxPosition_ &&
this.toolboxPosition_ === toolbox.Position.TOP &&
!this.targetWorkspace!.getToolbox()) {
this.toolboxPosition_ === toolbox.Position.TOP &&
!this.targetWorkspace!.getToolbox()) {
// This flyout is a simple toolbox. Reposition the workspace so that
// (0,0) is in the correct position relative to the new absolute edge
// (ie toolbox edge).
this.targetWorkspace!.translate(
this.targetWorkspace!.scrollX,
this.targetWorkspace!.scrollY + flyoutHeight);
this.targetWorkspace!.scrollX,
this.targetWorkspace!.scrollY + flyoutHeight);
}
this.height_ = flyoutHeight;
this.position();
@@ -379,5 +379,5 @@ export class HorizontalFlyout extends Flyout {
}
registry.register(
registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX, registry.DEFAULT,
HorizontalFlyout);
registry.Type.FLYOUTS_HORIZONTAL_TOOLBOX, registry.DEFAULT,
HorizontalFlyout);
+9 -9
View File
@@ -13,10 +13,10 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { IFlyout } from './interfaces/i_flyout.js';
import { ContainerRegion, MetricsManager } from './metrics_manager.js';
import {IFlyout} from './interfaces/i_flyout.js';
import {ContainerRegion, MetricsManager} from './metrics_manager.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -38,8 +38,8 @@ export class FlyoutMetricsManager extends MetricsManager {
* This is in workspace coordinates.
* @return The bounding box of the blocks on the workspace.
*/
private getBoundingBox_(): SVGRect |
{ height: number, y: number, width: number, x: number } {
private getBoundingBox_(): SVGRect|
{height: number, y: number, width: number, x: number} {
let blockBoundingBox;
try {
blockBoundingBox = this.workspace.getCanvas().getBBox();
@@ -47,7 +47,7 @@ export class FlyoutMetricsManager extends MetricsManager {
// Firefox has trouble with hidden elements (Bug 528969).
// 2021 Update: It looks like this was fixed around Firefox 77 released in
// 2020.
blockBoundingBox = { height: 0, y: 0, width: 0, x: 0 };
blockBoundingBox = {height: 0, y: 0, width: 0, x: 0};
}
return blockBoundingBox;
}
@@ -66,11 +66,11 @@ export class FlyoutMetricsManager extends MetricsManager {
}
override getScrollMetrics(
opt_getWorkspaceCoordinates: boolean, opt_viewMetrics: ContainerRegion,
opt_contentMetrics: ContainerRegion) {
opt_getWorkspaceCoordinates: boolean, opt_viewMetrics: ContainerRegion,
opt_contentMetrics: ContainerRegion) {
// AnyDuringMigration because: Expected 1 arguments, but got 0.
const contentMetrics =
opt_contentMetrics || (this.getContentMetrics as AnyDuringMigration)();
opt_contentMetrics || (this.getContentMetrics as AnyDuringMigration)();
const margin = this.flyout.MARGIN * this.workspace.scale;
const scale = opt_getWorkspaceCoordinates ? this.workspace.scale : 1;
+30 -30
View File
@@ -19,16 +19,16 @@ import './constants';
import * as browserEvents from './browser_events.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Flyout, FlyoutItem } from './flyout_base.js';
import {Flyout, FlyoutItem} from './flyout_base.js';
/* eslint-disable-next-line no-unused-vars */
import { FlyoutButton } from './flyout_button.js';
import {FlyoutButton} from './flyout_button.js';
/* eslint-disable-next-line no-unused-vars */
import { Options } from './options.js';
import {Options} from './options.js';
import * as registry from './registry.js';
import { Scrollbar } from './scrollbar.js';
import {Scrollbar} from './scrollbar.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import { Rect } from './utils/rect.js';
import {Coordinate} from './utils/coordinate.js';
import {Rect} from './utils/rect.js';
import * as toolbox from './utils/toolbox.js';
import * as WidgetDiv from './widgetdiv.js';
@@ -57,7 +57,7 @@ export class VerticalFlyout extends Flyout {
* @param xyRatio Contains a y property which is a float between 0 and 1
* specifying the degree of scrolling and a similar x property.
*/
protected override setMetrics_(xyRatio: { x: number, y: number }) {
protected override setMetrics_(xyRatio: {x: number, y: number}) {
if (!this.isVisible()) {
return;
}
@@ -68,12 +68,12 @@ export class VerticalFlyout extends Flyout {
if (typeof xyRatio.y === 'number') {
this.workspace_.scrollY =
-(scrollMetrics.top +
(scrollMetrics.height - viewMetrics.height) * xyRatio.y);
-(scrollMetrics.top +
(scrollMetrics.height - viewMetrics.height) * xyRatio.y);
}
this.workspace_.translate(
this.workspace_.scrollX + absoluteMetrics.left,
this.workspace_.scrollY + absoluteMetrics.top);
this.workspace_.scrollX + absoluteMetrics.left,
this.workspace_.scrollY + absoluteMetrics.top);
}
/**
@@ -144,7 +144,7 @@ export class VerticalFlyout extends Flyout {
const edgeWidth = this.width_ - this.CORNER_RADIUS;
const edgeHeight =
targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS;
targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS;
this.setBackgroundPath_(edgeWidth, edgeHeight);
const x = this.getX();
@@ -163,20 +163,20 @@ export class VerticalFlyout extends Flyout {
const totalWidth = width + this.CORNER_RADIUS;
// Decide whether to start on the left or right.
const path: Array<string | number> =
['M ' + (atRight ? totalWidth : 0) + ',0'];
const path: Array<string|number> =
['M ' + (atRight ? totalWidth : 0) + ',0'];
// Top.
path.push('h', (atRight ? -width : width));
// Rounded corner.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS, this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS, this.CORNER_RADIUS);
// Side closest to workspace.
path.push('v', Math.max(0, height));
// Rounded corner.
path.push(
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS, this.CORNER_RADIUS);
'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS, this.CORNER_RADIUS);
// Bottom.
path.push('h', (atRight ? width : -width));
path.push('z');
@@ -238,14 +238,14 @@ export class VerticalFlyout extends Flyout {
const root = block!.getSvgRoot();
const blockHW = block!.getHeightWidth();
const moveX =
block!.outputConnection ? cursorX - this.tabWidth_ : cursorX;
block!.outputConnection ? cursorX - this.tabWidth_ : cursorX;
block!.moveBy(moveX, cursorY);
// AnyDuringMigration because: Argument of type 'BlockSvg | undefined'
// is not assignable to parameter of type 'BlockSvg'.
const rect = this.createRect_(
block as AnyDuringMigration,
this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, i);
block as AnyDuringMigration,
this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, i);
// AnyDuringMigration because: Argument of type 'BlockSvg | undefined'
// is not assignable to parameter of type 'BlockSvg'.
@@ -277,7 +277,7 @@ export class VerticalFlyout extends Flyout {
const range = this.dragAngleRange_;
// Check for left or right dragging.
if (dragDirection < range && dragDirection > -range ||
(dragDirection < -180 + range || dragDirection > 180 - range)) {
(dragDirection < -180 + range || dragDirection > 180 - range)) {
return true;
}
return false;
@@ -289,7 +289,7 @@ export class VerticalFlyout extends Flyout {
* @return The component's bounding box. Null if drag target area should be
* ignored.
*/
override getClientRect(): Rect | null {
override getClientRect(): Rect|null {
if (!this.svgGroup_ || this.autoClose || !this.isVisible()) {
// The bounding rectangle won't compute correctly if the flyout is closed
// and auto-close flyouts aren't valid drag targets (or delete areas).
@@ -350,7 +350,7 @@ export class VerticalFlyout extends Flyout {
// AnyDuringMigration because: Argument of type 'SVGElement |
// undefined' is not assignable to parameter of type 'SVGElement'.
this.moveRectToBlock_(
this.rectMap_.get(block) as AnyDuringMigration, block);
this.rectMap_.get(block) as AnyDuringMigration, block);
}
}
if (this.RTL) {
@@ -358,20 +358,20 @@ export class VerticalFlyout extends Flyout {
for (let i = 0, button; button = this.buttons_[i]; i++) {
const y = button.getPosition().y;
const x = flyoutWidth / this.workspace_.scale - button.width -
this.MARGIN - this.tabWidth_;
this.MARGIN - this.tabWidth_;
button.moveTo(x, y);
}
}
if (this.targetWorkspace!.toolboxPosition === this.toolboxPosition_ &&
this.toolboxPosition_ === toolbox.Position.LEFT &&
!this.targetWorkspace!.getToolbox()) {
this.toolboxPosition_ === toolbox.Position.LEFT &&
!this.targetWorkspace!.getToolbox()) {
// This flyout is a simple toolbox. Reposition the workspace so that
// (0,0) is in the correct position relative to the new absolute edge
// (ie toolbox edge).
this.targetWorkspace!.translate(
this.targetWorkspace!.scrollX + flyoutWidth,
this.targetWorkspace!.scrollY);
this.targetWorkspace!.scrollX + flyoutWidth,
this.targetWorkspace!.scrollY);
}
this.width_ = flyoutWidth;
this.position();
@@ -381,4 +381,4 @@ export class VerticalFlyout extends Flyout {
}
registry.register(
registry.Type.FLYOUTS_VERTICAL_TOOLBOX, registry.DEFAULT, VerticalFlyout);
registry.Type.FLYOUTS_VERTICAL_TOOLBOX, registry.DEFAULT, VerticalFlyout);
+35 -35
View File
@@ -17,13 +17,13 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import {Block} from './block.js';
import * as common from './common.js';
/* eslint-disable-next-line no-unused-vars */
import { Names, NameType } from './names.js';
import {Names, NameType} from './names.js';
import * as deprecation from './utils/deprecation.js';
/* eslint-disable-next-line no-unused-vars */
import { Workspace } from './workspace.js';
import {Workspace} from './workspace.js';
/**
@@ -48,21 +48,21 @@ export class Generator {
* Any instances of '%1' will be replaced by the block ID that failed.
* E.g. ' checkTimeout(%1);\n'
*/
INFINITE_LOOP_TRAP: string | null = null;
INFINITE_LOOP_TRAP: string|null = null;
/**
* Arbitrary code to inject before every statement.
* Any instances of '%1' will be replaced by the block ID of the statement.
* E.g. 'highlight(%1);\n'
*/
STATEMENT_PREFIX: string | null = null;
STATEMENT_PREFIX: string|null = null;
/**
* Arbitrary code to inject after every statement.
* Any instances of '%1' will be replaced by the block ID of the statement.
* E.g. 'highlight(%1);\n'
*/
STATEMENT_SUFFIX: string | null = null;
STATEMENT_SUFFIX: string|null = null;
/**
* The method of indenting. Defaults to two spaces, but language generators
@@ -85,7 +85,7 @@ export class Generator {
* will cause blockToCode to emit a warning if the generator has not been
* initialized. If this flag is untouched, it will have no effect.
*/
isInitialized: boolean | null = null;
isInitialized: boolean|null = null;
/** Comma-separated list of reserved words. */
protected RESERVED_WORDS_ = '';
@@ -107,7 +107,7 @@ export class Generator {
this.name_ = name;
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_ =
new RegExp(this.FUNCTION_NAME_PLACEHOLDER_, 'g');
new RegExp(this.FUNCTION_NAME_PLACEHOLDER_, 'g');
}
/**
@@ -119,7 +119,7 @@ export class Generator {
if (!workspace) {
// Backwards compatibility from before there could be multiple workspaces.
console.warn(
'No workspace specified in workspaceToCode call. Guessing.');
'No workspace specified in workspaceToCode call. Guessing.');
workspace = common.getMainWorkspace();
}
let code = [];
@@ -211,11 +211,11 @@ export class Generator {
* For value blocks, an array containing the generated code and an
* operator order value. Returns '' if block is null.
*/
blockToCode(block: Block | null, opt_thisOnly?: boolean): string
| AnyDuringMigration[] {
blockToCode(block: Block|null, opt_thisOnly?: boolean): string
|AnyDuringMigration[] {
if (this.isInitialized === false) {
console.warn(
'Generator init was not called before blockToCode was called.');
'Generator init was not called before blockToCode was called.');
}
if (!block) {
return '';
@@ -232,8 +232,8 @@ export class Generator {
const func = (this as AnyDuringMigration)[block.type];
if (typeof func !== 'function') {
throw Error(
'Language "' + this.name_ + '" does not know how to generate ' +
'code for block type "' + block.type + '".');
'Language "' + this.name_ + '" does not know how to generate ' +
'code for block type "' + block.type + '".');
}
// First argument to func.call is the value of 'this' in the generator.
// Prior to 24 September 2013 'this' was the only way to access the block.
@@ -293,7 +293,7 @@ export class Generator {
const innerOrder = tuple[1];
if (isNaN(innerOrder)) {
throw TypeError(
'Expecting valid order from value block: ' + targetBlock.type);
'Expecting valid order from value block: ' + targetBlock.type);
}
if (!code) {
return '';
@@ -309,7 +309,7 @@ export class Generator {
// In all known languages multiple such code blocks are not order
// sensitive. In fact in Python ('a' 'b') 'c' would fail.
if (outerOrderClass === innerOrderClass &&
(outerOrderClass === 0 || outerOrderClass === 99)) {
(outerOrderClass === 0 || outerOrderClass === 99)) {
} else {
// The operators outside this code are stronger than the operators
// inside this code. To prevent the code from being pulled apart,
@@ -318,7 +318,7 @@ export class Generator {
// Check for special exceptions.
for (let i = 0; i < this.ORDER_OVERRIDES.length; i++) {
if (this.ORDER_OVERRIDES[i][0] === outerOrder &&
this.ORDER_OVERRIDES[i][1] === innerOrder) {
this.ORDER_OVERRIDES[i][1] === innerOrder) {
parensNeeded = false;
break;
}
@@ -349,8 +349,8 @@ export class Generator {
// Statement blocks must only return code.
if (typeof code !== 'string') {
throw TypeError(
'Expecting code from statement block: ' +
(targetBlock && targetBlock.type));
'Expecting code from statement block: ' +
(targetBlock && targetBlock.type));
}
if (code) {
code = this.prefixLines((code), this.INDENT);
@@ -370,18 +370,18 @@ export class Generator {
addLoopTrap(branch: string, block: Block): string {
if (this.INFINITE_LOOP_TRAP) {
branch = this.prefixLines(
this.injectId(this.INFINITE_LOOP_TRAP, block), this.INDENT) +
branch;
this.injectId(this.INFINITE_LOOP_TRAP, block), this.INDENT) +
branch;
}
if (this.STATEMENT_SUFFIX && !block.suppressPrefixSuffix) {
branch = this.prefixLines(
this.injectId(this.STATEMENT_SUFFIX, block), this.INDENT) +
branch;
this.injectId(this.STATEMENT_SUFFIX, block), this.INDENT) +
branch;
}
if (this.STATEMENT_PREFIX && !block.suppressPrefixSuffix) {
branch = branch +
this.prefixLines(
this.injectId(this.STATEMENT_PREFIX, block), this.INDENT);
this.prefixLines(
this.injectId(this.STATEMENT_PREFIX, block), this.INDENT);
}
return branch;
}
@@ -428,17 +428,17 @@ export class Generator {
* @return The actual name of the new function. This may differ from
* desiredName if the former has already been taken by the user.
*/
protected provideFunction_(desiredName: string, code: string[] | string):
string {
protected provideFunction_(desiredName: string, code: string[]|string):
string {
if (!this.definitions_[desiredName]) {
const functionName =
this.nameDB_!.getDistinctName(desiredName, NameType.PROCEDURE);
this.nameDB_!.getDistinctName(desiredName, NameType.PROCEDURE);
this.functionNames_[desiredName] = functionName;
if (Array.isArray(code)) {
code = code.join('\n');
}
let codeText = code.trim().replace(
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_, functionName);
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_, functionName);
// Change all ' ' indents into the desired indent.
// To avoid an infinite loop of replacements, change all indents to '\0'
// character first, then replace them all with the indent.
@@ -482,7 +482,7 @@ export class Generator {
* @return Code with comments and subsequent blocks added.
*/
protected scrub_(_block: Block, code: string, _opt_thisOnly?: boolean):
string {
string {
// Optionally override
return code;
}
@@ -528,12 +528,12 @@ Object.defineProperties(Generator.prototype, {
variableDB_: ({
/** @return Name database. */
get(this: Generator): Names |
undefined {
deprecation.warn('variableDB_', 'May 2021', 'May 2026', 'nameDB_');
return this.nameDB_;
},
undefined {
deprecation.warn('variableDB_', 'May 2021', 'May 2026', 'nameDB_');
return this.nameDB_;
},
/** @param nameDb New name database. */
set(this: Generator, nameDb: Names | undefined) {
set(this: Generator, nameDb: Names|undefined) {
deprecation.warn('variableDB_', 'May 2021', 'May 2026', 'nameDB_');
this.nameDB_ = nameDb;
},
+49 -49
View File
@@ -23,31 +23,31 @@ import './events/events_click';
import * as blockAnimations from './block_animations.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
import { BubbleDragger } from './bubble_dragger.js';
import {BubbleDragger} from './bubble_dragger.js';
import * as common from './common.js';
import { config } from './config.js';
import {config} from './config.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import {Field} from './field.js';
/* eslint-disable-next-line no-unused-vars */
import { IBlockDragger } from './interfaces/i_block_dragger.js';
import {IBlockDragger} from './interfaces/i_block_dragger.js';
/* eslint-disable-next-line no-unused-vars */
import { IBubble } from './interfaces/i_bubble.js';
import {IBubble} from './interfaces/i_bubble.js';
/* eslint-disable-next-line no-unused-vars */
import { IFlyout } from './interfaces/i_flyout.js';
import {IFlyout} from './interfaces/i_flyout.js';
import * as internalConstants from './internal_constants.js';
import * as registry from './registry.js';
import * as Tooltip from './tooltip.js';
import * as Touch from './touch.js';
import { Coordinate } from './utils/coordinate.js';
import { Workspace } from './workspace.js';
import {Coordinate} from './utils/coordinate.js';
import {Workspace} from './workspace.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceCommentSvg } from './workspace_comment_svg.js';
import { WorkspaceDragger } from './workspace_dragger.js';
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
import {WorkspaceDragger} from './workspace_dragger.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
@@ -133,13 +133,13 @@ export class Gesture {
* A handle to use to unbind a mouse move listener at the end of a drag.
* Opaque data returned from Blockly.bindEventWithChecks_.
*/
protected onMoveWrapper_: browserEvents.Data | null = null;
protected onMoveWrapper_: browserEvents.Data|null = null;
/**
* A handle to use to unbind a mouse up listener at the end of a drag.
* Opaque data returned from Blockly.bindEventWithChecks_.
*/
protected onUpWrapper_: browserEvents.Data | null = null;
protected onUpWrapper_: browserEvents.Data|null = null;
/** The object tracking a bubble drag, or null if none is in progress. */
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -147,7 +147,7 @@ export class Gesture {
private bubbleDragger_: BubbleDragger = null as AnyDuringMigration;
/** The object tracking a block drag, or null if none is in progress. */
private blockDragger_: IBlockDragger | null = null;
private blockDragger_: IBlockDragger|null = null;
/**
* The object tracking a workspace or flyout workspace drag, or null if none
@@ -178,7 +178,7 @@ export class Gesture {
* reference to it.
*/
constructor(
private e: Event, private readonly creatorWorkspace: WorkspaceSvg) {
private e: Event, private readonly creatorWorkspace: WorkspaceSvg) {
/**
* How far the mouse has moved during this drag, in pixel units.
* (0, 0) is at this.mouseDownXY_.
@@ -226,7 +226,7 @@ export class Gesture {
// 'Event'. AnyDuringMigration because: Property 'clientX' does not exist
// on type 'Event'.
const currentXY = new Coordinate(
(e as AnyDuringMigration).clientX, (e as AnyDuringMigration).clientY);
(e as AnyDuringMigration).clientX, (e as AnyDuringMigration).clientY);
const changed = this.updateDragDelta_(currentXY);
// Exceeded the drag radius for the first time.
if (changed) {
@@ -244,14 +244,14 @@ export class Gesture {
*/
private updateDragDelta_(currentXY: Coordinate): boolean {
this.currentDragDeltaXY_ =
Coordinate.difference(currentXY, (this.mouseDownXY_));
Coordinate.difference(currentXY, (this.mouseDownXY_));
if (!this.hasExceededDragRadius_) {
const currentDragDelta = Coordinate.magnitude(this.currentDragDeltaXY_);
// The flyout has a different drag radius from the rest of Blockly.
const limitRadius =
this.flyout_ ? config.flyoutDragRadius : config.dragRadius;
this.flyout_ ? config.flyoutDragRadius : config.dragRadius;
this.hasExceededDragRadius_ = currentDragDelta > limitRadius;
return this.hasExceededDragRadius_;
@@ -277,7 +277,7 @@ export class Gesture {
return false;
}
if (!this.flyout_.isScrollable() ||
this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)) {
this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)) {
// AnyDuringMigration because: Type 'WorkspaceSvg | null' is not
// assignable to type 'WorkspaceSvg'.
this.startWorkspace_ = this.flyout_.targetWorkspace as AnyDuringMigration;
@@ -352,8 +352,8 @@ export class Gesture {
*/
private updateIsDraggingWorkspace_() {
const wsMovable = this.flyout_ ?
this.flyout_.isScrollable() :
this.startWorkspace_ && this.startWorkspace_.isDraggable();
this.flyout_.isScrollable() :
this.startWorkspace_ && this.startWorkspace_.isDraggable();
if (!wsMovable) {
return;
@@ -394,10 +394,10 @@ export class Gesture {
/** Create a block dragger and start dragging the selected block. */
private startDraggingBlock_() {
const BlockDraggerClass = registry.getClassFromOptions(
registry.Type.BLOCK_DRAGGER, this.creatorWorkspace.options, true);
registry.Type.BLOCK_DRAGGER, this.creatorWorkspace.options, true);
this.blockDragger_ =
new BlockDraggerClass!((this.targetBlock_), (this.startWorkspace_));
new BlockDraggerClass!((this.targetBlock_), (this.startWorkspace_));
this.blockDragger_!.startDrag(this.currentDragDeltaXY_, this.healStack_);
this.blockDragger_!.drag(this.e, this.currentDragDeltaXY_);
}
@@ -406,7 +406,7 @@ export class Gesture {
/** Create a bubble dragger and start dragging the selected bubble. */
private startDraggingBubble_() {
this.bubbleDragger_ =
new BubbleDragger((this.startBubble_), (this.startWorkspace_));
new BubbleDragger((this.startBubble_), (this.startWorkspace_));
this.bubbleDragger_.startBubbleDrag();
this.bubbleDragger_.dragBubble(this.e, this.currentDragDeltaXY_);
}
@@ -451,8 +451,8 @@ export class Gesture {
// TODO(#6097): Make types accurate, possibly by refactoring touch handling.
const typelessEvent = e as AnyDuringMigration;
if ((e.type.toLowerCase() === 'touchstart' ||
e.type.toLowerCase() === 'pointerdown') &&
typelessEvent.pointerType !== 'mouse') {
e.type.toLowerCase() === 'pointerdown') &&
typelessEvent.pointerType !== 'mouse') {
Touch.longStart(typelessEvent, this);
}
@@ -460,13 +460,13 @@ export class Gesture {
// 'Event'. AnyDuringMigration because: Property 'clientX' does not exist
// on type 'Event'.
this.mouseDownXY_ = new Coordinate(
(e as AnyDuringMigration).clientX, (e as AnyDuringMigration).clientY);
(e as AnyDuringMigration).clientX, (e as AnyDuringMigration).clientY);
// AnyDuringMigration because: Property 'metaKey' does not exist on type
// 'Event'. AnyDuringMigration because: Property 'ctrlKey' does not exist
// on type 'Event'. AnyDuringMigration because: Property 'altKey' does not
// exist on type 'Event'.
this.healStack_ = (e as AnyDuringMigration).altKey ||
(e as AnyDuringMigration).ctrlKey || (e as AnyDuringMigration).metaKey;
(e as AnyDuringMigration).ctrlKey || (e as AnyDuringMigration).metaKey;
this.bindMouseEvents(e);
}
@@ -477,9 +477,9 @@ export class Gesture {
*/
bindMouseEvents(e: Event) {
this.onMoveWrapper_ = browserEvents.conditionalBind(
document, 'mousemove', null, this.handleMove.bind(this));
document, 'mousemove', null, this.handleMove.bind(this));
this.onUpWrapper_ = browserEvents.conditionalBind(
document, 'mouseup', null, this.handleUp.bind(this));
document, 'mouseup', null, this.handleUp.bind(this));
e.preventDefault();
e.stopPropagation();
@@ -596,8 +596,8 @@ export class Gesture {
handleWsStart(e: Event, ws: WorkspaceSvg) {
if (this.hasStarted_) {
throw Error(
'Tried to call gesture.handleWsStart, ' +
'but the gesture had already been started.');
'Tried to call gesture.handleWsStart, ' +
'but the gesture had already been started.');
}
this.setStartWorkspace_(ws);
this.e = e;
@@ -610,7 +610,7 @@ export class Gesture {
*/
private fireWorkspaceClick_(ws: WorkspaceSvg) {
eventUtils.fire(new (eventUtils.get(eventUtils.CLICK))!
(null, ws.id, 'workspace'));
(null, ws.id, 'workspace'));
}
/**
@@ -621,8 +621,8 @@ export class Gesture {
handleFlyoutStart(e: Event, flyout: IFlyout) {
if (this.hasStarted_) {
throw Error(
'Tried to call gesture.handleFlyoutStart, ' +
'but the gesture had already been started.');
'Tried to call gesture.handleFlyoutStart, ' +
'but the gesture had already been started.');
}
this.setStartFlyout_(flyout);
this.handleWsStart(e, flyout.getWorkspace());
@@ -636,8 +636,8 @@ export class Gesture {
handleBlockStart(e: Event, block: BlockSvg) {
if (this.hasStarted_) {
throw Error(
'Tried to call gesture.handleBlockStart, ' +
'but the gesture had already been started.');
'Tried to call gesture.handleBlockStart, ' +
'but the gesture had already been started.');
}
this.setStartBlock(block);
this.e = e;
@@ -651,8 +651,8 @@ export class Gesture {
handleBubbleStart(e: Event, bubble: IBubble) {
if (this.hasStarted_) {
throw Error(
'Tried to call gesture.handleBubbleStart, ' +
'but the gesture had already been started.');
'Tried to call gesture.handleBubbleStart, ' +
'but the gesture had already been started.');
}
this.setStartBubble(bubble);
this.e = e;
@@ -691,7 +691,7 @@ export class Gesture {
} else {
// Clicks events are on the start block, even if it was a shadow.
const event = new (eventUtils.get(eventUtils.CLICK))!
(this.startBlock_, this.startWorkspace_.id, 'block');
(this.startBlock_, this.startWorkspace_.id, 'block');
eventUtils.fire(event);
}
this.bringBlockToFront_();
@@ -736,8 +736,8 @@ export class Gesture {
setStartField(field: Field) {
if (this.hasStarted_) {
throw Error(
'Tried to call gesture.setStartField, ' +
'but the gesture had already been started.');
'Tried to call gesture.setStartField, ' +
'but the gesture had already been started.');
}
if (!this.startField_) {
this.startField_ = field;
@@ -833,7 +833,7 @@ export class Gesture {
// not a field click.
const hasStartBlock = !!this.startBlock_;
return hasStartBlock && !this.hasExceededDragRadius_ &&
!this.isFieldClick_();
!this.isFieldClick_();
}
/**
@@ -843,9 +843,9 @@ export class Gesture {
*/
private isFieldClick_(): boolean {
const fieldClickable =
this.startField_ ? this.startField_.isClickable() : false;
this.startField_ ? this.startField_.isClickable() : false;
return fieldClickable && !this.hasExceededDragRadius_ &&
(!this.flyout_ || !this.flyout_.autoClose);
(!this.flyout_ || !this.flyout_.autoClose);
}
/**
@@ -855,7 +855,7 @@ export class Gesture {
*/
private isWorkspaceClick_(): boolean {
const onlyTouchedWorkspace =
!this.startBlock_ && !this.startBubble_ && !this.startField_;
!this.startBlock_ && !this.startBubble_ && !this.startField_;
return onlyTouchedWorkspace && !this.hasExceededDragRadius_;
}
@@ -869,7 +869,7 @@ export class Gesture {
*/
isDragging(): boolean {
return this.isDraggingWorkspace_ || this.isDraggingBlock_ ||
this.isDraggingBubble_;
this.isDraggingBubble_;
}
/**
@@ -900,7 +900,7 @@ export class Gesture {
* @return The dragger that is currently in use or null if no drag is in
* progress.
*/
getCurrentDragger(): WorkspaceDragger | BubbleDragger | IBlockDragger | null {
getCurrentDragger(): WorkspaceDragger|BubbleDragger|IBlockDragger|null {
if (this.isDraggingBlock_) {
return this.blockDragger_;
} else if (this.isDraggingWorkspace_) {
+10 -10
View File
@@ -17,7 +17,7 @@
*/
import * as dom from './utils/dom.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
@@ -134,8 +134,8 @@ export class Grid {
* @param y2 The new y end position of the line (in px).
*/
private setLineAttributes_(
line: SVGElement, width: number, x1: number, x2: number, y1: number,
y2: number) {
line: SVGElement, width: number, x1: number, x2: number, y1: number,
y2: number) {
if (line) {
// AnyDuringMigration because: Argument of type 'number' is not
// assignable to parameter of type 'string'.
@@ -184,8 +184,8 @@ export class Grid {
* @return The SVG element for the grid pattern.
*/
static createDom(
rnd: string, gridOptions: AnyDuringMigration,
defs: SVGElement): SVGElement {
rnd: string, gridOptions: AnyDuringMigration,
defs: SVGElement): SVGElement {
/*
<pattern id="blocklyGridPattern837493" patternUnits="userSpaceOnUse">
<rect stroke="#888" />
@@ -193,16 +193,16 @@ export class Grid {
</pattern>
*/
const gridPattern = dom.createSvgElement(
Svg.PATTERN,
{ 'id': 'blocklyGridPattern' + rnd, 'patternUnits': 'userSpaceOnUse' },
defs);
Svg.PATTERN,
{'id': 'blocklyGridPattern' + rnd, 'patternUnits': 'userSpaceOnUse'},
defs);
// x1, y1, x1, x2 properties will be set later in update.
if (gridOptions['length'] > 0 && gridOptions['spacing'] > 0) {
dom.createSvgElement(
Svg.LINE, { 'stroke': gridOptions['colour'] }, gridPattern);
Svg.LINE, {'stroke': gridOptions['colour']}, gridPattern);
if (gridOptions['length'] > 1) {
dom.createSvgElement(
Svg.LINE, { 'stroke': gridOptions['colour'] }, gridPattern);
Svg.LINE, {'stroke': gridOptions['colour']}, gridPattern);
}
} else {
// Edge 16 doesn't handle empty patterns
+14 -14
View File
@@ -13,14 +13,14 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as browserEvents from './browser_events.js';
/* eslint-disable-next-line no-unused-vars */
import { Bubble } from './bubble.js';
import { Coordinate } from './utils/coordinate.js';
import {Bubble} from './bubble.js';
import {Coordinate} from './utils/coordinate.js';
import * as dom from './utils/dom.js';
import { Size } from './utils/size.js';
import { Svg } from './utils/svg.js';
import {Size} from './utils/size.js';
import {Svg} from './utils/svg.js';
import * as svgMath from './utils/svg_math.js';
@@ -31,7 +31,7 @@ import * as svgMath from './utils/svg_math.js';
export abstract class Icon {
protected block_: BlockSvg;
/** The icon SVG group. */
iconGroup_: SVGGElement | null = null;
iconGroup_: SVGGElement|null = null;
/** Whether this icon gets hidden when the block is collapsed. */
collapseHidden = true;
@@ -40,10 +40,10 @@ export abstract class Icon {
readonly SIZE = 17;
/** Bubble UI (if visible). */
protected bubble_: Bubble | null = null;
protected bubble_: Bubble|null = null;
/** Absolute coordinate of icon's center. */
protected iconXY_: Coordinate | null = null;
protected iconXY_: Coordinate|null = null;
/** @param block The block associated with this icon. */
constructor(block: BlockSvg) {
@@ -62,7 +62,7 @@ export abstract class Icon {
</g>
*/
this.iconGroup_ =
dom.createSvgElement(Svg.G, { 'class': 'blocklyIconGroup' });
dom.createSvgElement(Svg.G, {'class': 'blocklyIconGroup'});
if (this.block_.isInFlyout) {
dom.addClass(this.iconGroup_ as Element, 'blocklyIconGroupReadonly');
}
@@ -76,8 +76,8 @@ export abstract class Icon {
// AnyDuringMigration because: Argument of type 'SVGGElement | null' is not
// assignable to parameter of type 'EventTarget'.
browserEvents.conditionalBind(
this.iconGroup_ as AnyDuringMigration, 'mouseup', this,
this.iconClick_);
this.iconGroup_ as AnyDuringMigration, 'mouseup', this,
this.iconClick_);
this.updateEditable();
}
@@ -146,8 +146,8 @@ export abstract class Icon {
const blockXY = this.block_.getRelativeToSurfaceXY();
const iconXY = svgMath.getRelativeXY(this.iconGroup_ as SVGElement);
const newXY = new Coordinate(
blockXY.x + iconXY.x + this.SIZE / 2,
blockXY.y + iconXY.y + this.SIZE / 2);
blockXY.x + iconXY.x + this.SIZE / 2,
blockXY.y + iconXY.y + this.SIZE / 2);
if (!Coordinate.equals(this.getIconLocation(), newXY)) {
this.setIconLocation(newXY);
}
@@ -157,7 +157,7 @@ export abstract class Icon {
* Returns the center of the block's icon relative to the surface.
* @return Object with x and y properties in workspace coordinates.
*/
getIconLocation(): Coordinate | null {
getIconLocation(): Coordinate|null {
return this.iconXY_;
}
+75 -75
View File
@@ -14,29 +14,29 @@
import 'angular-mocks';
import { BlockDragSurfaceSvg } from './block_drag_surface.js';
import {BlockDragSurfaceSvg} from './block_drag_surface.js';
/* eslint-disable-next-line no-unused-vars */
import { BlocklyOptions } from './blockly_options.js';
import {BlocklyOptions} from './blockly_options.js';
import * as browserEvents from './browser_events.js';
import * as bumpObjects from './bump_objects.js';
import * as common from './common.js';
import * as Css from './css.js';
import * as dropDownDiv from './dropdowndiv.js';
import { Grid } from './grid.js';
import { Msg } from './msg.js';
import { Options } from './options.js';
import { ScrollbarPair } from './scrollbar_pair.js';
import { ShortcutRegistry } from './shortcut_registry.js';
import {Grid} from './grid.js';
import {Msg} from './msg.js';
import {Options} from './options.js';
import {ScrollbarPair} from './scrollbar_pair.js';
import {ShortcutRegistry} from './shortcut_registry.js';
import * as Tooltip from './tooltip.js';
import * as Touch from './touch.js';
import * as aria from './utils/aria.js';
import * as dom from './utils/dom.js';
import { Svg } from './utils/svg.js';
import {Svg} from './utils/svg.js';
import * as userAgent from './utils/useragent.js';
import * as WidgetDiv from './widgetdiv.js';
import { Workspace } from './workspace.js';
import { WorkspaceDragSurfaceSvg } from './workspace_drag_surface_svg.js';
import { WorkspaceSvg } from './workspace_svg.js';
import {Workspace} from './workspace.js';
import {WorkspaceDragSurfaceSvg} from './workspace_drag_surface_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/**
@@ -47,18 +47,18 @@ import { WorkspaceSvg } from './workspace_svg.js';
* @alias Blockly.inject
*/
export function inject(
container: Element | string, opt_options?: BlocklyOptions): WorkspaceSvg {
container: Element|string, opt_options?: BlocklyOptions): WorkspaceSvg {
if (typeof container === 'string') {
// AnyDuringMigration because: Type 'Element | null' is not assignable to
// type 'string | Element'.
container = (document.getElementById(container) ||
document.querySelector(container)) as AnyDuringMigration;
document.querySelector(container)) as AnyDuringMigration;
}
// Verify that the container is in document.
// AnyDuringMigration because: Argument of type 'string | Element' is not
// assignable to parameter of type 'Node'.
if (!container ||
!dom.containsNode(document, container as AnyDuringMigration)) {
!dom.containsNode(document, container as AnyDuringMigration)) {
throw Error('Error: container is not in current document.');
}
const options = new Options(opt_options || {} as BlocklyOptions);
@@ -79,7 +79,7 @@ export function inject(
const workspaceDragSurface = new WorkspaceDragSurfaceSvg(subContainer);
const workspace =
createMainWorkspace(svg, options, blockDragSurface, workspaceDragSurface);
createMainWorkspace(svg, options, blockDragSurface, workspaceDragSurface);
init(workspace);
@@ -91,7 +91,7 @@ export function inject(
common.svgResize(workspace);
subContainer.addEventListener('focusin', function () {
subContainer.addEventListener('focusin', function() {
// AnyDuringMigration because: Argument of type 'WorkspaceSvg' is not
// assignable to parameter of type 'Workspace'.
common.setMainWorkspace(workspace as AnyDuringMigration);
@@ -127,15 +127,15 @@ function createDom(container: Element, options: Options): Element {
</svg>
*/
const svg = dom.createSvgElement(
Svg.SVG, {
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
'version': '1.1',
'class': 'blocklySvg',
'tabindex': '0',
},
container);
Svg.SVG, {
'xmlns': dom.SVG_NS,
'xmlns:html': dom.HTML_NS,
'xmlns:xlink': dom.XLINK_NS,
'version': '1.1',
'class': 'blocklySvg',
'tabindex': '0',
},
container);
/*
<defs>
... filters go here ...
@@ -160,21 +160,21 @@ function createDom(container: Element, options: Options): Element {
* @return Newly created main workspace.
*/
function createMainWorkspace(
svg: Element, options: Options, blockDragSurface: BlockDragSurfaceSvg,
workspaceDragSurface: WorkspaceDragSurfaceSvg): WorkspaceSvg {
svg: Element, options: Options, blockDragSurface: BlockDragSurfaceSvg,
workspaceDragSurface: WorkspaceDragSurfaceSvg): WorkspaceSvg {
options.parentWorkspace = null;
const mainWorkspace =
new WorkspaceSvg(options, blockDragSurface, workspaceDragSurface);
new WorkspaceSvg(options, blockDragSurface, workspaceDragSurface);
const wsOptions = mainWorkspace.options;
mainWorkspace.scale = wsOptions.zoomOptions.startScale;
svg.appendChild(mainWorkspace.createDom('blocklyMainBackground'));
// Set the theme name and renderer name onto the injection div.
dom.addClass(
mainWorkspace.getInjectionDiv(),
mainWorkspace.getRenderer().getClassName());
mainWorkspace.getInjectionDiv(),
mainWorkspace.getRenderer().getClassName());
dom.addClass(
mainWorkspace.getInjectionDiv(), mainWorkspace.getTheme().getClassName());
mainWorkspace.getInjectionDiv(), mainWorkspace.getTheme().getClassName());
if (!wsOptions.hasCategories && wsOptions.languageTree) {
// Add flyout as an <svg> that is a sibling of the workspace SVG.
@@ -189,13 +189,13 @@ function createMainWorkspace(
}
// Register the workspace svg as a UI component.
mainWorkspace.getThemeManager().subscribe(
svg, 'workspaceBackgroundColour', 'background-color');
svg, 'workspaceBackgroundColour', 'background-color');
// A null translation will also apply the correct initial scale.
mainWorkspace.translate(0, 0);
mainWorkspace.addChangeListener(
bumpObjects.bumpIntoBoundsHandler(mainWorkspace));
bumpObjects.bumpIntoBoundsHandler(mainWorkspace));
// The SVG is now fully assembled.
common.svgResize(mainWorkspace);
@@ -215,19 +215,19 @@ function init(mainWorkspace: WorkspaceSvg) {
// Suppress the browser's context menu.
browserEvents.conditionalBind(
svg.parentNode as Element, 'contextmenu', null,
function (e: AnyDuringMigration) {
if (!browserEvents.isTargetInput(e)) {
e.preventDefault();
}
});
svg.parentNode as Element, 'contextmenu', null,
function(e: AnyDuringMigration) {
if (!browserEvents.isTargetInput(e)) {
e.preventDefault();
}
});
const workspaceResizeHandler =
browserEvents.conditionalBind(window, 'resize', null, function () {
mainWorkspace.hideChaff(true);
common.svgResize(mainWorkspace);
bumpObjects.bumpTopObjectsIntoBounds(mainWorkspace);
});
browserEvents.conditionalBind(window, 'resize', null, function() {
mainWorkspace.hideChaff(true);
common.svgResize(mainWorkspace);
bumpObjects.bumpTopObjectsIntoBounds(mainWorkspace);
});
mainWorkspace.setResizeHandlerWrapper(workspaceResizeHandler);
bindDocumentEvents();
@@ -256,15 +256,15 @@ function init(mainWorkspace: WorkspaceSvg) {
if (options.moveOptions && options.moveOptions.scrollbars) {
const horizontalScroll = options.moveOptions.scrollbars === true ||
!!options.moveOptions.scrollbars.horizontal;
!!options.moveOptions.scrollbars.horizontal;
const verticalScroll = options.moveOptions.scrollbars === true ||
!!options.moveOptions.scrollbars.vertical;
!!options.moveOptions.scrollbars.vertical;
mainWorkspace.scrollbar = new ScrollbarPair(
mainWorkspace, horizontalScroll, verticalScroll,
'blocklyMainWorkspaceScrollbar');
mainWorkspace, horizontalScroll, verticalScroll,
'blocklyMainWorkspaceScrollbar');
mainWorkspace.scrollbar.resize();
} else {
mainWorkspace.setMetrics({ x: 0.5, y: 0.5 });
mainWorkspace.setMetrics({x: 0.5, y: 0.5});
}
// Load the sounds.
@@ -287,7 +287,7 @@ function onKeyDown(e: KeyboardEvent) {
}
if (browserEvents.isTargetInput(e) ||
mainWorkspace.rendered && !mainWorkspace.isVisible()) {
mainWorkspace.rendered && !mainWorkspace.isVisible()) {
// When focused on an HTML text input widget, don't trap any keys.
// Ignore keypresses on rendered workspaces that have been explicitly
// hidden.
@@ -314,7 +314,7 @@ let documentEventsBound = false;
*/
function bindDocumentEvents() {
if (!documentEventsBound) {
browserEvents.conditionalBind(document, 'scroll', null, function () {
browserEvents.conditionalBind(document, 'scroll', null, function() {
const workspaces = Workspace.getAll();
for (let i = 0, workspace; workspace = workspaces[i]; i++) {
if (workspace instanceof WorkspaceSvg) {
@@ -330,10 +330,10 @@ function bindDocumentEvents() {
// Some iPad versions don't fire resize after portrait to landscape change.
if (userAgent.IPAD) {
browserEvents.conditionalBind(
window, 'orientationchange', document, function () {
// TODO (#397): Fix for multiple Blockly workspaces.
common.svgResize(common.getMainWorkspace() as WorkspaceSvg);
});
window, 'orientationchange', document, function() {
// TODO (#397): Fix for multiple Blockly workspaces.
common.svgResize(common.getMainWorkspace() as WorkspaceSvg);
});
}
}
documentEventsBound = true;
@@ -347,26 +347,26 @@ function bindDocumentEvents() {
function loadSounds(pathToMedia: string, workspace: WorkspaceSvg) {
const audioMgr = workspace.getAudioManager();
audioMgr.load(
[
pathToMedia + 'click.mp3',
pathToMedia + 'click.wav',
pathToMedia + 'click.ogg',
],
'click');
[
pathToMedia + 'click.mp3',
pathToMedia + 'click.wav',
pathToMedia + 'click.ogg',
],
'click');
audioMgr.load(
[
pathToMedia + 'disconnect.wav',
pathToMedia + 'disconnect.mp3',
pathToMedia + 'disconnect.ogg',
],
'disconnect');
[
pathToMedia + 'disconnect.wav',
pathToMedia + 'disconnect.mp3',
pathToMedia + 'disconnect.ogg',
],
'disconnect');
audioMgr.load(
[
pathToMedia + 'delete.mp3',
pathToMedia + 'delete.ogg',
pathToMedia + 'delete.wav',
],
'delete');
[
pathToMedia + 'delete.mp3',
pathToMedia + 'delete.ogg',
pathToMedia + 'delete.wav',
],
'delete');
// Bind temporary hooks that preload the sounds.
const soundBinds: AnyDuringMigration[] = [];
@@ -384,7 +384,7 @@ function loadSounds(pathToMedia: string, workspace: WorkspaceSvg) {
// Android ignores any sound not loaded as a result of a user action.
soundBinds.push(browserEvents.conditionalBind(
document, 'mousemove', null, unbindSounds, true));
document, 'mousemove', null, unbindSounds, true));
soundBinds.push(browserEvents.conditionalBind(
document, 'touchstart', null, unbindSounds, true));
document, 'touchstart', null, unbindSounds, true));
}
+15 -15
View File
@@ -16,17 +16,17 @@
import './field_label';
/* eslint-disable-next-line no-unused-vars */
import { Block } from './block.js';
import {Block} from './block.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { Connection } from './connection.js';
import {Connection} from './connection.js';
/* eslint-disable-next-line no-unused-vars */
import { Field } from './field.js';
import {Field} from './field.js';
import * as fieldRegistry from './field_registry.js';
import { inputTypes } from './input_types.js';
import {inputTypes} from './input_types.js';
/* eslint-disable-next-line no-unused-vars */
import { RenderedConnection } from './rendered_connection.js';
import {RenderedConnection} from './rendered_connection.js';
/**
@@ -50,11 +50,11 @@ export class Input {
* @param connection Optional connection for this input.
*/
constructor(
public type: number, public name: string, block: Block,
public connection: Connection | null) {
public type: number, public name: string, block: Block,
public connection: Connection|null) {
if (type !== inputTypes.DUMMY && !name) {
throw Error(
'Value inputs and statement inputs must have non-empty name.');
'Value inputs and statement inputs must have non-empty name.');
}
this.sourceBlock_ = block;
@@ -66,7 +66,7 @@ export class Input {
* Get the source block for this input.
* @return The source block, or null if there is none.
*/
getSourceBlock(): Block | null {
getSourceBlock(): Block|null {
return this.sourceBlock_;
}
@@ -78,7 +78,7 @@ export class Input {
* field again. Should be unique to the host block.
* @return The input being append to (to allow chaining).
*/
appendField(field: string | Field, opt_name?: string): Input {
appendField(field: string|Field, opt_name?: string): Input {
this.insertFieldAt(this.fieldRow.length, field, opt_name);
return this;
}
@@ -92,7 +92,7 @@ export class Input {
* field again. Should be unique to the host block.
* @return The index following the last inserted field.
*/
insertFieldAt(index: number, field: string | Field, opt_name?: string): number {
insertFieldAt(index: number, field: string|Field, opt_name?: string): number {
if (index < 0 || index > this.fieldRow.length) {
throw Error('index ' + index + ' out of bounds.');
}
@@ -221,7 +221,7 @@ export class Input {
* types are compatible.
* @return The input being modified (to allow chaining).
*/
setCheck(check: string | string[] | null): Input {
setCheck(check: string|string[]|null): Input {
if (!this.connection) {
throw Error('This input does not have a connection.');
}
@@ -249,7 +249,7 @@ export class Input {
* @param shadow DOM representation of a block or null.
* @return The input being modified (to allow chaining).
*/
setShadowDom(shadow: Element | null): Input {
setShadowDom(shadow: Element|null): Input {
if (!this.connection) {
throw Error('This input does not have a connection.');
}
@@ -261,7 +261,7 @@ export class Input {
* Returns the XML representation of the connection's shadow block.
* @return Shadow DOM representation of a block or null.
*/
getShadowDom(): Element | null {
getShadowDom(): Element|null {
if (!this.connection) {
throw Error('This input does not have a connection.');
}
+1 -1
View File
@@ -13,7 +13,7 @@
* @namespace Blockly.inputTypes
*/
import { ConnectionType } from './connection_type.js';
import {ConnectionType} from './connection_type.js';
/**
+53 -53
View File
@@ -14,29 +14,29 @@
import * as blockAnimations from './block_animations.js';
/* eslint-disable-next-line no-unused-vars */
import { BlockSvg } from './block_svg.js';
import {BlockSvg} from './block_svg.js';
import * as common from './common.js';
import { ComponentManager } from './component_manager.js';
import { config } from './config.js';
import { ConnectionType } from './connection_type.js';
import {ComponentManager} from './component_manager.js';
import {config} from './config.js';
import {ConnectionType} from './connection_type.js';
import * as constants from './constants.js';
import * as eventUtils from './events/utils.js';
/* eslint-disable-next-line no-unused-vars */
import { IDeleteArea } from './interfaces/i_delete_area.js';
import {IDeleteArea} from './interfaces/i_delete_area.js';
/* eslint-disable-next-line no-unused-vars */
import { IDragTarget } from './interfaces/i_drag_target.js';
import {IDragTarget} from './interfaces/i_drag_target.js';
/* eslint-disable-next-line no-unused-vars */
import { RenderedConnection } from './rendered_connection.js';
import {RenderedConnection} from './rendered_connection.js';
/* eslint-disable-next-line no-unused-vars */
import { Coordinate } from './utils/coordinate.js';
import {Coordinate} from './utils/coordinate.js';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from './workspace_svg.js';
import {WorkspaceSvg} from './workspace_svg.js';
/** Represents a nearby valid connection. */
interface CandidateConnection {
closest: RenderedConnection | null;
local: RenderedConnection | null;
closest: RenderedConnection|null;
local: RenderedConnection|null;
radius: number;
} // eslint-disable-line no-unused-vars
@@ -45,9 +45,9 @@ interface CandidateConnection {
* missing any components.
*/
const DUPLICATE_BLOCK_ERROR = 'The insertion marker ' +
'manager tried to create a marker but the result is missing %1. If ' +
'you are using a mutator, make sure your domToMutation method is ' +
'properly defined.';
'manager tried to create a marker but the result is missing %1. If ' +
'you are using a mutator, make sure your domToMutation method is ' +
'properly defined.';
export enum PreviewType {
@@ -222,13 +222,13 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is
// not assignable to parameter of type 'Connection'.
this.localConnection_.connect(
this.closestConnection_ as AnyDuringMigration);
this.closestConnection_ as AnyDuringMigration);
if (this.topBlock_.rendered) {
// Trigger a connection animation.
// Determine which connection is inferior (lower in the source stack).
const inferiorConnection = this.localConnection_.isSuperior() ?
this.closestConnection_ :
this.localConnection_;
this.closestConnection_ :
this.localConnection_;
blockAnimations.connectionUiEffect(inferiorConnection.getSourceBlock());
// Bring the just-edited stack to the front.
const rootBlock = this.topBlock_.getRootBlock();
@@ -242,13 +242,13 @@ export class InsertionMarkerManager {
* @param dxy Position relative to drag start, in workspace units.
* @param dragTarget The drag target that the block is currently over.
*/
update(dxy: Coordinate, dragTarget: IDragTarget | null) {
update(dxy: Coordinate, dragTarget: IDragTarget|null) {
const candidate = this.getCandidate_(dxy);
this.wouldDeleteBlock_ = this.shouldDelete_(candidate, dragTarget);
const shouldUpdate =
this.wouldDeleteBlock_ || this.shouldUpdatePreviews_(candidate, dxy);
this.wouldDeleteBlock_ || this.shouldUpdatePreviews_(candidate, dxy);
if (shouldUpdate) {
// Don't fire events for insertion marker creation or movement.
@@ -354,7 +354,7 @@ export class InsertionMarkerManager {
* @return Whether the preview should be updated.
*/
private shouldUpdatePreviews_(
candidate: CandidateConnection, dxy: Coordinate): boolean {
candidate: CandidateConnection, dxy: Coordinate): boolean {
const candidateLocal = candidate.local;
const candidateClosest = candidate.closest;
const radius = candidate.radius;
@@ -366,24 +366,24 @@ export class InsertionMarkerManager {
if (this.localConnection_ && this.closestConnection_) {
// The connection was the same as the current connection.
if (this.closestConnection_ === candidateClosest &&
this.localConnection_ === candidateLocal) {
this.localConnection_ === candidateLocal) {
return false;
}
const xDiff =
this.localConnection_.x + dxy.x - this.closestConnection_.x;
this.localConnection_.x + dxy.x - this.closestConnection_.x;
const yDiff =
this.localConnection_.y + dxy.y - this.closestConnection_.y;
this.localConnection_.y + dxy.y - this.closestConnection_.y;
const curDistance = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
// Slightly prefer the existing preview over a new preview.
return !(
candidateClosest &&
radius > curDistance - config.currentConnectionPreference);
candidateClosest &&
radius > curDistance - config.currentConnectionPreference);
} else if (!this.localConnection_ && !this.closestConnection_) {
// We weren't showing a preview before, but we should now.
return true;
} else {
console.error(
'Only one of localConnection_ and closestConnection_ was set.');
'Only one of localConnection_ and closestConnection_ was set.');
}
} else {
// No connection found.
@@ -392,7 +392,7 @@ export class InsertionMarkerManager {
}
console.error(
'Returning true from shouldUpdatePreviews, but it\'s not clear why.');
'Returning true from shouldUpdatePreviews, but it\'s not clear why.');
return true;
}
@@ -428,7 +428,7 @@ export class InsertionMarkerManager {
radius = neighbour.radius;
}
}
return { closest: candidateClosest, local: candidateLocal, radius };
return {closest: candidateClosest, local: candidateLocal, radius};
}
/**
@@ -456,14 +456,14 @@ export class InsertionMarkerManager {
* @return Whether dropping the block immediately would delete the block.
*/
private shouldDelete_(
candidate: CandidateConnection, dragTarget: IDragTarget | null): boolean {
candidate: CandidateConnection, dragTarget: IDragTarget|null): boolean {
if (dragTarget) {
const componentManager = this.workspace_.getComponentManager();
const isDeleteArea = componentManager.hasCapability(
dragTarget.id, ComponentManager.Capability.DELETE_AREA);
dragTarget.id, ComponentManager.Capability.DELETE_AREA);
if (isDeleteArea) {
return (dragTarget as IDeleteArea)
.wouldDelete(this.topBlock_, candidate && !!candidate.closest);
.wouldDelete(this.topBlock_, candidate && !!candidate.closest);
}
}
return false;
@@ -493,7 +493,7 @@ export class InsertionMarkerManager {
// Something went wrong and we're trying to connect to an invalid
// connection.
if (closest === this.closestConnection_ ||
closest.getSourceBlock().isInsertionMarker()) {
closest.getSourceBlock().isInsertionMarker()) {
console.log('Trying to connect to an insertion marker');
return;
}
@@ -513,7 +513,7 @@ export class InsertionMarkerManager {
const closest = this.closestConnection_;
const renderer = this.workspace_.getRenderer();
const method = renderer.getConnectionPreviewMethod(
(closest), (this.localConnection_), this.topBlock_);
(closest), (this.localConnection_), this.topBlock_);
switch (method) {
case InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE:
@@ -532,7 +532,7 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is not
// assignable to parameter of type 'Connection'.
if (closest &&
renderer.shouldHighlightConnection(closest as AnyDuringMigration)) {
renderer.shouldHighlightConnection(closest as AnyDuringMigration)) {
closest.highlight();
}
}
@@ -561,7 +561,7 @@ export class InsertionMarkerManager {
// Also hide if we had a preview before but now we're going to delete
// instead.
if (hadPreview &&
(closestChanged || localChanged || this.wouldDeleteBlock_)) {
(closestChanged || localChanged || this.wouldDeleteBlock_)) {
this.hidePreview_();
}
}
@@ -586,8 +586,8 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is not
// assignable to parameter of type 'Connection'.
if (this.closestConnection_ && this.closestConnection_.targetBlock() &&
this.workspace_.getRenderer().shouldHighlightConnection(
this.closestConnection_ as AnyDuringMigration)) {
this.workspace_.getRenderer().shouldHighlightConnection(
this.closestConnection_ as AnyDuringMigration)) {
this.closestConnection_.unhighlight();
}
if (this.fadedBlock_) {
@@ -614,7 +614,7 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'BlockSvg' is not
// assignable to parameter of type 'Block'.
imConn = imBlock.getMatchingConnection(
local.getSourceBlock() as AnyDuringMigration, local);
local.getSourceBlock() as AnyDuringMigration, local);
} catch (e) {
// It's possible that the number of connections on the local block has
// changed since the insertion marker was originally created. Let's
@@ -627,13 +627,13 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'BlockSvg' is not
// assignable to parameter of type 'Block'.
imConn = imBlock.getMatchingConnection(
local.getSourceBlock() as AnyDuringMigration, local);
local.getSourceBlock() as AnyDuringMigration, local);
}
if (imConn === this.markerConnection_) {
throw Error(
'Made it to showInsertionMarker_ even though the marker isn\'t ' +
'changing');
'Made it to showInsertionMarker_ even though the marker isn\'t ' +
'changing');
}
// Render disconnected from everything else so that we have a valid
@@ -675,17 +675,17 @@ export class InsertionMarkerManager {
const markerOutput = imBlock.outputConnection;
const isFirstInStatementStack =
imConn === markerNext && !(markerPrev && markerPrev.targetConnection);
imConn === markerNext && !(markerPrev && markerPrev.targetConnection);
const isFirstInOutputStack = imConn.type === ConnectionType.INPUT_VALUE &&
!(markerOutput && markerOutput.targetConnection);
!(markerOutput && markerOutput.targetConnection);
// The insertion marker is the first block in a stack. Unplug won't do
// anything in that case. Instead, unplug the following block.
if (isFirstInStatementStack || isFirstInOutputStack) {
imConn.targetBlock()!.unplug(false);
} else if (
imConn.type === ConnectionType.NEXT_STATEMENT &&
imConn !== markerNext) {
imConn.type === ConnectionType.NEXT_STATEMENT &&
imConn !== markerNext) {
// Inside of a C-block, first statement connection.
const innerConnection = imConn.targetConnection;
if (innerConnection) {
@@ -693,24 +693,24 @@ export class InsertionMarkerManager {
}
const previousBlockNextConnection =
markerPrev ? markerPrev.targetConnection : null;
markerPrev ? markerPrev.targetConnection : null;
imBlock.unplug(true);
if (previousBlockNextConnection) {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is
// not assignable to parameter of type 'Connection'.
previousBlockNextConnection.connect(
innerConnection as AnyDuringMigration);
innerConnection as AnyDuringMigration);
}
} else {
imBlock.unplug(/* healStack */
true);
true);
}
if (imConn.targetConnection) {
throw Error(
'markerConnection_ still connected at the end of ' +
'disconnectInsertionMarker');
'markerConnection_ still connected at the end of ' +
'disconnectInsertionMarker');
}
// AnyDuringMigration because: Type 'null' is not assignable to type
@@ -729,7 +729,7 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is not
// assignable to parameter of type 'Connection'.
this.highlightedBlock_.highlightShapeForInput(
closest as AnyDuringMigration, true);
closest as AnyDuringMigration, true);
}
/** Hides any visible input outlines. */
@@ -737,7 +737,7 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Argument of type 'RenderedConnection' is not
// assignable to parameter of type 'Connection'.
this.highlightedBlock_.highlightShapeForInput(
this.closestConnection_ as AnyDuringMigration, false);
this.closestConnection_ as AnyDuringMigration, false);
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'BlockSvg'.
this.highlightedBlock_ = null as AnyDuringMigration;
@@ -751,7 +751,7 @@ export class InsertionMarkerManager {
// AnyDuringMigration because: Type 'BlockSvg | null' is not assignable to
// type 'BlockSvg'.
this.fadedBlock_ =
this.closestConnection_.targetBlock() as AnyDuringMigration;
this.closestConnection_.targetBlock() as AnyDuringMigration;
this.fadedBlock_.fadeForReplacement(true);
}
+1 -1
View File
@@ -13,7 +13,7 @@
* @namespace Blockly.IASTNodeLocationSvg
*/
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocation } from './i_ast_node_location.js';
import {IASTNodeLocation} from './i_ast_node_location.js';
/**
@@ -22,7 +22,7 @@
import '../block';
/* eslint-disable-next-line no-unused-vars */
import { IASTNodeLocation } from './i_ast_node_location.js';
import {IASTNodeLocation} from './i_ast_node_location.js';
/**
+1 -1
View File
@@ -18,7 +18,7 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { IComponent } from './i_component.js';
import {IComponent} from './i_component.js';
/**
+2 -2
View File
@@ -21,9 +21,9 @@ import '../block_drag_surface';
import '../utils/coordinate';
/* eslint-disable-next-line no-unused-vars */
import { IContextMenu } from './i_contextmenu.js';
import {IContextMenu} from './i_contextmenu.js';
/* eslint-disable-next-line no-unused-vars */
import { IDraggable } from './i_draggable.js';
import {IDraggable} from './i_draggable.js';
/**
@@ -18,7 +18,7 @@
// Unused import preserved for side-effects. Remove if unneeded.
import './i_toolbox_item';
import { ISelectableToolboxItem } from './i_selectable_toolbox_item.js';
import {ISelectableToolboxItem} from './i_selectable_toolbox_item.js';
/**
+4 -4
View File
@@ -15,9 +15,9 @@
/* eslint-disable-next-line no-unused-vars */
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from '../workspace_svg.js';
import {WorkspaceSvg} from '../workspace_svg.js';
import { ISelectable } from './i_selectable.js';
import {ISelectable} from './i_selectable.js';
/** @alias Blockly.ICopyable */
@@ -29,7 +29,7 @@ export interface ICopyable extends ISelectable {
toCopyData: AnyDuringMigration;
}
export interface CopyData {
saveInfo: AnyDuringMigration | Element;
saveInfo: AnyDuringMigration|Element;
source: WorkspaceSvg;
typeCounts: AnyDuringMigration | null;
typeCounts: AnyDuringMigration|null;
}
+1 -1
View File
@@ -22,7 +22,7 @@
// Unused import preserved for side-effects. Remove if unneeded.
import './i_draggable';
import { IDragTarget } from './i_drag_target.js';
import {IDragTarget} from './i_drag_target.js';
/**
+1 -1
View File
@@ -25,7 +25,7 @@ import './i_draggable';
// Unused import preserved for side-effects. Remove if unneeded.
import '../utils/rect';
import { IComponent } from './i_component.js';
import {IComponent} from './i_component.js';
/**
+1 -1
View File
@@ -14,7 +14,7 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { IDeletable } from './i_deletable.js';
import {IDeletable} from './i_deletable.js';
/**
+3 -3
View File
@@ -27,10 +27,10 @@ import '../utils/coordinate';
import '../utils/svg';
/* eslint-disable-next-line no-unused-vars */
import { WorkspaceSvg } from '../workspace_svg.js';
import {WorkspaceSvg} from '../workspace_svg.js';
/* eslint-disable-next-line no-unused-vars */
import { IRegistrable } from './i_registrable.js';
import {IRegistrable} from './i_registrable.js';
/**
@@ -45,7 +45,7 @@ export interface IFlyout extends IRegistrable {
RTL: boolean;
/** The target workspace */
targetWorkspace: WorkspaceSvg | null;
targetWorkspace: WorkspaceSvg|null;
/** Margin around the edges of the blocks in the flyout. */
readonly MARGIN: number;
+1 -1
View File
@@ -21,7 +21,7 @@ import '../metrics_manager';
// Unused import preserved for side-effects. Remove if unneeded.
import '../utils/rect';
import { IComponent } from './i_component.js';
import {IComponent} from './i_component.js';
/**
+1 -1
View File
@@ -14,7 +14,7 @@
*/
/* eslint-disable-next-line no-unused-vars */
import { Field } from '../field.js';
import {Field} from '../field.js';
type fromJson = (p1: object) => Field;
+2 -2
View File
@@ -14,9 +14,9 @@
*/
// eslint-disable-next-line no-unused-vars
import { IDeletable } from './i_deletable.js';
import {IDeletable} from './i_deletable.js';
// eslint-disable-next-line no-unused-vars
import { IMovable } from './i_movable.js';
import {IMovable} from './i_movable.js';
/**
+1 -1
View File
@@ -18,7 +18,7 @@
import '../utils/toolbox';
/* eslint-disable-next-line no-unused-vars */
import { IToolboxItem } from './i_toolbox_item.js';
import {IToolboxItem} from './i_toolbox_item.js';
/**
+1 -1
View File
@@ -18,7 +18,7 @@
*/
// eslint-disable-next-line no-unused-vars
import { Workspace } from '../workspace.js';
import {Workspace} from '../workspace.js';
/**
+1 -1
View File
@@ -27,7 +27,7 @@ import './i_toolbox_item';
import '../workspace_svg';
/* eslint-disable-next-line no-unused-vars */
import { IRegistrable } from './i_registrable.js';
import {IRegistrable} from './i_registrable.js';
/**
+3 -3
View File
@@ -30,7 +30,7 @@ export interface IToolboxItem {
* Gets the div for the toolbox item.
* @return The div for the toolbox item.
*/
getDiv(): Element | null;
getDiv(): Element|null;
/**
* Gets a unique identifier for this toolbox item.
@@ -43,7 +43,7 @@ export interface IToolboxItem {
* @return The parent toolbox item, or null if this toolbox item is not
* nested.
*/
getParent(): IToolboxItem | null;
getParent(): IToolboxItem|null;
/**
* Gets the nested level of the category.
@@ -70,7 +70,7 @@ export interface IToolboxItem {
* Gets the HTML element that is clickable.
* @return The HTML element that receives clicks.
*/
getClickTarget(): Element | null;
getClickTarget(): Element|null;
/**
* Sets whether the category is visible or not.
+3 -3
View File
@@ -16,7 +16,7 @@
* @namespace Blockly.internalConstants
*/
import { ConnectionType } from './connection_type.js';
import {ConnectionType} from './connection_type.js';
/**
@@ -40,9 +40,9 @@ export const OPPOSITE_TYPE: number[] = [];
OPPOSITE_TYPE[ConnectionType.INPUT_VALUE] = ConnectionType.OUTPUT_VALUE;
OPPOSITE_TYPE[ConnectionType.OUTPUT_VALUE] = ConnectionType.INPUT_VALUE;
OPPOSITE_TYPE[ConnectionType.NEXT_STATEMENT] =
ConnectionType.PREVIOUS_STATEMENT;
ConnectionType.PREVIOUS_STATEMENT;
OPPOSITE_TYPE[ConnectionType.PREVIOUS_STATEMENT] =
ConnectionType.NEXT_STATEMENT;
ConnectionType.NEXT_STATEMENT;
/**
* String for use in the dropdown created in field_variable.

Some files were not shown because too many files have changed in this diff Show More