Files
blockly/core/renderers/common/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

719 lines
25 KiB
TypeScript

/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Methods for graphically rendering a block as SVG.
*/
/**
* Methods for graphically rendering a block as SVG.
* @class
*/
import * as goog from '../../../closure/goog/goog.js';
goog.declareModuleId('Blockly.blockRendering.RenderInfo');
import type {BlockSvg} from '../../block_svg.js';
import {Align, Input} from '../../input.js';
import {inputTypes} from '../../input_types.js';
import type {RenderedConnection} from '../../rendered_connection.js';
import type {Measurable} from '../measurables/base.js';
import {BottomRow} from '../measurables/bottom_row.js';
import {ExternalValueInput} from '../measurables/external_value_input.js';
import {Field} from '../measurables/field.js';
import {Hat} from '../measurables/hat.js';
import {Icon} from '../measurables/icon.js';
import {InRowSpacer} from '../measurables/in_row_spacer.js';
import {InlineInput} from '../measurables/inline_input.js';
import {InputRow} from '../measurables/input_row.js';
import {JaggedEdge} from '../measurables/jagged_edge.js';
import {NextConnection} from '../measurables/next_connection.js';
import {OutputConnection} from '../measurables/output_connection.js';
import {PreviousConnection} from '../measurables/previous_connection.js';
import {RoundCorner} from '../measurables/round_corner.js';
import type {Row} from '../measurables/row.js';
import {SpacerRow} from '../measurables/spacer_row.js';
import {SquareCorner} from '../measurables/square_corner.js';
import {StatementInput} from '../measurables/statement_input.js';
import {TopRow} from '../measurables/top_row.js';
import {Types} from '../measurables/types.js';
import type {ConstantProvider} from './constants.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.blockRendering.RenderInfo
*/
export class RenderInfo {
block_: AnyDuringMigration;
protected constants_: ConstantProvider;
outputConnection: OutputConnection;
isInline: boolean;
isCollapsed: boolean;
isInsertionMarker: boolean;
RTL: boolean;
/** The block renderer in use. */
protected readonly renderer_: Renderer;
/** The height of the rendered block, including child blocks. */
height = 0;
/** The width of the rendered block, including child blocks. */
widthWithChildren = 0;
/**
* The width of the rendered block, excluding child blocks. This is the
* right edge of the block when rendered LTR.
*/
width = 0;
statementEdge = 0;
/** An array of Row objects containing sizing information. */
rows: Row[] = [];
/** An array of input rows on the block. */
inputRows: InputRow[] = [];
/** An array of measurable objects containing hidden icons. */
hiddenIcons: Icon[] = [];
topRow: TopRow;
bottomRow: BottomRow;
// The position of the start point for drawing, relative to the block's
// location.
startX = 0;
startY = 0;
/**
* @param renderer The renderer in use.
* @param block The block to measure.
* @internal
*/
constructor(renderer: Renderer, block: BlockSvg) {
this.renderer_ = renderer;
this.block_ = block;
/** The renderer's constant provider. */
this.constants_ = this.renderer_.getConstants();
/**
* A measurable representing the output connection if the block has one.
* Otherwise null.
*/
// AnyDuringMigration because: Type 'OutputConnection | null' is not
// assignable to type 'OutputConnection'.
this.outputConnection =
(!block.outputConnection ?
null :
new OutputConnection(this.constants_, (block.outputConnection))) as
AnyDuringMigration;
/**
* Whether the block should be rendered as a single line, either because
* it's inline or because it has been collapsed.
*/
this.isInline = block.getInputsInline() && !block.isCollapsed();
/** Whether the block is collapsed. */
this.isCollapsed = block.isCollapsed();
/**
* Whether the block is an insertion marker. Insertion markers are the same
* shape as normal blocks, but don't show fields.
*/
this.isInsertionMarker = block.isInsertionMarker();
/** True if the block should be rendered right-to-left. */
this.RTL = block.RTL;
/**
* 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_);
}
/**
* Get the block renderer in use.
* @return The block renderer in use.
* @internal
*/
getRenderer(): Renderer {
return this.renderer_;
}
/**
* Populate and return 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.
* @internal
*/
measure() {
this.createRows_();
this.addElemSpacing_();
this.addRowSpacing_();
this.computeBounds_();
this.alignRowElements_();
this.finalize_();
}
/**
* Create rows of Measurable objects representing all renderable parts of the
* block.
*/
protected createRows_() {
this.populateTopRow_();
this.rows.push(this.topRow);
let activeRow = new InputRow(this.constants_);
this.inputRows.push(activeRow);
// Icons always go on the first row, before anything else.
const icons = this.block_.getIcons();
for (let i = 0, icon; icon = icons[i]; i++) {
const iconInfo = new Icon(this.constants_, icon);
if (this.isCollapsed && icon.collapseHidden) {
this.hiddenIcons.push(iconInfo);
} else {
activeRow.elements.push(iconInfo);
}
}
let lastInput = null;
// Loop across all of the inputs on the block, creating objects for anything
// that needs to be rendered and breaking the block up into visual rows.
for (let i = 0, input; input = this.block_.inputList[i]; i++) {
if (!input.isVisible()) {
continue;
}
if (this.shouldStartNewRow_(input, lastInput)) {
// Finish this row and create a new one.
this.rows.push(activeRow);
activeRow = new InputRow(this.constants_);
this.inputRows.push(activeRow);
}
// All of the fields in an input go on the same row.
for (let j = 0, field; field = input.fieldRow[j]; j++) {
activeRow.elements.push(new Field(this.constants_, field, input));
}
this.addInput_(input, activeRow);
lastInput = input;
}
if (this.isCollapsed) {
activeRow.hasJaggedEdge = true;
activeRow.elements.push(new JaggedEdge(this.constants_));
}
if (activeRow.elements.length || activeRow.hasDummyInput) {
this.rows.push(activeRow);
}
this.populateBottomRow_();
this.rows.push(this.bottomRow);
}
/**
* Create all non-spacer elements that belong on the top row.
* @internal
*/
populateTopRow_() {
const hasPrevious = !!this.block_.previousConnection;
const hasHat = (this.block_.hat ? this.block_.hat === 'cap' :
this.constants_.ADD_START_HATS) &&
!this.outputConnection && !hasPrevious;
let cornerClass = this.topRow.hasLeftSquareCorner(this.block_) ?
SquareCorner :
RoundCorner;
this.topRow.elements.push(new cornerClass(this.constants_));
if (hasHat) {
const hat = new Hat(this.constants_);
this.topRow.elements.push(hat);
this.topRow.capline = hat.ascenderHeight;
} else if (hasPrevious) {
this.topRow.hasPreviousConnection = true;
this.topRow.connection = new PreviousConnection(
this.constants_,
(this.block_.previousConnection as RenderedConnection));
this.topRow.elements.push(this.topRow.connection);
}
const precedesStatement = this.block_.inputList.length &&
this.block_.inputList[0].type === inputTypes.STATEMENT;
// This is the minimum height for the row. If one of its elements has a
// greater height it will be overwritten in the compute pass.
if (precedesStatement && !this.block_.isCollapsed()) {
this.topRow.minHeight =
this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT;
} else {
this.topRow.minHeight = this.constants_.TOP_ROW_MIN_HEIGHT;
}
cornerClass = this.topRow.hasRightSquareCorner(this.block_) ? SquareCorner :
RoundCorner;
this.topRow.elements.push(new cornerClass(this.constants_, 'right'));
}
/**
* Create all non-spacer elements that belong on the bottom row.
* @internal
*/
populateBottomRow_() {
this.bottomRow.hasNextConnection = !!this.block_.nextConnection;
const followsStatement = this.block_.inputList.length &&
this.block_.inputList[this.block_.inputList.length - 1].type ===
inputTypes.STATEMENT;
// This is the minimum height for the row. If one of its elements has a
// greater height it will be overwritten in the compute pass.
if (followsStatement) {
this.bottomRow.minHeight =
this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT;
} else {
this.bottomRow.minHeight = this.constants_.BOTTOM_ROW_MIN_HEIGHT;
}
const leftSquareCorner = this.bottomRow.hasLeftSquareCorner(this.block_);
if (leftSquareCorner) {
this.bottomRow.elements.push(new SquareCorner(this.constants_));
} else {
this.bottomRow.elements.push(new RoundCorner(this.constants_));
}
if (this.bottomRow.hasNextConnection) {
this.bottomRow.connection = new NextConnection(
this.constants_, (this.block_.nextConnection as RenderedConnection));
this.bottomRow.elements.push(this.bottomRow.connection);
}
const rightSquareCorner = this.bottomRow.hasRightSquareCorner(this.block_);
if (rightSquareCorner) {
this.bottomRow.elements.push(new SquareCorner(this.constants_, 'right'));
} else {
this.bottomRow.elements.push(new RoundCorner(this.constants_, 'right'));
}
}
/**
* Add an input element to the active row, if needed, and record the type of
* the input on the row.
* @param input The input to record information about.
* @param activeRow The row that is currently being populated.
*/
protected addInput_(input: Input, activeRow: Row) {
// Non-dummy inputs have visual representations onscreen.
if (this.isInline && input.type === inputTypes.VALUE) {
activeRow.elements.push(new InlineInput(this.constants_, input));
activeRow.hasInlineInput = true;
} else if (input.type === inputTypes.STATEMENT) {
activeRow.elements.push(new StatementInput(this.constants_, input));
activeRow.hasStatement = true;
} else if (input.type === inputTypes.VALUE) {
activeRow.elements.push(new ExternalValueInput(this.constants_, input));
activeRow.hasExternalInput = true;
} else if (input.type === inputTypes.DUMMY) {
// Dummy inputs have no visual representation, but the information is
// still important.
activeRow.minHeight = Math.max(
activeRow.minHeight,
input.getSourceBlock() && input.getSourceBlock()!.isShadow() ?
this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT :
this.constants_.DUMMY_INPUT_MIN_HEIGHT);
activeRow.hasDummyInput = true;
}
if (activeRow.align === null) {
activeRow.align = input.align;
}
}
/**
* Decide whether to start a new row between the two Blockly.Inputs.
* @param input The first input to consider
* @param lastInput The input that follows.
* @return True if the next input should be rendered on a new row.
*/
protected 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;
}
return false;
}
/** Add horizontal spacing between and around elements within each row. */
protected addElemSpacing_() {
for (let i = 0, row; row = this.rows[i]; i++) {
const oldElems = row.elements;
row.elements = [];
// No spacing needed before the corner on the top row or the bottom row.
if (row.startsWithElemSpacer()) {
// There's a spacer before the first element in the row.
row.elements.push(new InRowSpacer(
this.constants_, this.getInRowSpacing_(null, oldElems[0])));
}
if (!oldElems.length) {
continue;
}
for (let e = 0; e < oldElems.length - 1; e++) {
row.elements.push(oldElems[e]);
const spacing = this.getInRowSpacing_(oldElems[e], oldElems[e + 1]);
row.elements.push(new InRowSpacer(this.constants_, spacing));
}
row.elements.push(oldElems[oldElems.length - 1]);
if (row.endsWithElemSpacer()) {
// There's a spacer after the last element in the row.
row.elements.push(new InRowSpacer(
this.constants_,
this.getInRowSpacing_(oldElems[oldElems.length - 1], null)));
}
}
}
/**
* Calculate the width of a spacer element in a row based on the previous and
* next elements in that row. For instance, extra padding is added between
* two editable fields.
* @param prev The element before the spacer.
* @param next The element after the spacer.
* @return The size of the spacing between the two elements.
*/
protected getInRowSpacing_(prev: Measurable|null, next: Measurable|null):
number {
if (!prev) {
// Statement input padding.
if (next && Types.isStatementInput(next)) {
return this.constants_.STATEMENT_INPUT_PADDING_LEFT;
}
}
// Between inputs and the end of the row.
if (prev && Types.isInput(prev) && !next) {
// AnyDuringMigration because: Property 'isExternalInput' does not exist
// on type 'typeof Types'.
if ((Types as AnyDuringMigration).isExternalInput(prev)) {
return this.constants_.NO_PADDING;
} else if (Types.isInlineInput(prev)) {
return this.constants_.LARGE_PADDING;
} else if (Types.isStatementInput(prev)) {
return this.constants_.NO_PADDING;
}
}
// Spacing between a square corner and a previous or next connection
if (prev && Types.isLeftSquareCorner(prev) && next) {
if (Types.isPreviousConnection(next) || Types.isNextConnection(next)) {
return next.notchOffset;
}
}
// 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;
}
}
return this.constants_.MEDIUM_PADDING;
}
/**
* Figure out where the right edge of the block and right edge of statement
* inputs should be placed.
*/
protected computeBounds_() {
let widestStatementRowFields = 0;
let blockWidth = 0;
let widestRowWithConnectedBlocks = 0;
for (let i = 0, row; row = this.rows[i]; i++) {
row.measure();
blockWidth = Math.max(blockWidth, row.width);
if (row.hasStatement) {
const statementInput = row.getLastInput();
const innerWidth = row.width - statementInput.width;
widestStatementRowFields =
Math.max(widestStatementRowFields, innerWidth);
}
widestRowWithConnectedBlocks =
Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks);
}
this.statementEdge = widestStatementRowFields;
this.width = blockWidth;
for (let i = 0, row; row = this.rows[i]; i++) {
if (row.hasStatement) {
row.statementEdge = this.statementEdge;
}
}
this.widthWithChildren = Math.max(blockWidth, widestRowWithConnectedBlocks);
if (this.outputConnection) {
this.startX = this.outputConnection.width;
this.width += this.outputConnection.width;
this.widthWithChildren += this.outputConnection.width;
}
}
/**
* Extra spacing may be necessary to make sure that the right sides of all
* rows line up. This can only be calculated after a first pass to calculate
* the sizes of all rows.
*/
protected alignRowElements_() {
for (let i = 0, row; row = this.rows[i]; i++) {
if (row.hasStatement) {
this.alignStatementRow_(row as InputRow);
} else {
const currentWidth = row.width;
const desiredWidth = this.getDesiredRowWidth_(row);
const missingSpace = desiredWidth - currentWidth;
if (missingSpace > 0) {
this.addAlignmentPadding_(row, missingSpace);
}
// AnyDuringMigration because: Property 'isTopOrBottomRow' does not
// exist on type 'typeof Types'.
if ((Types as AnyDuringMigration).isTopOrBottomRow(row)) {
row.widthWithConnectedBlocks = row.width;
}
}
}
}
/**
* Calculate the desired width of an input row.
* @param _row The input row.
* @return The desired width of the input row.
*/
protected getDesiredRowWidth_(_row: Row): number {
return this.width - this.startX;
}
/**
* Modify the given row to add the given amount of padding around its fields.
* The exact location of the padding is based on the alignment property of the
* last input in the field.
* @param row The row to add padding to.
* @param missingSpace How much padding to add.
*/
protected addAlignmentPadding_(row: Row, missingSpace: number) {
const firstSpacer = row.getFirstSpacer();
const lastSpacer = row.getLastSpacer();
if (row.hasExternalInput || row.hasStatement) {
row.widthWithConnectedBlocks += missingSpace;
}
// Decide where the extra padding goes.
if (row.align === Align.LEFT) {
// Add padding to the end of the row.
lastSpacer.width += missingSpace;
} else if (row.align === Align.CENTRE) {
// Split the padding between the beginning and end of the row.
firstSpacer.width += missingSpace / 2;
lastSpacer.width += missingSpace / 2;
} else if (row.align === Align.RIGHT) {
// Add padding at the beginning of the row.
firstSpacer.width += missingSpace;
} else {
// Default to left-aligning.
lastSpacer.width += missingSpace;
}
row.width += missingSpace;
}
/**
* Align the elements of a statement row based on computed bounds.
* Unlike other types of rows, statement rows add space in multiple places.
* @param row The statement row to resize.
*/
protected alignStatementRow_(row: InputRow) {
const statementInput = row.getLastInput();
let currentWidth = row.width - statementInput.width;
let desiredWidth = this.statementEdge;
// Add padding before the statement input.
const missingSpace = desiredWidth - currentWidth;
if (missingSpace > 0) {
this.addAlignmentPadding_(row, missingSpace);
}
// Also widen the statement input to reach to the right side of the
// block. Note that this does not add padding.
currentWidth = row.width;
desiredWidth = this.getDesiredRowWidth_(row);
statementInput.width += desiredWidth - currentWidth;
statementInput.height = Math.max(statementInput.height, row.height);
row.width += desiredWidth - currentWidth;
row.widthWithConnectedBlocks =
Math.max(row.width, this.statementEdge + row.connectedBlockWidths);
}
/** Add spacers between rows and set their sizes. */
protected addRowSpacing_() {
const oldRows = this.rows;
this.rows = [];
for (let r = 0; r < oldRows.length; r++) {
this.rows.push(oldRows[r]);
if (r !== oldRows.length - 1) {
this.rows.push(this.makeSpacerRow_(oldRows[r], oldRows[r + 1]));
}
}
}
/**
* Create a spacer row to go between prev and next, and set its size.
* @param prev The previous row.
* @param next The next row.
* @return The newly created spacer row.
*/
protected makeSpacerRow_(prev: Row, next: Row): SpacerRow {
const height = this.getSpacerRowHeight_(prev, next);
const width = this.getSpacerRowWidth_(prev, next);
const spacer = new SpacerRow(this.constants_, height, width);
if (prev.hasStatement) {
spacer.followsStatement = true;
}
if (next.hasStatement) {
spacer.precedesStatement = true;
}
return spacer;
}
/**
* Calculate the width of a spacer row.
* @param _prev The row before the spacer.
* @param _next The row after the spacer.
* @return The desired width of the spacer row between these two rows.
*/
protected getSpacerRowWidth_(_prev: Row, _next: Row): number {
return this.width - this.startX;
}
/**
* Calculate the height of a spacer row.
* @param _prev The row before the spacer.
* @param _next The row after the spacer.
* @return The desired height of the spacer row between these two rows.
*/
protected getSpacerRowHeight_(_prev: Row, _next: Row): number {
return this.constants_.MEDIUM_PADDING;
}
/**
* Calculate the centerline of an element in a rendered row.
* This base implementation puts the centerline at the middle of the row
* vertically, with no special cases. You will likely need extra logic to
* handle (at minimum) top and bottom rows.
* @param row The row containing the element.
* @param elem The element to place.
* @return The desired centerline of the given element, as an offset from the
* top left of the block.
*/
protected getElemCenterline_(row: Row, elem: Measurable): number {
if (Types.isSpacer(elem)) {
return row.yPos + elem.height / 2;
}
if (Types.isBottomRow(row)) {
const bottomRow = row as BottomRow;
const baseline =
bottomRow.yPos + bottomRow.height - bottomRow.descenderHeight;
if (Types.isNextConnection(elem)) {
return baseline + elem.height / 2;
}
return baseline - elem.height / 2;
}
if (Types.isTopRow(row)) {
const topRow = row as TopRow;
// AnyDuringMigration because: Property 'isHat' does not exist on type
// 'typeof Types'.
if ((Types as AnyDuringMigration).isHat(elem)) {
return topRow.capline - elem.height / 2;
}
return topRow.capline + elem.height / 2;
}
return row.yPos + row.height / 2;
}
/**
* Record final position information on elements on the given row, for use in
* drawing. At minimum this records xPos and centerline on each element.
* @param row The row containing the elements.
*/
protected recordElemPositions_(row: Row) {
let xCursor = row.xPos;
for (let j = 0, elem; elem = row.elements[j]; j++) {
// Now that row heights are finalized, make spacers use the row height.
if (Types.isSpacer(elem)) {
elem.height = row.height;
}
elem.xPos = xCursor;
elem.centerline = this.getElemCenterline_(row, elem);
xCursor += elem.width;
}
}
/**
* Make any final changes to the rendering information object. In particular,
* store the y position of each row, and record the height of the full block.
*/
protected finalize_() {
// Performance note: this could be combined with the draw pass, if the time
// that this takes is excessive. But it shouldn't be, because it only
// accesses and sets properties that already exist on the objects.
let widestRowWithConnectedBlocks = 0;
let yCursor = 0;
for (let i = 0, row; row = this.rows[i]; i++) {
row.yPos = yCursor;
row.xPos = this.startX;
yCursor += row.height;
widestRowWithConnectedBlocks =
Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks);
this.recordElemPositions_(row);
}
if (this.outputConnection && this.block_.nextConnection &&
this.block_.nextConnection.isConnected()) {
// Include width of connected block in value to stack width measurement.
widestRowWithConnectedBlocks = Math.max(
widestRowWithConnectedBlocks,
this.block_.nextConnection.targetBlock().getHeightWidth().width);
}
this.widthWithChildren = widestRowWithConnectedBlocks + this.startX;
this.height = yCursor;
this.startY = this.topRow.capline;
this.bottomRow.baseline = yCursor - this.bottomRow.descenderHeight;
}
}