chore: move comments back to their correct positions (#6249)

* fix: work on fixing comments

* chore: finish moving all comments

* chore: format

* chore: move some other messed up comments

* chore: format
This commit is contained in:
Beka Westberg
2022-06-28 21:13:18 +00:00
committed by GitHub
parent 29e1f0cb03
commit 8a467d730a
46 changed files with 223 additions and 351 deletions
+3 -6
View File
@@ -459,9 +459,8 @@ export class Block implements IASTNodeLocation, IDeletable {
thisConnection.type === ConnectionType.INPUT_VALUE &&
thisConnection.targetConnection) {
if (connection) {
return null;
return null; // More than one value input found.
}
// More than one value input found.
connection = thisConnection;
}
}
@@ -1542,9 +1541,8 @@ export class Block implements IASTNodeLocation, IDeletable {
'JSON attribute \'extensions\' should be an array of' +
' strings. Found raw string in JSON for \'' + json['type'] +
'\' block.');
json['extensions'] = [json['extensions']];
json['extensions'] = [json['extensions']]; // Correct and continue.
}
// Correct and continue.
// Add the mutator to the block.
if (json['mutator'] !== undefined) {
@@ -1998,9 +1996,8 @@ export class Block implements IASTNodeLocation, IDeletable {
this.commentModel.text = text;
// AnyDuringMigration because: Type 'string | null' is not assignable to
// type 'string | Comment'.
this.comment = text as AnyDuringMigration;
this.comment = text as AnyDuringMigration; // For backwards compatibility.
}
// For backwards compatibility.
/**
* Set this block's warning text.
+5 -9
View File
@@ -27,7 +27,7 @@ interface CloneRect {
y: number;
width: number;
height: number;
} // eslint-disable-line no-unused-vars
}
/** PID of disconnect UI animation. There can only be one at a time. */
let disconnectPid: AnyDuringMigration = 0;
@@ -105,9 +105,8 @@ export function connectionUiEffect(block: BlockSvg) {
const scale = workspace.scale;
workspace.getAudioManager().play('click');
if (scale < 1) {
return;
return; // Too small to care about visual effects.
}
// Too small to care about visual effects.
// Determine the absolute coordinates of the inferior block.
const xy = workspace.getSvgXY(block.getSvgRoot());
// Offset the coordinates based on the two connection types, fix scale.
@@ -161,9 +160,8 @@ function connectionUiStep(ripple: SVGElement, start: Date, scale: number) {
export function disconnectUiEffect(block: BlockSvg) {
block.workspace.getAudioManager().play('disconnect');
if (block.workspace.scale < 1) {
return;
return; // Too small to care about visual effects.
}
// Too small to care about visual effects.
// Horizontal distance for bottom of block to wiggle.
const DISPLACEMENT = 10;
// Scale magnitude of skew to height of block.
@@ -183,10 +181,8 @@ export function disconnectUiEffect(block: BlockSvg) {
* @param start Date of animation's start.
*/
function disconnectUiStep(group: SVGElement, magnitude: number, start: Date) {
const DURATION = 200;
// Milliseconds.
const WIGGLES = 3;
// Half oscillations.
const DURATION = 200; // Milliseconds.
const WIGGLES = 3; // Half oscillations.
const ms = new Date().getTime() - start.getTime();
const percent = ms / DURATION;
+16 -29
View File
@@ -143,7 +143,6 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
/** Block's warning icon (if any). */
warning: Warning|null = null;
// Create core elements for the block.
private svgGroup_: SVGGElement;
style: BlockStyle;
/** @internal */
@@ -542,26 +541,22 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
/** Snap this block to the nearest grid point. */
snapToGrid() {
if (!this.workspace) {
return;
return; // Deleted block.
}
// Deleted block.
if (this.workspace.isDragging()) {
return;
return // Don't bump blocks during a drag.;
}
// Don't bump blocks during a drag.
if (this.getParent()) {
return;
return; // Only snap top-level blocks.
}
// Only snap top-level blocks.
if (this.isInFlyout) {
return;
return; // Don't move blocks around in a flyout.
}
// Don't move blocks around in a flyout.
const grid = this.workspace.getGrid();
if (!grid || !grid.shouldSnap()) {
return;
return; // Config says no snapping.
}
// Config says no snapping.
const spacing = grid.getSpacing();
const half = spacing / 2;
const xy = this.getRelativeToSurfaceXY();
@@ -619,10 +614,10 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
this.updateCollapsed_();
} else if (this.rendered) {
this.render();
// Don't bump neighbours. Users like to store collapsed functions together
// and bumping makes them go out of alignment.
}
}
// Don't bump neighbours. Users like to store collapsed functions together
// and bumping makes them go out of alignment.
/**
* Makes sure that when the block is collapsed, it is rendered correctly
@@ -844,9 +839,8 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
override setInsertionMarker(insertionMarker: boolean) {
if (this.isInsertionMarker_ === insertionMarker) {
return;
return; // No change.
}
// No change.
this.isInsertionMarker_ = insertionMarker;
if (this.isInsertionMarker_) {
this.setColour(
@@ -1043,17 +1037,14 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
this.commentIcon_!.updateText();
return;
}
// For backwards compatibility.
if (shouldHaveComment) {
this.commentIcon_ = new Comment(this);
this.comment = this.commentIcon_;
} else // For backwards compatibility.
{
this.comment = this.commentIcon_; // For backwards compatibility.
} else {
this.commentIcon_!.dispose();
this.commentIcon_ = null;
this.comment = null;
this.comment = null; // For backwards compatibility.
}
// For backwards compatibility.
if (this.rendered) {
this.render();
// Adding or removing a comment icon will cause the block to change shape.
@@ -1090,8 +1081,7 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
// Wait until the drag finishes.
const thisBlock = this;
this.warningTextDb_[id] = setTimeout(function() {
if (thisBlock.workspace) {
// Check block wasn't deleted.
if (thisBlock.workspace) { // Check block wasn't deleted.
delete thisBlock.warningTextDb_[id];
thisBlock.setWarningText(text, id);
}
@@ -1541,13 +1531,11 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
override bumpNeighbours() {
if (!this.workspace) {
return;
return; // Deleted block.
}
// Deleted block.
if (this.workspace.isDragging()) {
return;
return; // Don't bump blocks during a drag.
}
// Don't bump blocks during a drag.
const rootBlock = this.getRootBlock();
if (rootBlock.isInFlyout) {
return;
@@ -1655,9 +1643,8 @@ export class BlockSvg extends Block implements IASTNodeLocationSvg,
*/
render(opt_bubble?: boolean) {
if (this.renderIsInProgress_) {
return;
return; // Don't allow recursive renders.
}
// Don't allow recursive renders.
this.renderIsInProgress_ = true;
try {
this.rendered = true;
+3 -6
View File
@@ -274,18 +274,15 @@ export function mouseToSvg(
*/
export function getScrollDeltaPixels(e: WheelEvent): {x: number, y: number} {
switch (e.deltaMode) {
case 0x00:
// Pixel mode.
case 0x00: // Pixel mode.
default:
return {x: e.deltaX, y: e.deltaY};
case 0x01:
// Line mode.
case 0x01: // Line mode.
return {
x: e.deltaX * LINE_MODE_MULTIPLIER,
y: e.deltaY * LINE_MODE_MULTIPLIER,
};
case 0x02:
// Page mode.
case 0x02: // Page mode.
return {
x: e.deltaX * PAGE_MODE_MULTIPLIER,
y: e.deltaY * PAGE_MODE_MULTIPLIER,
+4 -3
View File
@@ -548,7 +548,8 @@ export class Bubble implements IBubble {
const bubbleLeft = bubbleRight - this.width_;
const workspaceRight = viewMetrics.left + viewMetrics.width;
const workspaceLeft = viewMetrics.left + // Thickness in workspace units.
const workspaceLeft = viewMetrics.left +
// Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
if (bubbleLeft < workspaceLeft) {
@@ -563,8 +564,8 @@ export class Bubble implements IBubble {
const bubbleRight = bubbleLeft + this.width_;
const workspaceLeft = viewMetrics.left;
const workspaceRight = viewMetrics.left +
viewMetrics.width - // Thickness in workspace units.
const workspaceRight = viewMetrics.left + viewMetrics.width -
// Thickness in workspace units.
Scrollbar.scrollbarThickness / this.workspace_.scale;
if (bubbleLeft < workspaceLeft) {
+1 -1
View File
@@ -31,7 +31,7 @@ interface Config {
currentConnectionPreference: number;
bumpDelay: number;
connectingSnapRadius: number;
} // eslint-disable-line no-unused-vars
}
/** Default snap radius. */
const DEFAULT_SNAP_RADIUS = 28;
+1 -2
View File
@@ -673,9 +673,8 @@ function getSingleConnection(block: Block, orphanBlock: Block): Connection|
const connection = input.connection;
if (connection && typeChecker.canConnect(output, connection, false)) {
if (foundConnection) {
return null;
return null; // More than one connection.
}
// More than one connection.
foundConnection = connection;
}
}
+1 -2
View File
@@ -96,9 +96,8 @@ export function show(
setTimeout(function() {
menu.focus();
}, 1);
currentBlock = null;
currentBlock = null; // May be set by Blockly.Block.
}
// May be set by Blockly.Block.
/**
* Create the context menu object and populate it with the given options.
+2 -4
View File
@@ -123,9 +123,8 @@ export interface PositionMetrics {
*/
export function createDom() {
if (div) {
return;
return; // Already created.
}
// Already created.
div = document.createElement('div');
div.className = 'blocklyDropDownDiv';
const parentDiv = common.getParentContainer() || document.body;
@@ -442,8 +441,7 @@ function getPositionAboveMetrics(
const arrowY = divSize.height - BORDER_SIZE * 2 - ARROW_SIZE / 2;
const finalY = secondaryY - divSize.height - PADDING_Y;
const initialY = secondaryY - divSize.height;
// No padding on Y.
const initialY = secondaryY - divSize.height; // No padding on Y.
return {
initialX: xCoords.divX,
+2 -2
View File
@@ -47,9 +47,9 @@ export class BlockCreate extends BlockBase {
this.type = eventUtils.BLOCK_CREATE;
if (!opt_block) {
return;
return; // Blank event to be populated by fromJson.
}
// Blank event to be populated by fromJson.
if (opt_block.isShadow()) {
}
+2 -2
View File
@@ -49,9 +49,9 @@ export class BlockDelete extends BlockBase {
this.type = eventUtils.BLOCK_DELETE;
if (!opt_block) {
return;
return; // Blank event to be populated by fromJson.
}
// Blank event to be populated by fromJson.
if (opt_block.getParent()) {
throw Error('Connected blocks cannot be deleted.');
}
+2 -2
View File
@@ -42,9 +42,9 @@ export class CommentDelete extends CommentBase {
this.type = eventUtils.COMMENT_DELETE;
if (!opt_comment) {
return;
return; // Blank event to be populated by fromJson.
}
// Blank event to be populated by fromJson.
this.xml = opt_comment.toXmlWithXY();
}
// TODO (#1266): "Full" and "minimal" serialization.
+2 -2
View File
@@ -52,9 +52,9 @@ export class CommentMove extends CommentBase {
this.type = eventUtils.COMMENT_MOVE;
if (!opt_comment) {
return;
return; // Blank event to be populated by fromJson.
}
// Blank event to be populated by fromJson.
/**
* The comment that is being moved. Will be cleared after recording the new
* location.
+4 -8
View File
@@ -352,8 +352,7 @@ export function runAfterPageLoad(fn: () => AnyDuringMigration) {
throw Error('runAfterPageLoad() requires browser document.');
}
if (document.readyState === 'complete') {
// Page has already loaded. Call immediately.
fn();
fn(); // Page has already loaded. Call immediately.
} else {
// Poll readyState.
const readyStateCheckInterval = setInterval(function() {
@@ -393,8 +392,7 @@ export function buildTooltipForDropdown(
// 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
if (typeof document === 'object') { // Relies on document.readyState
runAfterPageLoad(function() {
for (const key in lookupTable) {
// Will print warnings if reference is missing.
@@ -446,8 +444,7 @@ function checkDropdownOptionsInTable(
if (dropdown instanceof FieldDropdown && !dropdown.isOptionListDynamic()) {
const options = dropdown.getOptions();
for (let i = 0; i < options.length; i++) {
const optionKey = options[i][1];
// label, then value
const optionKey = options[i][1]; // label, then value
if (lookupTable[optionKey] === null) {
console.warn(
'No tooltip mapping for value ' + optionKey + ' of field ' +
@@ -473,8 +470,7 @@ export function buildTooltipWithFieldText(
// 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
if (typeof document === 'object') { // Relies on document.readyState
runAfterPageLoad(function() {
// Will print warnings if reference is missing.
parsing.checkMessageReferences(msgTemplate);
+1 -2
View File
@@ -1050,8 +1050,7 @@ export abstract class Field implements IASTNodeLocationSvg,
* the empty string.
*/
setTooltip(newTip: Tooltip.TipInfo|null) {
if (!newTip && newTip !== '') {
// If null or undefined.
if (!newTip && newTip !== '') { // If null or undefined.
newTip = this.sourceBlock_;
}
const clickTarget = this.getClickTarget_();
+1 -1
View File
@@ -509,8 +509,8 @@ export class FieldColour extends Field {
}
const cell = (document.createElement('td'));
row!.appendChild(cell);
cell.setAttribute('data-colour', colours[i]);
// This becomes the value, if clicked.
cell.setAttribute('data-colour', colours[i]);
cell.title = titles[i] || colours[i];
cell.id = idGenerator.getNextUniqueId();
// AnyDuringMigration because: Argument of type 'number' is not
+4 -7
View File
@@ -309,10 +309,8 @@ export class FieldDropdown extends Field {
const options = this.getOptions(false);
this.selectedMenuItem_ = null;
for (let i = 0; i < options.length; i++) {
let content = options[i][0];
// Human-readable text or image.
const value = options[i][1];
// Language-neutral value.
let content = options[i][0]; // Human-readable text or image.
const value = options[i][1]; // Language-neutral value.
if (typeof content === 'object') {
// An image, not text.
const image = new Image(content['width'], content['height']);
@@ -387,9 +385,8 @@ export class FieldDropdown extends Field {
}
}
if (hasImages || options.length < 2) {
return;
return; // Do nothing if too few items or at least one label is an image.
}
// Do nothing if too few items or at least one label is an image.
const strings = [];
for (let i = 0; i < options.length; i++) {
strings.push(options[i][0]);
@@ -697,7 +694,7 @@ interface ImageProperties {
alt: string;
width: number;
height: number;
} // eslint-disable-line no-unused-vars
}
/**
* The y offset from the top of the field to the top of the image, if an image
+2 -4
View File
@@ -140,9 +140,8 @@ export class FieldVariable extends FieldDropdown {
*/
override initModel() {
if (this.variable_) {
return;
return; // Initialization already happened.
}
// Initialization already happened.
const variable = Variables.getOrCreateVariablePackage(
this.sourceBlock_.workspace, null, this.defaultVariableName,
this.defaultType_);
@@ -349,9 +348,8 @@ export class FieldVariable extends FieldDropdown {
private typeIsAllowed_(type: string): boolean {
const typeList = this.getVariableTypes_();
if (!typeList) {
return true;
return true; // If it's null, all types are valid.
}
// If it's null, all types are valid.
for (let i = 0; i < typeList.length; i++) {
if (type === typeList[i]) {
return true;
+1 -2
View File
@@ -328,8 +328,7 @@ export class HorizontalFlyout extends Flyout {
if (this.toolboxPosition_ === toolbox.Position.TOP) {
const height = flyoutRect.height;
return new Rect(-BIG_NUM, top + height, -BIG_NUM, BIG_NUM);
} else {
// Bottom.
} else { // Bottom.
return new Rect(top, BIG_NUM, -BIG_NUM, BIG_NUM);
}
}
+1 -2
View File
@@ -311,8 +311,7 @@ export class VerticalFlyout extends Flyout {
if (this.toolboxPosition_ === toolbox.Position.LEFT) {
const width = flyoutRect.width;
return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width);
} else {
// Right
} else { // Right
return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM);
}
}
+2 -3
View File
@@ -152,8 +152,8 @@ export class Generator {
}
// AnyDuringMigration because: Type 'string' is not assignable to type
// 'any[]'.
code = code.join('\n') as AnyDuringMigration;
// Blank line between each section.
code = code.join('\n') as AnyDuringMigration;
// AnyDuringMigration because: Argument of type 'any[]' is not assignable
// to parameter of type 'string'. AnyDuringMigration because: Type 'string'
// is not assignable to type 'any[]'.
@@ -395,8 +395,7 @@ export class Generator {
* @return Code snippet with ID.
*/
injectId(msg: string, block: Block): string {
const id = block.id.replace(/\$/g, '$$$$');
// Issue 251.
const id = block.id.replace(/\$/g, '$$$$'); // Issue 251.
return msg.replace(/%1/g, '\'' + id + '\'');
}
+1 -2
View File
@@ -278,9 +278,8 @@ export class Input {
/** Initialize the fields on this input. */
init() {
if (!this.sourceBlock_.workspace.rendered) {
return;
return; // Headless blocks don't need fields initialized.
}
// Headless blocks don't need fields initialized.
for (let i = 0; i < this.fieldRow.length; i++) {
this.fieldRow[i].init();
}
+3 -5
View File
@@ -41,7 +41,7 @@ interface CandidateConnection {
closest: RenderedConnection|null;
local: RenderedConnection|null;
radius: number;
} // eslint-disable-line no-unused-vars
}
/**
* An error message to throw if the block created by createMarkerBlock_ is
@@ -299,9 +299,8 @@ export class InsertionMarkerManager {
for (let i = 0; i < sourceBlock.inputList.length; i++) {
const sourceInput = sourceBlock.inputList[i];
if (sourceInput.name === constants.COLLAPSED_INPUT_NAME) {
continue;
continue; // Ignore the collapsed input.
}
// Ignore the collapsed input.
const resultInput = result.inputList[i];
if (!resultInput) {
throw new Error(DUPLICATE_BLOCK_ERROR.replace('%1', 'an input'));
@@ -395,8 +394,7 @@ export class InsertionMarkerManager {
console.error(
'Only one of localConnection_ and closestConnection_ was set.');
}
} else {
// No connection found.
} else { // No connection found.
// Only need to update if we were showing a preview before.
return !!(this.localConnection_ && this.closestConnection_);
}
+1 -2
View File
@@ -516,9 +516,8 @@ export class Mutator extends Icon {
static reconnect(
connectionChild: Connection, block: Block, inputName: string): boolean {
if (!connectionChild || !connectionChild.getSourceBlock().workspace) {
return false;
return false; // No connection or block has been deleted.
}
// No connection or block has been deleted.
const connectionParent = block.getInput(inputName)!.connection;
const currentParent = connectionChild.targetBlock();
if ((!currentParent || currentParent === block) && connectionParent &&
+3 -6
View File
@@ -97,8 +97,7 @@ export function getStartPositionRect(
if (hasVerticalScrollbar && workspace.RTL) {
left += Scrollbar.scrollbarThickness;
}
} else {
// position.horizontal === horizontalPosition.RIGHT
} else { // position.horizontal === horizontalPosition.RIGHT
left = metrics.absoluteMetrics.left + metrics.viewMetrics.width -
size.width - horizontalPadding;
if (hasVerticalScrollbar && !workspace.RTL) {
@@ -109,8 +108,7 @@ export function getStartPositionRect(
let top = 0;
if (position.vertical === verticalPosition.TOP) {
top = metrics.absoluteMetrics.top + verticalPadding;
} else {
// position.vertical === verticalPosition.BOTTOM
} else { // position.vertical === verticalPosition.BOTTOM
top = metrics.absoluteMetrics.top + metrics.viewMetrics.height -
size.height - verticalPadding;
if (workspace.scrollbar && workspace.scrollbar.canScrollHorizontally()) {
@@ -173,8 +171,7 @@ export function bumpPositionRect(
if (boundingRect.intersects(otherEl)) {
if (bumpDir === bumpDirection.UP) {
top = otherEl.top - height - margin;
} else {
// bumpDir === bumpDirection.DOWN
} else { // bumpDir === bumpDirection.DOWN
top = otherEl.bottom + margin;
}
// Recheck other savedPositions
+1 -2
View File
@@ -440,10 +440,9 @@ export function getDefinition(name: string, workspace: Workspace): Block|null {
if (procedureBlock.getProcedureDef) {
const tuple = procedureBlock.getProcedureDef();
if (tuple && Names.equals(tuple[0], name)) {
return blocks[i];
return blocks[i]; // Can't use procedureBlock var due to type check.
}
}
}
// Can't use procedureBlock var due to type check.
return null;
}
+2 -2
View File
@@ -37,12 +37,12 @@ import * as svgPaths from './utils/svg_paths.js';
/** A shape that has a pathDown property. */
interface PathDownShape {
pathDown: string;
} // eslint-disable-line no-unused-vars
}
/** A shape that has a pathLeft property. */
interface PathLeftShape {
pathLeft: string;
} // eslint-disable-line no-unused-vars
}
/** Maximum randomness in workspace units for bumping a block. */
const BUMP_RANDOMNESS = 10;
+3 -6
View File
@@ -224,13 +224,13 @@ export class ConstantProvider {
* ``setFontConstants_`` to be the height of the text based on the font
* used.
*/
FIELD_TEXT_HEIGHT: number = -1;
FIELD_TEXT_HEIGHT: number = -1; // Dynamically set.
/**
* Text baseline. This constant is dynamically set in ``setFontConstants_``
* to be the baseline of the text based on the font used.
*/
FIELD_TEXT_BASELINE: number = -1;
FIELD_TEXT_BASELINE: number = -1; // Dynamically set.
/** A field's border rect corner radius. */
FIELD_BORDER_RECT_RADIUS = 4;
@@ -462,8 +462,6 @@ export class ConstantProvider {
this.EMPTY_STATEMENT_INPUT_HEIGHT = this.MIN_BLOCK_HEIGHT;
this.START_POINT = svgPaths.moveBy(0, 0);
// Dynamically set.
// Dynamically set.
/** A field's text element's dominant baseline. */
this.FIELD_TEXT_BASELINE_CENTER = !userAgent.IE && !userAgent.EDGE;
@@ -773,8 +771,7 @@ export class ConstantProvider {
const halfHeight = height / 2;
const control1Y = halfHeight + overlap;
const control2Y = halfHeight + 0.5;
const control3Y = overlap;
// 2.5
const control3Y = overlap; // 2.5
const endPoint1 = svgPaths.point(-width, forward * halfHeight);
const endPoint2 = svgPaths.point(width, forward * halfHeight);
+1 -2
View File
@@ -440,8 +440,7 @@ export class Drawer {
if (bottomRow.connection) {
const connInfo = bottomRow.connection;
const x = connInfo.xPos;
// Already contains info about startX.
const x = connInfo.xPos; // Already contains info about startX.
const connX = this.info_.RTL ? -x : x;
connInfo.connectionModel.setOffsetInBlock(connX, bottomRow.baseline);
}
+1 -2
View File
@@ -171,8 +171,7 @@ export class Drawer extends BaseDrawer {
if (bottomRow.connection) {
const connInfo = bottomRow.connection;
const x = connInfo.xPos;
// Already contains info about startX.
const x = connInfo.xPos; // Already contains info about startX.
const connX =
(this.info_.RTL ? -x : x) + this.constants_.DARK_PATH_OFFSET / 2;
connInfo.connectionModel.setOffsetInBlock(
+25 -50
View File
@@ -28,57 +28,32 @@ import {Row} from './row.js';
class TypesContainer {
[index: string]: number|Function;
NONE = 0;
// None
FIELD = 1 << 0;
// Field.
HAT = 1 << 1;
// Hat.
ICON = 1 << 2;
// Icon.
SPACER = 1 << 3;
// Spacer.
BETWEEN_ROW_SPACER = 1 << 4;
// Between Row Spacer.
IN_ROW_SPACER = 1 << 5;
// In Row Spacer.
EXTERNAL_VALUE_INPUT = 1 << 6;
// External Value Input.
INPUT = 1 << 7;
// Input.
INLINE_INPUT = 1 << 8;
// Inline Input.
STATEMENT_INPUT = 1 << 9;
// Statement Input.
CONNECTION = 1 << 10;
// Connection.
PREVIOUS_CONNECTION = 1 << 11;
// Previous Connection.
NEXT_CONNECTION = 1 << 12;
// Next Connection.
OUTPUT_CONNECTION = 1 << 13;
// Output Connection.
CORNER = 1 << 14;
// Corner.
LEFT_SQUARE_CORNER = 1 << 15;
// Square Corner.
LEFT_ROUND_CORNER = 1 << 16;
// Round Corner.
RIGHT_SQUARE_CORNER = 1 << 17;
// Right Square Corner.
RIGHT_ROUND_CORNER = 1 << 18;
// Right Round Corner.
JAGGED_EDGE = 1 << 19;
// Jagged Edge.
ROW = 1 << 20;
// Row.
TOP_ROW = 1 << 21;
// Top Row.
BOTTOM_ROW = 1 << 22;
// Bottom Row.
INPUT_ROW = 1 << 23;
NONE = 0; // None
FIELD = 1 << 0; // Field.
HAT = 1 << 1; // Hat.
ICON = 1 << 2; // Icon.
SPACER = 1 << 3; // Spacer.
BETWEEN_ROW_SPACER = 1 << 4; // Between Row Spacer.
IN_ROW_SPACER = 1 << 5; // In Row Spacer.
EXTERNAL_VALUE_INPUT = 1 << 6; // External Value Input.
INPUT = 1 << 7; // Input.
INLINE_INPUT = 1 << 8; // Inline Input.
STATEMENT_INPUT = 1 << 9; // Statement Input.
CONNECTION = 1 << 10; // Connection.
PREVIOUS_CONNECTION = 1 << 11; // Previous Connection.
NEXT_CONNECTION = 1 << 12; // Next Connection.
OUTPUT_CONNECTION = 1 << 13; // Output Connection.
CORNER = 1 << 14; // Corner.
LEFT_SQUARE_CORNER = 1 << 15; // Square Corner.
LEFT_ROUND_CORNER = 1 << 16; // Round Corner.
RIGHT_SQUARE_CORNER = 1 << 17; // Right Square Corner.
RIGHT_ROUND_CORNER = 1 << 18; // Right Round Corner.
JAGGED_EDGE = 1 << 19; // Jagged Edge.
ROW = 1 << 20; // Row.
TOP_ROW = 1 << 21; // Top Row.
BOTTOM_ROW = 1 << 22; // Bottom Row.
INPUT_ROW = 1 << 23; // Input Row.
// Input Row.
/**
* A Left Corner Union Type.
* @internal
+5 -6
View File
@@ -243,24 +243,23 @@ export class ConstantProvider extends BaseConstantProvider {
0: 5 * this.GRID_UNIT, // Field in hexagon.
1: 2 * this.GRID_UNIT, // Hexagon in hexagon.
2: 5 * this.GRID_UNIT, // Round in hexagon.
3: 5 * this.GRID_UNIT,
}, // Square in hexagon.
3: 5 * this.GRID_UNIT, // Square in hexagon.
},
2: {
// Outer shape: round.
0: 3 * this.GRID_UNIT, // Field in round.
1: 3 * this.GRID_UNIT, // Hexagon in round.
2: 1 * this.GRID_UNIT, // Round in round.
3: 2 * this.GRID_UNIT,
}, // Square in round.
3: 2 * this.GRID_UNIT, // Square in round.
},
3: {
// Outer shape: square.
0: 2 * this.GRID_UNIT, // Field in square.
1: 2 * this.GRID_UNIT, // Hexagon in square.
2: 2 * this.GRID_UNIT, // Round in square.
3: 2 * this.GRID_UNIT,
3: 2 * this.GRID_UNIT, // Square in square.
},
};
// Square in square.
this.FIELD_TEXT_FONTSIZE = 3 * this.GRID_UNIT;
+1 -2
View File
@@ -664,8 +664,7 @@ export class Scrollbar {
*/
private onMouseDownBar_(e: Event) {
this.workspace.markFocused();
Touch.clearTouchIdentifier();
// This is really a click.
Touch.clearTouchIdentifier(); // This is really a click.
this.cleanUp_();
if (browserEvents.isRightButton(e)) {
// Right-click.
+1 -2
View File
@@ -488,8 +488,7 @@ function tryToConnectParent(
throw new MissingConnection('output', child, state);
}
connected = parentConnection.connect(childConnection);
} else {
// Statement type.
} else { // Statement type.
childConnection = child.previousConnection;
if (!childConnection) {
throw new MissingConnection('previous', child, state);
+3 -6
View File
@@ -492,8 +492,7 @@ export class Toolbox extends DeleteArea implements IAutoHideable,
return new Rect(top, BIG_NUM, -BIG_NUM, BIG_NUM);
} else if (this.toolboxPosition === toolbox.Position.LEFT) {
return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, right);
} else {
// Right
} else { // Right
return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM);
}
}
@@ -665,15 +664,13 @@ export class Toolbox extends DeleteArea implements IAutoHideable,
this.width_ = workspaceMetrics.viewWidth;
if (this.toolboxPosition === toolbox.Position.TOP) {
toolboxDiv.style.top = '0';
} else {
// Bottom
} else { // Bottom
toolboxDiv.style.bottom = '0';
}
} else {
if (this.toolboxPosition === toolbox.Position.RIGHT) {
toolboxDiv.style.right = '0';
} else {
// Left
} else { // Left
toolboxDiv.style.left = '0';
}
toolboxDiv.style.height = '100%';
+1 -2
View File
@@ -198,9 +198,8 @@ function getTargetObject(obj: object|null): {tooltip: AnyDuringMigration}|null {
*/
export function createDom() {
if (containerDiv) {
return;
return; // Already created.
}
// Already created.
// Create an HTML container for popup overlays (e.g. editor widgets).
containerDiv = document.createElement('div');
containerDiv.className = 'blocklyTooltipDiv';
+2 -3
View File
@@ -29,7 +29,7 @@ interface PseudoEvent {
target: Element;
stopPropagation: () => void;
preventDefault: () => void;
} // eslint-disable-line no-unused-vars
}
/** Length in ms for a touch to become a long press. */
const LONGPRESS = 750;
@@ -100,8 +100,7 @@ export function longStart(e: Event, gesture: Gesture) {
// Additional check to distinguish between touch events and pointer events
if (typelessEvent.changedTouches) {
// TouchEvent
typelessEvent.button = 2;
// Simulate a right button click.
typelessEvent.button = 2; // Simulate a right button click.
// e was a touch event. It needs to pretend to be a mouse event.
typelessEvent.clientX = typelessEvent.changedTouches[0].clientX;
typelessEvent.clientY = typelessEvent.changedTouches[0].clientY;
+2 -2
View File
@@ -82,8 +82,8 @@ export function createSvgElement<T extends SVGElement>(
// IE defines a unique attribute "runtimeStyle", it is NOT applied to
// elements created with createElementNS. However, Closure checks for IE
// and assumes the presence of the attribute and crashes.
if ((document.body as any).runtimeStyle) {
// Indicates presence of IE-only attr.
if ((document.body as any)
.runtimeStyle) { // Indicates presence of IE-only attr.
(e as any).runtimeStyle = (e as any).currentStyle = e.style;
}
if (opt_parent) {
+73 -87
View File
@@ -44,8 +44,7 @@ function tokenizeInterpolationInternal(
let number = null;
for (let i = 0; i < chars.length; i++) {
const c = chars[i];
if (state === 0) {
// Start escape.
if (state === 0) { // Start escape.
if (c === '%') {
const text = buffer.join('');
if (text) {
@@ -54,96 +53,84 @@ function tokenizeInterpolationInternal(
buffer.length = 0;
state = 1;
} else {
buffer.push(c); // Regular char.
}
} else if (state === 1) {
if (c === '%') {
buffer.push(c); // Escaped %: %%
state = 0;
} else if (parseInterpolationTokens && '0' <= c && c <= '9') {
state = 2;
number = c;
const text = buffer.join('');
if (text) {
tokens.push(text);
}
buffer.length = 0;
} else if (c === '{') {
state = 3;
} else {
buffer.push('%', c); // Not recognized. Return as literal.
state = 0;
}
} else if (state === 2) {
if ('0' <= c && c <= '9') {
number += c; // Multi-digit number.
} else {
tokens.push(parseInt(number ?? '', 10));
i--; // Parse this char again.
state = 0;
}
} else if (state === 3) { // String table reference
if (c === '') {
// Premature end before closing '}'
buffer.splice(0, 0, '%{'); // Re-insert leading delimiter
i--; // Parse this char again.
state = 0; // and parse as string literal.
} else if (c !== '}') {
buffer.push(c);
}
} else // Regular char.
if (state === 1) {
if (c === '%') {
buffer.push(c);
// Escaped %: %%
state = 0;
} else if (parseInterpolationTokens && '0' <= c && c <= '9') {
state = 2;
number = c;
const text = buffer.join('');
if (text) {
tokens.push(text);
}
buffer.length = 0;
} else if (c === '{') {
state = 3;
} else {
buffer.push('%', c);
// Not recognized. Return as literal.
state = 0;
}
} else if (state === 2) {
// Multi-digit number.
if ('0' <= c && c <= '9') {
number += c;
} else // Multi-digit number.
{
tokens.push(parseInt(number ?? '', 10));
i--;
// Parse this char again.
state = 0;
}
} else if (state === 3) {
// String table reference
if (c === '') {
// Premature end before closing '}'
buffer.splice(0, 0, '%{');
// Re-insert leading delimiter
i--;
// Parse this char again.
state = 0;
} else // and parse as string literal.
if (c !== '}') {
buffer.push(c);
} else {
const rawKey = buffer.join('');
if (/[A-Z]\w*/i.test(rawKey)) { // Strict matching
// Found a valid string key. Attempt case insensitive match.
const keyUpper = rawKey.toUpperCase();
} else {
const rawKey = buffer.join('');
if (/[A-Z]\w*/i.test(rawKey)) { // Strict matching
// Found a valid string key. Attempt case insensitive match.
const keyUpper = rawKey.toUpperCase();
// BKY_ is the prefix used to namespace the strings used in
// Blockly core files and the predefined blocks in ../blocks/.
// These strings are defined in ../msgs/ files.
const bklyKey =
keyUpper.startsWith('BKY_') ? keyUpper.substring(4) : null;
if (bklyKey && bklyKey in Msg) {
const rawValue = Msg[bklyKey];
if (typeof rawValue === 'string') {
// Attempt to dereference substrings, too, appending to the
// end.
Array.prototype.push.apply(
tokens,
tokenizeInterpolationInternal(
rawValue, parseInterpolationTokens));
} else if (parseInterpolationTokens) {
// When parsing interpolation tokens, numbers are special
// placeholders (%1, %2, etc). Make sure all other values are
// strings.
tokens.push(String(rawValue));
} else {
tokens.push(rawValue);
}
} else {
// No entry found in the string table. Pass reference as string.
tokens.push('%{' + rawKey + '}');
}
buffer.length = 0;
// Clear the array
state = 0;
// BKY_ is the prefix used to namespace the strings used in
// Blockly core files and the predefined blocks in ../blocks/.
// These strings are defined in ../msgs/ files.
const bklyKey =
keyUpper.startsWith('BKY_') ? keyUpper.substring(4) : null;
if (bklyKey && bklyKey in Msg) {
const rawValue = Msg[bklyKey];
if (typeof rawValue === 'string') {
// Attempt to dereference substrings, too, appending to the
// end.
Array.prototype.push.apply(
tokens,
tokenizeInterpolationInternal(
rawValue, parseInterpolationTokens));
} else if (parseInterpolationTokens) {
// When parsing interpolation tokens, numbers are special
// placeholders (%1, %2, etc). Make sure all other values are
// strings.
tokens.push(String(rawValue));
} else {
tokens.push('%{' + rawKey + '}');
buffer.length = 0;
state = 0;
tokens.push(rawValue);
}
} else {
// No entry found in the string table. Pass reference as string.
tokens.push('%{' + rawKey + '}');
}
buffer.length = 0; // Clear the array
state = 0;
} else {
tokens.push('%{' + rawKey + '}');
buffer.length = 0;
state = 0; // and parse as string literal.
}
}
}
}
// and parse as string literal.
let text = buffer.join('');
if (text) {
tokens.push(text);
@@ -228,11 +215,10 @@ export function checkMessageReferences(message: string): boolean {
const msgKey = m[i].toUpperCase();
if (msgTable[msgKey.slice(6, -1)] === undefined) {
console.warn('No message string for ' + m[i] + ' in ' + message);
validSoFar = false;
validSoFar = false; // Continue to report other errors.
}
}
}
// Continue to report other errors.
return validSoFar;
}
+4 -8
View File
@@ -304,11 +304,9 @@ export function createVariableButtonHandler(
msg = msg.replace('%1', existing.name).replace('%2', existing.type);
}
dialog.alert(msg, function() {
promptAndCheckWithAlert( // Recurse
text);
promptAndCheckWithAlert(text);
});
} else // Recurse
{
} else {
// No conflict
workspace.createVariable(text, type);
if (opt_callback) {
@@ -353,11 +351,9 @@ export function renameVariable(
.replace('%1', existing.name)
.replace('%2', existing.type);
dialog.alert(msg, function() {
promptAndCheckWithAlert( // Recurse
newName);
promptAndCheckWithAlert(newName);
});
} else // Recurse
{
} else {
workspace.renameVariableById(variable.getId(), newName);
if (opt_callback) {
opt_callback(newName);
+1 -2
View File
@@ -72,9 +72,8 @@ export function testOnly_setDiv(newDiv: HTMLDivElement|null) {
*/
export function createDom() {
if (containerDiv) {
return;
return; // Already created.
}
// Already created.
containerDiv = document.createElement('div') as HTMLDivElement;
containerDiv.className = 'blocklyWidgetDiv';
+1 -2
View File
@@ -580,8 +580,7 @@ export class WorkspaceCommentSvg extends WorkspaceComment implements
* @internal
*/
override toXmlWithXY(opt_noId?: boolean): Element {
let width = 0;
// Not used in LTR.
let width = 0; // Not used in LTR.
if (this.workspace.RTL) {
// Here be performance dragons: This calls getMetrics().
width = this.workspace.getWidth();
+1 -2
View File
@@ -58,9 +58,8 @@ export class WorkspaceDragSurfaceSvg {
/** Create the drag surface and inject it into the container. */
createDom() {
if (this.SVG_) {
return;
return; // Already created.
}
// Already created.
/**
* Dom structure when the workspace is being dragged. If there is no drag in
* progress, the SVG is empty and display: none.
+5 -10
View File
@@ -1432,8 +1432,7 @@ export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
if (!this.rendered || !state['type'] && !state['tagName']) {
return null;
}
if (this.currentGesture_) {
// Dragging while pasting? No.
if (this.currentGesture_) { // Dragging while pasting? No.
this.currentGesture_.cancel();
}
@@ -1852,9 +1851,8 @@ export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
// This is needed as for some browser/system combinations which do not
// set deltaX.
x = this.scrollX - scrollDelta.y;
y = this.scrollY;
y = this.scrollY; // Don't scroll vertically.
}
// Don't scroll vertically.
this.scroll(x, y);
}
e.preventDefault();
@@ -1956,9 +1954,8 @@ export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
if (this.options.languageTree) {
throw Error('Can\'t nullify an existing toolbox.');
}
return;
return; // No change (null to null).
}
// No change (null to null).
if (!this.options.languageTree) {
throw Error('Existing toolbox is null. Can\'t create new toolbox.');
}
@@ -2046,9 +2043,8 @@ export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
let scaleChange = Math.pow(speed, amount);
const newScale = this.scale * scaleChange;
if (this.scale === newScale) {
return;
return; // No change in zoom.
}
// No change in zoom.
// Clamp scale within valid range.
if (newScale > this.options.zoomOptions.maxScale) {
@@ -2122,9 +2118,8 @@ export class WorkspaceSvg extends Workspace implements IASTNodeLocationSvg {
let blocksWidth = blocksBox.right - blocksBox.left + doubleMargin;
let blocksHeight = blocksBox.bottom - blocksBox.top + doubleMargin;
if (!blocksWidth) {
return;
return; // Prevents zooming to infinity.
}
// Prevents zooming to infinity.
if (this.flyout_) {
// We have to add the flyout size to both the workspace size and the
// block size because the blocks we want to resize include the blocks in
+14 -27
View File
@@ -107,8 +107,7 @@ export function variablesToDom(variableList: VariableModel[]): Element {
*/
export function blockToDomWithXY(block: Block, opt_noId?: boolean): Element|
DocumentFragment {
if (block.isInsertionMarker()) {
// Skip over insertion markers.
if (block.isInsertionMarker()) { // Skip over insertion markers.
block = block.getChildren(false)[0];
if (!block) {
// Disappears when appended.
@@ -116,8 +115,7 @@ export function blockToDomWithXY(block: Block, opt_noId?: boolean): Element|
}
}
let width = 0;
// Not used in LTR.
let width = 0; // Not used in LTR.
if (block.workspace?.RTL) {
width = block.workspace.getWidth();
}
@@ -437,13 +435,11 @@ export function clearWorkspaceAndLoadFromXml(
* @alias Blockly.Xml.domToWorkspace
*/
export function domToWorkspace(xml: Element, workspace: Workspace): string[] {
let width = 0;
// Not used in LTR.
let width = 0; // Not used in LTR.
if (workspace.RTL) {
width = workspace.getWidth();
}
const newBlockIds = [];
// A list of block IDs added by this call.
const newBlockIds = []; // A list of block IDs added by this call.
dom.startTextWidthCache();
const existingGroup = eventUtils.getGroup();
if (!existingGroup) {
@@ -539,22 +535,15 @@ export function appendDomToWorkspace(
const bbox = (workspace as WorkspaceSvg).getBlocksBoundingBox();
// Load the new blocks into the workspace and get the IDs of the new blocks.
const newBlockIds = domToWorkspace(xml, workspace);
if (bbox && bbox.top !== bbox.bottom) {
// check if any previous block
let offsetY = 0;
// offset to add to y of the new block
if (bbox && bbox.top !== bbox.bottom) { // Check if any previous block.
let offsetY = 0; // Offset to add to y of the new block.
let offsetX = 0;
const farY = bbox.bottom;
// bottom position
const topX = workspace.RTL ? bbox.right : bbox.left;
// x of bounding box
const farY = bbox.bottom; // Bottom position.
const topX = workspace.RTL ? bbox.right : bbox.left; // X of bounding box.
// Check position of the new blocks.
let newLeftX = Infinity;
// x of top left corner
let newRightX = -Infinity;
// x of top right corner
let newY = Infinity;
// y of top corner
let newLeftX = Infinity; // X of top left corner.
let newRightX = -Infinity; // X of top right corner.
let newY = Infinity; // Y of top corner.
const ySeparation = 10;
for (let i = 0; i < newBlockIds.length; i++) {
const blockXY =
@@ -562,12 +551,10 @@ export function appendDomToWorkspace(
if (blockXY.y < newY) {
newY = blockXY.y;
}
if (blockXY.x < newLeftX) {
// if we left align also on x
if (blockXY.x < newLeftX) { // if we left align also on x
newLeftX = blockXY.x;
}
if (blockXY.x > newRightX) {
// if we right align also on x
if (blockXY.x > newRightX) { // if we right align also on x
newRightX = blockXY.x;
}
}
@@ -673,7 +660,7 @@ interface childNodeTagMap {
field: Element[];
input: Element[];
next: Element[];
} // eslint-disable-line no-unused-vars
}
/**
* Creates a mapping of childNodes for each supported XML tag for the provided
+8 -12
View File
@@ -346,13 +346,11 @@ export class ZoomControls implements IPositionable {
this.workspace.markFocused();
this.workspace.zoomCenter(amount);
this.fireZoomEvent_();
Touch.clearTouchIdentifier();
// Don't block future drags.
e.stopPropagation();
// Don't start a workspace scroll.
e.preventDefault();
Touch.clearTouchIdentifier(); // Don't block future drags.
e.stopPropagation(); // Don't start a workspace scroll.
e.preventDefault(); // Stop double-clicking from selecting text.
}
// Stop double-clicking from selecting text.
/**
* Create the zoom reset icon and its event handler.
* @param rnd The random string to use as a suffix in the clip path's ID.
@@ -416,13 +414,11 @@ export class ZoomControls implements IPositionable {
setTimeout(this.workspace.endCanvasTransition.bind(this.workspace), 500);
this.fireZoomEvent_();
Touch.clearTouchIdentifier();
// Don't block future drags.
e.stopPropagation();
// Don't start a workspace scroll.
e.preventDefault();
Touch.clearTouchIdentifier(); // Don't block future drags.
e.stopPropagation(); // Don't start a workspace scroll.
e.preventDefault(); // Stop double-clicking from selecting text.
}
// Stop double-clicking from selecting text.
/** Fires a zoom control UI event. */
private fireZoomEvent_() {
const uiEvent = new (eventUtils.get(eventUtils.CLICK))!