Files
blockly/core/renderers/zelos/info.ts
Beka Westberg 21d90696d1 chore: Migrate core/ to Typescript, actually (#6299)
* fix: convert files to typescript

* fix: add alias for AnyDuringMigration so that tsc will run

* chore: format

* chore: enable ts for the clang-format workflow (#6233)

* chore: Restore @fileoverview comment locations (#6237)

* chore: add declareModuleId (#6238)

* fix: Revert comment change to app_controller.js (#6241)

* fix: Add missing import goog statements (#6240)

I've added the import statement immediately before the
goog.declareModuleId calls that depend on it.

There is an argument to be made that we should put the import
statement in their normal place amongst any other imports, and
move the declareModuleId statement to below the double blank
line below the imports, but as these are so tightly coupled,
replace the previous goog.module calls, and will both be deleted
at the same time once the transition to TypeScript is fully complete
I think it's fine (and certainly much easier) to do it this way.

* chore: Fix whitespace (#6243)

* fix: Remove spurious blank lines

  Remove extraneous blank lines introduced by deletion of
  'use strict'; pragmas.

  Also fix the location of the goog.declareModuleId call in
  core/utils/array.ts.

* fix: Add missing double-blank-line before body of modules

  Our convention is to have two blank lines between the imports (or
  module ID, if there are no imports) and the beginning of the body
  of the module.  Enforce this.

* fix: one addition format error for PR #6243

* fix(build): Skip npm prepare when running in CI (#6244)

Have npm prepare do nothing when running in CI.

We don't need to do any building, because npm test will build
everything needed in the workflows in which it is run, and we
don't want to build anything in other workflows because a tsc
error would prevent those workflows from completing.

* fix: re-add `@package` annotations as `@internal` annotations (#6232)

* fix: add ~70% of internal attributes

* fix: work on manually adding more @internal annotations

* fix: add more manual internal annotations

* fix: rename package typos to internal

* fix: final manual fixes for internal annotations

* chore: format

* chore: make unnecessary multiline jsdoc a single line

* fix: fix internal tags in serialization exceptions

* fix: tsc errors picked up from develop (#6224)

* fix: relative path for deprecation utils

* fix: checking if properties exist in svg_math

* fix: set all timeout PIDs to AnyDuringMigration

* fix: make nullability errors explicity in block drag surface

* fix: make null check in events_block_change explicit

* fix: make getEventWorkspace_ internal so we can access it from CommentCreateDeleteHelper

* fix: rename DIV -> containerDiv in tooltip

* fix: ignore backwards compat check in category

* fix: set block styles to AnyDuringMigration

* fix: type typo in KeyboardShortcut

* fix: constants name in row measurables

* fix: typecast in mutator

* fix: populateProcedures type of flattened array

* fix: ignore errors related to workspace comment deserialization

* chore: format files

* fix: renaming imports missing file extensions

* fix: remove check for sound.play

* fix: temporarily remove bad requireType.

All `export type` statements are stripped when tsc is run. This means
that when we attempt to require BlockDefinition from the block files, we
get an error because it does not exist.

We decided to temporarily remove the require, because this will no
longer be a problem when we conver the blocks to typescript, and
everything gets compiled together.

* fix: bad jsdoc in array

* fix: silence missing property errors

Closure was complaining about inexistant properties, but they actually
do exist, they're just not being transpiled by tsc in a way that closure
understands.

I.E. if things are initialized in a function called by the constructor,
rather than in a class field or in the custructor itself, closure would
error.

It would also error on enums, because they are transpiled to a weird
IIFE.

* fix: context menu action handler not knowing the type of this.

this: TypeX information gets stripped when tsc is run, so closure could
not know that this was not global. Fixed this by reorganizing to use the
option object directly instead of passing it to onAction to be bound to
this.

* fix: readd getDeveloperVars checks (should not be part of migration)

This was found because ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE was no
longer being accessed.

* fix: silence closure errors about overriding supertype props

We propertly define the overrides in typescript, but these get removed
from the compiled output, so closure doesn't know they exist.

* fix: silence globalThis errors

this: TypeX annotations get stripped from the compiled output, so
closure can't know that we're accessing the correct things. However,
typescript makes sure that this always has the correct properties, so
silencing this should be fine.

* fix: bad jsdoc name

* chore: attempt compiling with blockly.js

* fix: attempt moving the import statement above the namespace line

* chore: add todo comments to block def files

* chore: remove todo from context menu

* chore: add comments abotu disabled errors

* 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

* fix: Correct enum formatting, use merged `namespace`s for types that are class static members (#6246)

* fix: formatting of enum KeyCodes

* fix: Use merged namespace for ContextMenuRegistry static types

  - Create a namespace to be merged with the ContextMenuRegistry
    class containing the types that were formerly declared as static
    properties on that class.

  - Use type aliases to export them individually as well, for
    compatibility with the changes made by MigranTS (and/or
    @gonfunko) to how other modules in core/ now import these
    types.

  - Update renamings.json5 to reflect the availability of the
    direct exports for modules that import this module directly
    (though they are not available to, and will not be used by,
    code that imports only via blockly.js/blockly.ts.)

* fix: Use merged namespace for Input.Align

  - Create a merged namespace for the Input.Align enum.

  - Use type/const aliases to export it as Input too.

  - Update renamings.json5 to reflect the availability of the
    direct export.

* fix: Use merged namespace for Names.NameType

  - Create a merged namespace for the Names.NameType enum.

  - Use type/const aliases to export it as NameType too.

  - Update renamings.json5 to reflect the availability of the
    direct export.  (This ought to have happened in an earlier
    version as it was already available by both routes.)

* chore: Fix minor issues for PR #6246

  - Use `Align` instead of `Input.Align` where possible.

* fix(build): Suppress irrelevant JSC_UNUSED_LOCAL_ASSIGNMENT errors

  tsc generates code for merged namespaces that looks like:

      (function (ClassName) {
          let EnumName;
          (function (EnumName) {
              EnumName[EnumNameAlign["v1"] = 0] = "v1";
              // etc.
          })(EnumName = ClassName.EnumName || (ClassName.EnumName = {}));
      })(ClassName || (ClassName = {}));

  and Closure Compiler complains about the fact that the EnumName let
  binding is initialised but never used.  (It exists so that any other
  code that was in the namespace could see the enum.)

  Suppress this message, since it is not actionable and lint and/or tsc
  should tell us if we have actual unused variables in our .ts files.

* chore(build): Suppress spurious warnings from closure-make-deps (#6253)

A little bit of an ugly hack, but it works: pipe stderr through
grep -v to suppress error output starting with "WARNING in".

* fix: remaining enums that weren't properly exported (#6251)

* fix: remaining enums that weren't properly exported

* chore: format

* fix: add enum value exports

* chore: format

* fix: properly export interfaces that were typedefs (#6250)

* fix: properly export interfaces that were typedefs

* fix: allowCollsion -> allowCollision

* fix: convert unconverted enums

* fix: enums that were/are instance properties

* fix: revert changes to property enums

* fix: renamed protected parameter properties (#6252)

* fix: bad protected parameter properties

* chore:format

* fix: gesture constructor

* fix: overridden properties that were renamed

* refactor: Migrate `blockly.js` to TypeScript (#6261)

* chore: Apply changes to blockly.js to blockly.ts

* fix: Build using core/blockly.ts instead of .js

  Compiles and runs in compressed mode correctly!

* fix(build): Don't depend on execSync running bash (#6262)

For some reason on Github CI servers execSync uses /bin/sh, which
is (on Ubuntu) dash rather than bash, and does not understand
the pipefail option.

So remove the grep pipe on stderr and just discard all error output
at all.

This is not ideal as errors in test deps will go unreported AND
not even cause test failure, but it's not clear that it's worth
investing more time to fix this at the moment.

* chore: use `import type` where possible (#6279)

* chore: automatically change imports to import types

* chore: revert changes that actually need to be imports

* chore: format

* chore: add more import type statements based on importsNotUsedAsValues

* chore: fix tsconfig

* chore: add link to compiler issue

* fix: add type information to blockly options (#6283)

* fix: add type information to blockly options

* chore: format

* chore: remove erroneous comment

* fix: bugs revealed by getting the built output working (#6282)

* fix: types of compose and decompose in block

* fix: workspace naming in toolbox

* chore: add jsdoc

* chore: restore registry comments to better positions

* chore: pr comments'

* fix(variables): Revert inadvertent change to allDeveloperVariables (#6290)

It appears that a function call got modified incorrectly (probably
in an effort to fix a typing issue).  This fix trivially reverts
the line in question to match the original JS version from develop.

This causes the generator tests to pass.

* fix: circular dependencies (#6281)

* chore: fix circular dependencies w/ static workspace funcs

* remove preserved imports that aren't currently necessary (probably)

* fix circular dependency with workspaces and block using stub

* fix dependency between variables and xml by moving function to utils

* add stub for trashcan as well

* fix line endings from rebase

* fix goog/base order

* add trashcan patch

* fix: types of compose and decompose in block

* fix: workspace naming in toolbox

* chore: add jsdoc

* chore: restore registry comments to better positions

* chore: remove implementations in goog.js

* chore: fix types of stubs

* chore: remove added AnyDuringMigration casts

* chore: remove modifications to xml and variables

* chore: format

* chore: remove event requirements in workspace comments

* chore: fix circular dependency with xml and workspace comments

* fixup remove ContextMenu import

* chore: fix dependency between mutator and workspace

* chore: break circular dependency between names and procedures

* chore: get tests to run?

* chore: pr comments'

* chore: fix stubbing field registry fromJson

* chore: fix spying on fire

* chore: fix stubbing parts of connection checker

* chore: fix stubbing dialog

* chore: fix stubbing style

* chore: fix spying on duplicate

* chore: fix stubbing variables

* chore: fix stubbing copy

* chore: fix stubbing in workspace

* chore: remove unnecessary stubs

* chore: fix formatting

* chore: fix other formatting

* chore: add backwards compatible static properties to workspace

* chore: move static type properties

* chore: move and comment stubs

* chore: add newlines at EOF

* chore: improve errors for monkey patched functions

* chore: update comment with a pointer to the doc

* chore: update comment with a pointer to the doc

* chore: format

* chore: revert changes to playground used for testing (#6292)

* chore: get mocha tests to pass. (#6291)

* chore: fix undo and empty code blocks

* chore: skip IE test

* chore: fix gesture test

* chore: fix replace message references test

* chore: fix string table interpolation

* chore: skip getById tests

* chore: fix field tests

* chore: fix console errors by making workspace nullable

* chore: format

* chore: fix definition overwrite warning

* chore: update metadata

* chore: temporarily modify the the advanced compile test

* chore: fix gestures by fixing test instead

Co-authored-by: Neil Fraser <fraser@google.com>
Co-authored-by: Christopher Allen <cpcallen+git@google.com>
2022-08-02 10:30:13 -07:00

594 lines
22 KiB
TypeScript

/**
* @fileoverview Makecode/scratch-style renderer.
* Zelos: spirit of eager rivalry, emulation, envy, jealousy, and zeal.
*/
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Makecode/scratch-style renderer.
* @class
*/
import * as goog from '../../../closure/goog/goog.js';
goog.declareModuleId('Blockly.zelos.RenderInfo');
import type {BlockSvg} from '../../block_svg.js';
import {FieldImage} from '../../field_image.js';
import {FieldLabel} from '../../field_label.js';
import {FieldTextInput} from '../../field_textinput.js';
import {Align, Input} from '../../input.js';
import {inputTypes} from '../../input_types.js';
import {RenderInfo as BaseRenderInfo} from '../common/info.js';
import type {Measurable} from '../measurables/base.js';
import {Field} from '../measurables/field.js';
import {InRowSpacer} from '../measurables/in_row_spacer.js';
import {InputConnection} from '../measurables/input_connection.js';
import type {Row} from '../measurables/row.js';
import type {SpacerRow} from '../measurables/spacer_row.js';
import {Types} from '../measurables/types.js';
import type {ConstantProvider, InsideCorners} from './constants.js';
import {BottomRow} from './measurables/bottom_row.js';
import {StatementInput} from './measurables/inputs.js';
import {RightConnectionShape} from './measurables/row_elements.js';
import {TopRow} from './measurables/top_row.js';
import type {PathObject} from './path_object.js';
import type {Renderer} from './renderer.js';
/**
* An object containing all sizing information needed to draw this block.
*
* This measure pass does not propagate changes to the block (although fields
* may choose to rerender when getSize() is called). However, calling it
* repeatedly may be expensive.
* @alias Blockly.zelos.RenderInfo
*/
export class RenderInfo extends BaseRenderInfo {
override topRow: TopRow;
override bottomRow: BottomRow;
override constants_: ConstantProvider;
override renderer_: Renderer;
override isInline = true;
isMultiRow: boolean;
hasStatementInput: boolean;
rightSide: RightConnectionShape|null;
private readonly rightAlignedDummyInputs_: WeakMap<Row, Input>;
/**
* @param renderer The renderer in use.
* @param block The block to measure.
* @internal
*/
constructor(renderer: Renderer, block: BlockSvg) {
super(renderer, block);
this.renderer_ = renderer;
this.constants_ = this.renderer_.getConstants();
/**
* An object with rendering information about the top row of the block.
*/
this.topRow = new TopRow(this.constants_);
/**
* An object with rendering information about the bottom row of the block.
*/
this.bottomRow = new BottomRow(this.constants_);
/**
* Whether the block should be rendered as a multi-line block, either
* because it's not inline or because it has been collapsed.
*/
this.isMultiRow = !block.getInputsInline() || block.isCollapsed();
/**
* Whether or not the block has a statement input in one of its rows.
*/
this.hasStatementInput = block.statementInputCount > 0;
/**
* An object with rendering information about the right connection shape.
*/
this.rightSide = this.outputConnection ?
new RightConnectionShape(this.constants_) :
null;
/**
* A map of rows to right aligned dummy inputs within those rows. Used to
* add padding between left and right aligned inputs.
*/
this.rightAlignedDummyInputs_ = new WeakMap();
}
/**
* Get the block renderer in use.
* @return The block renderer in use.
* @internal
*/
override getRenderer(): Renderer {
return this.renderer_ as Renderer;
}
override measure() {
// Modifying parent measure method to add `adjustXPosition_`.
this.createRows_();
this.addElemSpacing_();
this.addRowSpacing_();
this.adjustXPosition_();
this.computeBounds_();
this.alignRowElements_();
this.finalize_();
}
override shouldStartNewRow_(input: Input, lastInput: Input): boolean {
// If this is the first input, just add to the existing row.
// That row is either empty or has some icons in it.
if (!lastInput) {
return false;
}
// A statement input or an input following one always gets a new row.
if (input.type === inputTypes.STATEMENT ||
lastInput.type === inputTypes.STATEMENT) {
return true;
}
// Value and dummy inputs get new row if inputs are not inlined.
if (input.type === inputTypes.VALUE || input.type === inputTypes.DUMMY) {
return !this.isInline || this.isMultiRow;
}
return false;
}
override getDesiredRowWidth_(row: Row): number {
if (row.hasStatement) {
const rightCornerWidth =
(this.constants_.INSIDE_CORNERS as InsideCorners).rightWidth || 0;
return this.width - this.startX - rightCornerWidth;
}
return super.getDesiredRowWidth_(row);
}
override getInRowSpacing_(prev: Measurable|null, next: Measurable|null):
number {
if (!prev || !next) {
// No need for padding at the beginning or end of the row if the
// output shape is dynamic.
if (this.outputConnection && this.outputConnection.isDynamicShape &&
!this.hasStatementInput && !this.bottomRow.hasNextConnection) {
return this.constants_.NO_PADDING;
}
}
if (!prev) {
// Statement input padding.
if (next && Types.isStatementInput(next)) {
return this.constants_.STATEMENT_INPUT_PADDING_LEFT;
}
}
// Spacing between a rounded corner and a previous or next connection.
if (prev && Types.isLeftRoundedCorner(prev) && next) {
if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) {
return next.notchOffset - this.constants_.CORNER_RADIUS;
}
}
// Spacing between a square corner and a hat.
// AnyDuringMigration because: Property 'isHat' does not exist on type
// 'typeof Types'.
if (prev && Types.isLeftSquareCorner(prev) && next &&
(Types as AnyDuringMigration).isHat(next)) {
return this.constants_.NO_PADDING;
}
return this.constants_.MEDIUM_PADDING;
}
override getSpacerRowHeight_(prev: Row, next: Row): number {
// If we have an empty block add a spacer to increase the height.
if (Types.isTopRow(prev) && Types.isBottomRow(next)) {
return this.constants_.EMPTY_BLOCK_SPACER_HEIGHT;
}
const followsStatement = Types.isInputRow(prev) && prev.hasStatement;
const precedesStatement = Types.isInputRow(next) && next.hasStatement;
if (precedesStatement || followsStatement) {
const cornerHeight =
(this.constants_.INSIDE_CORNERS as InsideCorners).rightHeight || 0;
const height = Math.max(this.constants_.NOTCH_HEIGHT, cornerHeight);
return precedesStatement && followsStatement ?
Math.max(height, this.constants_.DUMMY_INPUT_MIN_HEIGHT) :
height;
}
// Top and bottom rows act as a spacer so we don't need any extra padding.
if (Types.isTopRow(prev)) {
const topRow = prev as TopRow;
if (!topRow.hasPreviousConnection &&
(!this.outputConnection || this.hasStatementInput)) {
return Math.abs(
this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS);
}
return this.constants_.NO_PADDING;
}
if (Types.isBottomRow(next)) {
const bottomRow = next as BottomRow;
if (!this.outputConnection) {
const topHeight = Math.max(
this.topRow.minHeight,
Math.max(
this.constants_.NOTCH_HEIGHT,
this.constants_.CORNER_RADIUS)) -
this.constants_.CORNER_RADIUS;
return topHeight;
} else if (!bottomRow.hasNextConnection && this.hasStatementInput) {
return Math.abs(
this.constants_.NOTCH_HEIGHT - this.constants_.CORNER_RADIUS);
}
return this.constants_.NO_PADDING;
}
return this.constants_.MEDIUM_PADDING;
}
override getSpacerRowWidth_(prev: Row, next: Row): number {
const width = this.width - this.startX;
if (Types.isInputRow(prev) && prev.hasStatement ||
Types.isInputRow(next) && next.hasStatement) {
return Math.max(width, this.constants_.STATEMENT_INPUT_SPACER_MIN_WIDTH);
}
return width;
}
override getElemCenterline_(row: Row, elem: Measurable): number {
if (row.hasStatement && !Types.isSpacer(elem) &&
!Types.isStatementInput(elem)) {
return row.yPos + this.constants_.EMPTY_STATEMENT_INPUT_HEIGHT / 2;
}
if (Types.isInlineInput(elem) && elem instanceof InputConnection) {
const connectedBlock = elem.connectedBlock;
if (connectedBlock && connectedBlock.outputConnection &&
connectedBlock.nextConnection) {
return row.yPos + connectedBlock.height / 2;
}
}
return super.getElemCenterline_(row, elem);
}
override addInput_(input: Input, activeRow: Row) {
// If we have two dummy inputs on the same row, one aligned left and the
// other right, keep track of the right aligned dummy input so we can add
// padding later.
if (input.type === inputTypes.DUMMY && activeRow.hasDummyInput &&
activeRow.align === Align.LEFT && input.align === Align.RIGHT) {
this.rightAlignedDummyInputs_.set(activeRow, input);
} else if (input.type === inputTypes.STATEMENT) {
// Handle statements without next connections correctly.
activeRow.elements.push(new StatementInput(this.constants_, input));
activeRow.hasStatement = true;
if (activeRow.align === null) {
activeRow.align = input.align;
}
return;
}
super.addInput_(input, activeRow);
}
override addAlignmentPadding_(row: Row, missingSpace: number) {
if (this.rightAlignedDummyInputs_.get(row)) {
let alignmentDivider;
for (let i = 0; i < row.elements.length; i++) {
const elem = row.elements[i];
if (Types.isSpacer(elem)) {
alignmentDivider = elem;
}
if (Types.isField(elem) && elem instanceof Field &&
elem.parentInput === this.rightAlignedDummyInputs_.get(row)) {
break;
}
}
if (alignmentDivider) {
alignmentDivider.width += missingSpace;
row.width += missingSpace;
return;
}
}
super.addAlignmentPadding_(row, missingSpace);
}
/**
* Adjust the x position of fields to bump all non-label fields in the first
* row past the notch position. This must be called before ``computeBounds``
* is called.
*/
protected adjustXPosition_() {
const notchTotalWidth =
this.constants_.NOTCH_OFFSET_LEFT + this.constants_.NOTCH_WIDTH;
let minXPos = notchTotalWidth;
// Run through every input row on the block and only apply bump logic to the
// first input row (if the block has prev connection) and every input row
// that has a prev and next notch.
for (let i = 2; i < this.rows.length - 1; i += 2) {
const prevSpacer = this.rows[i - 1] as SpacerRow;
const row = this.rows[i];
const nextSpacer = this.rows[i + 1] as SpacerRow;
const hasPrevNotch = i === 2 ? !!this.topRow.hasPreviousConnection :
!!prevSpacer.followsStatement;
const hasNextNotch = i + 2 >= this.rows.length - 1 ?
!!this.bottomRow.hasNextConnection :
!!nextSpacer.precedesStatement;
if (Types.isInputRow(row) && row.hasStatement) {
row.measure();
minXPos = row.width - row.getLastInput().width + notchTotalWidth;
} else if (
hasPrevNotch && (i === 2 || hasNextNotch) && Types.isInputRow(row) &&
!row.hasStatement) {
let xCursor = row.xPos;
let prevInRowSpacer = null;
for (let j = 0; j < row.elements.length; j++) {
const elem = row.elements[j];
if (Types.isSpacer(elem)) {
prevInRowSpacer = elem;
}
if (prevInRowSpacer && (Types.isField(elem) || Types.isInput(elem))) {
if (xCursor < minXPos &&
!(Types.isField(elem) && elem instanceof Field &&
(elem.field instanceof FieldLabel ||
elem.field instanceof FieldImage))) {
const difference = minXPos - xCursor;
prevInRowSpacer.width += difference;
}
}
xCursor += elem.width;
}
}
}
}
/**
* Finalize the output connection info. In particular, set the height of the
* output connection to match that of the block. For the right side, add a
* right connection shape element and have it match the dimensions of the
* output connection.
*/
protected finalizeOutputConnection_() {
// Dynamic output connections depend on the height of the block.
if (!this.outputConnection || !this.outputConnection.isDynamicShape) {
return;
}
const outputConnectionShape = this.outputConnection.shape;
if (!('isDynamic' in outputConnectionShape &&
outputConnectionShape.isDynamic)) {
return;
}
let yCursor = 0;
// Determine the block height.
for (let i = 0; i < this.rows.length; i++) {
const row = this.rows[i];
row.yPos = yCursor;
yCursor += row.height;
}
this.height = yCursor;
// Adjust the height of the output connection.
const blockHeight = this.bottomRow.hasNextConnection ?
this.height - this.bottomRow.descenderHeight :
this.height;
const connectionHeight = outputConnectionShape.height(blockHeight);
const connectionWidth = outputConnectionShape.width(blockHeight);
this.outputConnection.height = connectionHeight;
this.outputConnection.width = connectionWidth;
this.outputConnection.startX = connectionWidth;
this.outputConnection.connectionOffsetY =
outputConnectionShape.connectionOffsetY(connectionHeight);
this.outputConnection.connectionOffsetX =
outputConnectionShape.connectionOffsetX(connectionWidth);
// Add the right connection measurable.
// Don't add it if we have a value-to-statement or a value-to-stack block.
let rightConnectionWidth = 0;
if (!this.hasStatementInput && !this.bottomRow.hasNextConnection) {
rightConnectionWidth = connectionWidth;
this.rightSide!.height = connectionHeight;
this.rightSide!.width = rightConnectionWidth;
this.rightSide!.centerline = connectionHeight / 2;
this.rightSide!.xPos = this.width + rightConnectionWidth;
}
this.startX = connectionWidth;
this.width += connectionWidth + rightConnectionWidth;
this.widthWithChildren += connectionWidth + rightConnectionWidth;
}
/**
* Finalize horizontal alignment of elements on the block. In particular,
* reduce the implicit spacing created by the left and right output connection
* shapes by adding setting negative spacing onto the leftmost and rightmost
* spacers.
*/
protected finalizeHorizontalAlignment_() {
if (!this.outputConnection || this.hasStatementInput ||
this.bottomRow.hasNextConnection) {
return;
}
let totalNegativeSpacing = 0;
for (let i = 0; i < this.rows.length; i++) {
const row = this.rows[i];
if (!Types.isInputRow(row)) {
continue;
}
const firstElem = row.elements[1];
const lastElem = row.elements[row.elements.length - 2];
let leftNegPadding = this.getNegativeSpacing_(firstElem);
let rightNegPadding = this.getNegativeSpacing_(lastElem);
totalNegativeSpacing = leftNegPadding + rightNegPadding;
const minBlockWidth =
this.constants_.MIN_BLOCK_WIDTH + this.outputConnection.width * 2;
if (this.width - totalNegativeSpacing < minBlockWidth) {
// Maintain a minimum block width, split negative spacing between left
// and right edge.
totalNegativeSpacing = this.width - minBlockWidth;
leftNegPadding = totalNegativeSpacing / 2;
rightNegPadding = totalNegativeSpacing / 2;
}
// Add a negative spacer on the start and end of the block.
row.elements.unshift(new InRowSpacer(this.constants_, -leftNegPadding));
row.elements.push(new InRowSpacer(this.constants_, -rightNegPadding));
}
if (totalNegativeSpacing) {
this.width -= totalNegativeSpacing;
this.widthWithChildren -= totalNegativeSpacing;
this.rightSide!.xPos -= totalNegativeSpacing;
for (let i = 0; i < this.rows.length; i++) {
const row = this.rows[i];
// AnyDuringMigration because: Property 'isTopOrBottomRow' does not
// exist on type 'typeof Types'.
if ((Types as AnyDuringMigration).isTopOrBottomRow(row)) {
row.elements[1].width -= totalNegativeSpacing;
}
row.width -= totalNegativeSpacing;
row.widthWithConnectedBlocks -= totalNegativeSpacing;
}
}
}
/**
* Calculate the spacing to reduce the left and right edges by based on the
* outer and inner connection shape.
* @param elem The first or last element on a block.
* @return The amount of spacing to reduce the first or last spacer.
*/
protected getNegativeSpacing_(elem: Measurable): number {
if (!elem) {
return 0;
}
const connectionWidth = this.outputConnection.width;
const outerShape = this.outputConnection.shape.type;
const constants = (this.constants_);
if (this.isMultiRow && this.inputRows.length > 1) {
switch (outerShape) {
case constants.SHAPES.ROUND: {
// Special case for multi-row round reporter blocks.
const maxWidth = this.constants_.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;
const width = this.height / 2 > maxWidth ? maxWidth : this.height / 2;
const topPadding = this.constants_.SMALL_PADDING;
const roundPadding =
width * (1 - Math.sin(Math.acos((width - topPadding) / width)));
return connectionWidth - roundPadding;
}
default:
return 0;
}
}
if (Types.isInlineInput(elem) && elem instanceof InputConnection) {
const connectedBlock = elem.connectedBlock;
const innerShape = connectedBlock ?
(connectedBlock.pathObject as PathObject).outputShapeType :
elem.shape.type;
if (innerShape == null) {
return 0;
}
// Special case for value to stack / value to statement blocks.
if (connectedBlock && connectedBlock.outputConnection &&
(connectedBlock.statementInputCount ||
connectedBlock.nextConnection)) {
return 0;
}
// Special case for hexagonal output.
if (outerShape === constants.SHAPES.HEXAGONAL &&
outerShape !== innerShape) {
return 0;
}
return connectionWidth -
this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][innerShape];
} else if (Types.isField(elem) && elem instanceof Field) {
// Special case for text inputs.
if (outerShape === constants.SHAPES.ROUND &&
elem.field instanceof FieldTextInput) {
return connectionWidth - 2.75 * constants.GRID_UNIT;
}
return connectionWidth -
this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][0];
} else if (Types.isIcon(elem)) {
return this.constants_.SMALL_PADDING;
}
return 0;
}
/**
* Finalize vertical alignment of rows on a block. In particular, reduce the
* implicit spacing when a non-shadow block is connected to any of an input
* row's inline inputs.
*/
protected finalizeVerticalAlignment_() {
if (this.outputConnection) {
return;
}
// Run through every input row on the block and only apply tight nesting
// logic to input rows that have a prev and next notch.
for (let i = 2; i < this.rows.length - 1; i += 2) {
const prevSpacer = this.rows[i - 1] as SpacerRow;
const row = this.rows[i];
const nextSpacer = this.rows[i + 1] as SpacerRow;
const firstRow = i === 2;
const hasPrevNotch = firstRow ? !!this.topRow.hasPreviousConnection :
!!prevSpacer.followsStatement;
const hasNextNotch = i + 2 >= this.rows.length - 1 ?
!!this.bottomRow.hasNextConnection :
!!nextSpacer.precedesStatement;
if (hasPrevNotch) {
const elem = row.elements[1];
const hasSingleTextOrImageField = row.elements.length === 3 &&
elem instanceof Field &&
(elem.field instanceof FieldLabel ||
elem.field instanceof FieldImage);
if (!firstRow && hasSingleTextOrImageField) {
// Remove some padding if we have a single image or text field.
prevSpacer.height -= this.constants_.SMALL_PADDING;
nextSpacer.height -= this.constants_.SMALL_PADDING;
row.height -= this.constants_.MEDIUM_PADDING;
} else if (!firstRow && !hasNextNotch) {
// Add a small padding so the notch doesn't clash with inputs/fields.
prevSpacer.height += this.constants_.SMALL_PADDING;
} else if (hasNextNotch) {
// Determine if the input row has non-shadow connected blocks.
let hasNonShadowConnectedBlocks = false;
const minVerticalTightNestingHeight = 40;
for (let j = 0; j < row.elements.length; j++) {
const elem = row.elements[j];
if (elem instanceof InputConnection && Types.isInlineInput(elem) &&
elem.connectedBlock && !elem.connectedBlock.isShadow() &&
elem.connectedBlock.getHeightWidth().height >=
minVerticalTightNestingHeight) {
hasNonShadowConnectedBlocks = true;
break;
}
}
// Apply tight-nesting if we have both a prev and next notch and the
// block has non-shadow connected blocks.
if (hasNonShadowConnectedBlocks) {
prevSpacer.height -= this.constants_.SMALL_PADDING;
nextSpacer.height -= this.constants_.SMALL_PADDING;
}
}
}
}
}
override finalize_() {
this.finalizeOutputConnection_();
this.finalizeHorizontalAlignment_();
this.finalizeVerticalAlignment_();
super.finalize_();
if (this.rightSide) {
this.widthWithChildren += this.rightSide.width;
}
}
}