Files
blockly/core/renderers/zelos/constants.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

859 lines
28 KiB
TypeScript

/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview An object that provides constants for rendering blocks in Zelos
* mode.
*/
/**
* An object that provides constants for rendering blocks in Zelos
* mode.
* @class
*/
import * as goog from '../../../closure/goog/goog.js';
goog.declareModuleId('Blockly.zelos.ConstantProvider');
import {ConnectionType} from '../../connection_type.js';
import type {RenderedConnection} from '../../rendered_connection.js';
import type {Theme} from '../../theme.js';
import * as utilsColour from '../../utils/colour.js';
import * as dom from '../../utils/dom.js';
import {Svg} from '../../utils/svg.js';
import * as svgPaths from '../../utils/svg_paths.js';
import {ConstantProvider as BaseConstantProvider} from '../common/constants.js';
import type {Shape} from '../common/constants.js';
/** An object containing sizing and path information about inside corners. */
export interface InsideCorners {
width: number;
height: number;
pathTop: string;
pathBottom: string;
rightWidth: number;
rightHeight: number;
pathTopRight: string;
pathBottomRight: string;
}
/**
* An object that provides constants for rendering blocks in Zelos mode.
* @alias Blockly.zelos.ConstantProvider
*/
export class ConstantProvider extends BaseConstantProvider {
GRID_UNIT = 4;
override SMALL_PADDING: AnyDuringMigration;
override MEDIUM_PADDING: AnyDuringMigration;
override MEDIUM_LARGE_PADDING: AnyDuringMigration;
override LARGE_PADDING: AnyDuringMigration;
override CORNER_RADIUS: AnyDuringMigration;
override NOTCH_WIDTH: AnyDuringMigration;
override NOTCH_HEIGHT: AnyDuringMigration;
override NOTCH_OFFSET_LEFT: AnyDuringMigration;
override STATEMENT_INPUT_NOTCH_OFFSET: AnyDuringMigration;
override MIN_BLOCK_WIDTH: AnyDuringMigration;
override MIN_BLOCK_HEIGHT: AnyDuringMigration;
override EMPTY_STATEMENT_INPUT_HEIGHT: AnyDuringMigration;
override TAB_OFFSET_FROM_TOP = 0;
override TOP_ROW_MIN_HEIGHT: AnyDuringMigration;
override TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT: AnyDuringMigration;
override BOTTOM_ROW_MIN_HEIGHT: AnyDuringMigration;
override BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT: AnyDuringMigration;
override STATEMENT_BOTTOM_SPACER: AnyDuringMigration;
STATEMENT_INPUT_SPACER_MIN_WIDTH: number;
override STATEMENT_INPUT_PADDING_LEFT: AnyDuringMigration;
override EMPTY_INLINE_INPUT_PADDING: AnyDuringMigration;
override EMPTY_INLINE_INPUT_HEIGHT: AnyDuringMigration;
override DUMMY_INPUT_MIN_HEIGHT: AnyDuringMigration;
override DUMMY_INPUT_SHADOW_MIN_HEIGHT: AnyDuringMigration;
override CURSOR_WS_WIDTH: AnyDuringMigration;
override CURSOR_COLOUR = '#ffa200';
/**
* Radius of the cursor for input and output connections.
* @internal
*/
CURSOR_RADIUS = 5;
override JAGGED_TEETH_HEIGHT = 0;
override JAGGED_TEETH_WIDTH = 0;
override START_HAT_HEIGHT = 22;
override START_HAT_WIDTH = 96;
override SHAPES = {HEXAGONAL: 1, ROUND: 2, SQUARE: 3, PUZZLE: 4, NOTCH: 5};
SHAPE_IN_SHAPE_PADDING: AnyDuringMigration;
override FULL_BLOCK_FIELDS = true;
override FIELD_TEXT_FONTSIZE: AnyDuringMigration;
override FIELD_TEXT_FONTWEIGHT = 'bold';
override FIELD_TEXT_FONTFAMILY =
'"Helvetica Neue", "Segoe UI", Helvetica, sans-serif';
override FIELD_BORDER_RECT_RADIUS: AnyDuringMigration;
override FIELD_BORDER_RECT_X_PADDING: AnyDuringMigration;
override FIELD_BORDER_RECT_Y_PADDING: AnyDuringMigration;
override FIELD_BORDER_RECT_HEIGHT: AnyDuringMigration;
override FIELD_DROPDOWN_BORDER_RECT_HEIGHT: AnyDuringMigration;
override FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW = true;
override FIELD_DROPDOWN_COLOURED_DIV = true;
override FIELD_DROPDOWN_SVG_ARROW = true;
override FIELD_DROPDOWN_SVG_ARROW_PADDING: AnyDuringMigration;
override FIELD_TEXTINPUT_BOX_SHADOW = true;
override FIELD_COLOUR_FULL_BLOCK = true;
override FIELD_COLOUR_DEFAULT_WIDTH: AnyDuringMigration;
override FIELD_COLOUR_DEFAULT_HEIGHT: AnyDuringMigration;
override FIELD_CHECKBOX_X_OFFSET: AnyDuringMigration;
MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH: number;
/** The selected glow colour. */
SELECTED_GLOW_COLOUR = '#fff200';
/** The size of the selected glow. */
SELECTED_GLOW_SIZE = 0.5;
/** The replacement glow colour. */
REPLACEMENT_GLOW_COLOUR = '#fff200';
/** The size of the selected glow. */
REPLACEMENT_GLOW_SIZE = 2;
/**
* The ID of the selected glow filter, or the empty string if no filter is
* set.
* @internal
*/
selectedGlowFilterId = '';
/**
* The <filter> element to use for a selected glow, or null if not set.
*/
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'SVGElement'.
private selectedGlowFilter_: SVGElement = null as AnyDuringMigration;
/**
* The ID of the replacement glow filter, or the empty string if no filter
* is set.
* @internal
*/
replacementGlowFilterId = '';
/**
* The <filter> element to use for a replacement glow, or null if not set.
*/
// AnyDuringMigration because: Type 'null' is not assignable to type
// 'SVGElement'.
private replacementGlowFilter_: SVGElement = null as AnyDuringMigration;
/**
* The object containing information about the hexagon used for a boolean
* reporter block. Null before init is called.
*/
HEXAGONAL: Shape|null = null;
/**
* The object containing information about the hexagon used for a number or
* string reporter block. Null before init is called.
*/
ROUNDED: Shape|null = null;
/**
* The object containing information about the hexagon used for a
* rectangular reporter block. Null before init is called.
*/
SQUARED: Shape|null = null;
/** @internal */
constructor() {
super();
this.SMALL_PADDING = this.GRID_UNIT;
this.MEDIUM_PADDING = 2 * this.GRID_UNIT;
this.MEDIUM_LARGE_PADDING = 3 * this.GRID_UNIT;
this.LARGE_PADDING = 4 * this.GRID_UNIT;
this.CORNER_RADIUS = 1 * this.GRID_UNIT;
this.NOTCH_WIDTH = 9 * this.GRID_UNIT;
this.NOTCH_HEIGHT = 2 * this.GRID_UNIT;
this.NOTCH_OFFSET_LEFT = 3 * this.GRID_UNIT;
this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT;
this.MIN_BLOCK_WIDTH = 2 * this.GRID_UNIT;
this.MIN_BLOCK_HEIGHT = 12 * this.GRID_UNIT;
this.EMPTY_STATEMENT_INPUT_HEIGHT = 6 * this.GRID_UNIT;
this.TOP_ROW_MIN_HEIGHT = this.CORNER_RADIUS;
this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT = this.LARGE_PADDING;
this.BOTTOM_ROW_MIN_HEIGHT = this.CORNER_RADIUS;
this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT = 6 * this.GRID_UNIT;
this.STATEMENT_BOTTOM_SPACER = -this.NOTCH_HEIGHT;
/** Minimum statement input spacer width. */
this.STATEMENT_INPUT_SPACER_MIN_WIDTH = 40 * this.GRID_UNIT;
this.STATEMENT_INPUT_PADDING_LEFT = 4 * this.GRID_UNIT;
this.EMPTY_INLINE_INPUT_PADDING = 4 * this.GRID_UNIT;
this.EMPTY_INLINE_INPUT_HEIGHT = 8 * this.GRID_UNIT;
this.DUMMY_INPUT_MIN_HEIGHT = 8 * this.GRID_UNIT;
this.DUMMY_INPUT_SHADOW_MIN_HEIGHT = 6 * this.GRID_UNIT;
this.CURSOR_WS_WIDTH = 20 * this.GRID_UNIT;
/**
* Map of output/input shapes and the amount they should cause a block to be
* padded. Outer key is the outer shape, inner key is the inner shape.
* When a block with the outer shape contains an input block with the inner
* shape on its left or right edge, the block elements are aligned such that
* the padding specified is reached.
* @internal
*/
this.SHAPE_IN_SHAPE_PADDING = {
1: {
// Outer shape: hexagon.
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.
},
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: {
// 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, // Square in square.
},
};
this.FIELD_TEXT_FONTSIZE = 3 * this.GRID_UNIT;
this.FIELD_BORDER_RECT_RADIUS = this.CORNER_RADIUS;
this.FIELD_BORDER_RECT_X_PADDING = 2 * this.GRID_UNIT;
this.FIELD_BORDER_RECT_Y_PADDING = 1.625 * this.GRID_UNIT;
this.FIELD_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT;
this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = 8 * this.GRID_UNIT;
this.FIELD_DROPDOWN_SVG_ARROW_PADDING = this.FIELD_BORDER_RECT_X_PADDING;
this.FIELD_COLOUR_DEFAULT_WIDTH = 2 * this.GRID_UNIT;
this.FIELD_COLOUR_DEFAULT_HEIGHT = 4 * this.GRID_UNIT;
this.FIELD_CHECKBOX_X_OFFSET = 1 * this.GRID_UNIT;
/** The maximum width of a dynamic connection shape. */
this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH = 12 * this.GRID_UNIT;
}
override setFontConstants_(theme: Theme) {
super.setFontConstants_(theme);
this.FIELD_BORDER_RECT_HEIGHT =
this.FIELD_TEXT_HEIGHT + this.FIELD_BORDER_RECT_Y_PADDING * 2;
this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT = this.FIELD_BORDER_RECT_HEIGHT;
}
override init() {
super.init();
this.HEXAGONAL = this.makeHexagonal();
this.ROUNDED = this.makeRounded();
this.SQUARED = this.makeSquared();
this.STATEMENT_INPUT_NOTCH_OFFSET = this.NOTCH_OFFSET_LEFT +
(this.INSIDE_CORNERS as InsideCorners).rightWidth;
}
override setDynamicProperties_(theme: Theme) {
super.setDynamicProperties_(theme);
this.SELECTED_GLOW_COLOUR = theme.getComponentStyle('selectedGlowColour') ||
this.SELECTED_GLOW_COLOUR;
const selectedGlowSize =
Number(theme.getComponentStyle('selectedGlowSize'));
this.SELECTED_GLOW_SIZE = selectedGlowSize && !isNaN(selectedGlowSize) ?
selectedGlowSize :
this.SELECTED_GLOW_SIZE;
this.REPLACEMENT_GLOW_COLOUR =
theme.getComponentStyle('replacementGlowColour') ||
this.REPLACEMENT_GLOW_COLOUR;
const replacementGlowSize =
Number(theme.getComponentStyle('replacementGlowSize'));
this.REPLACEMENT_GLOW_SIZE =
replacementGlowSize && !isNaN(replacementGlowSize) ?
replacementGlowSize :
this.REPLACEMENT_GLOW_SIZE;
}
override dispose() {
super.dispose();
if (this.selectedGlowFilter_) {
dom.removeNode(this.selectedGlowFilter_);
}
if (this.replacementGlowFilter_) {
dom.removeNode(this.replacementGlowFilter_);
}
}
override makeStartHat() {
const height = this.START_HAT_HEIGHT;
const width = this.START_HAT_WIDTH;
const mainPath = svgPaths.curve('c', [
svgPaths.point(25, -height),
svgPaths.point(71, -height),
svgPaths.point(width, 0),
]);
return {height, width, path: mainPath};
}
/**
* Create sizing and path information about a hexagonal shape.
* @return An object containing sizing and path information about a hexagonal
* shape for connections.
* @internal
*/
makeHexagonal(): Shape {
const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;
/**
* Make the main path for the hexagonal connection shape out of two lines.
* The lines are defined with relative positions and require the block
* height. The 'up' and 'down' versions of the paths are the same, but the Y
* sign flips. The 'left' and 'right' versions of the path are also the
* same, but the X sign flips.
* @param height The height of the block the connection is on.
* @param up True if the path should be drawn from bottom to top, false
* otherwise.
* @param right True if the path is for the right side of the block.
* @return A path fragment describing a rounded connection.
*/
function makeMainPath(height: number, up: boolean, right: boolean): string {
const halfHeight = height / 2;
const width = halfHeight > maxWidth ? maxWidth : halfHeight;
const forward = up ? -1 : 1;
const direction = right ? -1 : 1;
const dy = forward * height / 2;
return svgPaths.lineTo(-direction * width, dy) +
svgPaths.lineTo(direction * width, dy);
}
return {
type: this.SHAPES.HEXAGONAL,
isDynamic: true,
width(height: number): number {
const halfHeight = height / 2;
return halfHeight > maxWidth ? maxWidth : halfHeight;
},
height(height: number): number {
return height;
},
connectionOffsetY(connectionHeight: number): number {
return connectionHeight / 2;
},
connectionOffsetX(connectionWidth: number): number {
return -connectionWidth;
},
pathDown(height: number): string {
return makeMainPath(height, false, false);
},
pathUp(height: number): string {
return makeMainPath(height, true, false);
},
pathRightDown(height: number): string {
return makeMainPath(height, false, true);
},
pathRightUp(height: number): string {
return makeMainPath(height, false, true);
},
};
}
/**
* Create sizing and path information about a rounded shape.
* @return An object containing sizing and path information about a rounded
* shape for connections.
* @internal
*/
makeRounded(): Shape {
const maxWidth = this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;
const maxHeight = maxWidth * 2;
/**
* Make the main path for the rounded connection shape out of two arcs and
* a line that joins them. The arcs are defined with relative positions.
* Usually, the height of the block is split between the two arcs. In the
* case where the height of the block exceeds the maximum height, a line is
* drawn in between the two arcs. The 'up' and 'down' versions of the paths
* are the same, but the Y sign flips. The 'up' and 'right' versions of the
* path flip the sweep-flag which moves the arc at negative angles.
* @param blockHeight The height of the block the connection is on.
* @param up True if the path should be drawn from bottom to top, false
* otherwise.
* @param right True if the path is for the right side of the block.
* @return A path fragment describing a rounded connection.
*/
function makeMainPath(
blockHeight: number, up: boolean, right: boolean): string {
const remainingHeight =
blockHeight > maxHeight ? blockHeight - maxHeight : 0;
const height = blockHeight > maxHeight ? maxHeight : blockHeight;
const radius = height / 2;
return svgPaths.arc(
'a', '0 0,1', radius,
svgPaths.point(
(up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) +
svgPaths.lineOnAxis('v', (right ? 1 : -1) * remainingHeight) +
svgPaths.arc(
'a', '0 0,1', radius,
svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius));
}
return {
type: this.SHAPES.ROUND,
isDynamic: true,
width(height: number): number {
const halfHeight = height / 2;
return halfHeight > maxWidth ? maxWidth : halfHeight;
},
height(height: number): number {
return height;
},
connectionOffsetY(connectionHeight: number): number {
return connectionHeight / 2;
},
connectionOffsetX(connectionWidth: number): number {
return -connectionWidth;
},
pathDown(height: number): string {
return makeMainPath(height, false, false);
},
pathUp(height: number): string {
return makeMainPath(height, true, false);
},
pathRightDown(height: number): string {
return makeMainPath(height, false, true);
},
pathRightUp(height: number): string {
return makeMainPath(height, false, true);
},
};
}
/**
* Create sizing and path information about a squared shape.
* @return An object containing sizing and path information about a squared
* shape for connections.
* @internal
*/
makeSquared(): Shape {
const radius = this.CORNER_RADIUS;
/**
* Make the main path for the squared connection shape out of two corners
* and a single line in-between (a and v). These are defined in relative
* positions and require the height of the block.
* The 'left' and 'right' versions of the paths are the same, but the Y sign
* flips. The 'up' and 'down' versions of the path determine where the
* corner point is placed and in turn the direction of the corners.
* @param height The height of the block the connection is on.
* @param up True if the path should be drawn from bottom to top, false
* otherwise.
* @param right True if the path is for the right side of the block.
* @return A path fragment describing a squared connection.
*/
function makeMainPath(height: number, up: boolean, right: boolean): string {
const innerHeight = height - radius * 2;
return svgPaths.arc(
'a', '0 0,1', radius,
svgPaths.point(
(up ? -1 : 1) * radius, (up ? -1 : 1) * radius)) +
svgPaths.lineOnAxis('v', (right ? 1 : -1) * innerHeight) +
svgPaths.arc(
'a', '0 0,1', radius,
svgPaths.point((up ? 1 : -1) * radius, (up ? -1 : 1) * radius));
}
return {
type: this.SHAPES.SQUARE,
isDynamic: true,
width(_height: number): number {
return radius;
},
height(height: number): number {
return height;
},
connectionOffsetY(connectionHeight: number): number {
return connectionHeight / 2;
},
connectionOffsetX(connectionWidth: number): number {
return -connectionWidth;
},
pathDown(height: number): string {
return makeMainPath(height, false, false);
},
pathUp(height: number): string {
return makeMainPath(height, true, false);
},
pathRightDown(height: number): string {
return makeMainPath(height, false, true);
},
pathRightUp(height: number): string {
return makeMainPath(height, false, true);
},
};
}
override shapeFor(connection: RenderedConnection): Shape {
let checks = connection.getCheck();
if (!checks && connection.targetConnection) {
checks = connection.targetConnection.getCheck();
}
let outputShape;
switch (connection.type) {
case ConnectionType.INPUT_VALUE:
case ConnectionType.OUTPUT_VALUE:
outputShape = connection.getSourceBlock().getOutputShape();
// If the block has an output shape set, use that instead.
if (outputShape !== null) {
switch (outputShape) {
case this.SHAPES.HEXAGONAL:
return this.HEXAGONAL!;
case this.SHAPES.ROUND:
return this.ROUNDED!;
case this.SHAPES.SQUARE:
return this.SQUARED!;
}
}
// Includes doesn't work in IE.
if (checks && checks.indexOf('Boolean') !== -1) {
return this.HEXAGONAL!;
}
if (checks && checks.indexOf('Number') !== -1) {
return this.ROUNDED!;
}
if (checks && checks.indexOf('String') !== -1) {
return this.ROUNDED!;
}
return this.ROUNDED!;
case ConnectionType.PREVIOUS_STATEMENT:
case ConnectionType.NEXT_STATEMENT:
return this.NOTCH!;
default:
throw Error('Unknown type');
}
}
override makeNotch() {
const width = this.NOTCH_WIDTH;
const height = this.NOTCH_HEIGHT;
const innerWidth = width / 3;
const curveWidth = innerWidth / 3;
const halfHeight = height / 2;
const quarterHeight = halfHeight / 2;
/**
* Make the main path for the notch.
* @param dir Direction multiplier to apply to horizontal offsets along the
* path. Either 1 or -1.
* @return A path fragment describing a notch.
*/
function makeMainPath(dir: number): string {
return svgPaths.curve(
'c',
[
svgPaths.point(dir * curveWidth / 2, 0),
svgPaths.point(dir * curveWidth * 3 / 4, quarterHeight / 2),
svgPaths.point(dir * curveWidth, quarterHeight),
]) +
svgPaths.line([svgPaths.point(dir * curveWidth, halfHeight)]) +
svgPaths.curve(
'c',
[
svgPaths.point(dir * curveWidth / 4, quarterHeight / 2),
svgPaths.point(dir * curveWidth / 2, quarterHeight),
svgPaths.point(dir * curveWidth, quarterHeight),
]) +
svgPaths.lineOnAxis('h', dir * innerWidth) +
svgPaths.curve(
'c',
[
svgPaths.point(dir * curveWidth / 2, 0),
svgPaths.point(dir * curveWidth * 3 / 4, -(quarterHeight / 2)),
svgPaths.point(dir * curveWidth, -quarterHeight),
]) +
svgPaths.line([svgPaths.point(dir * curveWidth, -halfHeight)]) +
svgPaths.curve('c', [
svgPaths.point(dir * curveWidth / 4, -(quarterHeight / 2)),
svgPaths.point(dir * curveWidth / 2, -quarterHeight),
svgPaths.point(dir * curveWidth, -quarterHeight),
]);
}
const pathLeft = makeMainPath(1);
const pathRight = makeMainPath(-1);
return {
type: this.SHAPES.NOTCH,
width,
height,
pathLeft,
pathRight,
};
}
override makeInsideCorners() {
const radius = this.CORNER_RADIUS;
const innerTopLeftCorner =
svgPaths.arc('a', '0 0,0', radius, svgPaths.point(-radius, radius));
const innerTopRightCorner =
svgPaths.arc('a', '0 0,1', radius, svgPaths.point(-radius, radius));
const innerBottomLeftCorner =
svgPaths.arc('a', '0 0,0', radius, svgPaths.point(radius, radius));
const innerBottomRightCorner =
svgPaths.arc('a', '0 0,1', radius, svgPaths.point(radius, radius));
return {
width: radius,
height: radius,
pathTop: innerTopLeftCorner,
pathBottom: innerBottomLeftCorner,
rightWidth: radius,
rightHeight: radius,
pathTopRight: innerTopRightCorner,
pathBottomRight: innerBottomRightCorner,
};
}
override generateSecondaryColour_(colour: string) {
return utilsColour.blend('#000', colour, 0.15) || colour;
}
override generateTertiaryColour_(colour: string) {
return utilsColour.blend('#000', colour, 0.25) || colour;
}
override createDom(svg: SVGElement, tagName: string, selector: string) {
super.createDom(svg, tagName, selector);
/*
<defs>
... filters go here ...
</defs>
*/
const defs = dom.createSvgElement(Svg.DEFS, {}, svg);
// Using a dilate distorts the block shape.
// Instead use a gaussian blur, and then set all alpha to 1 with a transfer.
const selectedGlowFilter = dom.createSvgElement(
Svg.FILTER, {
'id': 'blocklySelectedGlowFilter' + this.randomIdentifier,
'height': '160%',
'width': '180%',
'y': '-30%',
'x': '-40%',
},
defs);
dom.createSvgElement(
Svg.FEGAUSSIANBLUR,
{'in': 'SourceGraphic', 'stdDeviation': this.SELECTED_GLOW_SIZE},
selectedGlowFilter);
// Set all gaussian blur pixels to 1 opacity before applying flood
const selectedComponentTransfer = dom.createSvgElement(
Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, selectedGlowFilter);
dom.createSvgElement(
Svg.FEFUNCA,
{'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'},
selectedComponentTransfer);
// Color the highlight
dom.createSvgElement(
Svg.FEFLOOD, {
'flood-color': this.SELECTED_GLOW_COLOUR,
'flood-opacity': 1,
'result': 'outColor',
},
selectedGlowFilter);
dom.createSvgElement(
Svg.FECOMPOSITE, {
'in': 'outColor',
'in2': 'outBlur',
'operator': 'in',
'result': 'outGlow',
},
selectedGlowFilter);
this.selectedGlowFilterId = selectedGlowFilter.id;
this.selectedGlowFilter_ = selectedGlowFilter;
// Using a dilate distorts the block shape.
// Instead use a gaussian blur, and then set all alpha to 1 with a transfer.
const replacementGlowFilter = dom.createSvgElement(
Svg.FILTER, {
'id': 'blocklyReplacementGlowFilter' + this.randomIdentifier,
'height': '160%',
'width': '180%',
'y': '-30%',
'x': '-40%',
},
defs);
dom.createSvgElement(
Svg.FEGAUSSIANBLUR,
{'in': 'SourceGraphic', 'stdDeviation': this.REPLACEMENT_GLOW_SIZE},
replacementGlowFilter);
// Set all gaussian blur pixels to 1 opacity before applying flood
const replacementComponentTransfer = dom.createSvgElement(
Svg.FECOMPONENTTRANSFER, {'result': 'outBlur'}, replacementGlowFilter);
dom.createSvgElement(
Svg.FEFUNCA,
{'type': 'table', 'tableValues': '0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1'},
replacementComponentTransfer);
// Color the highlight
dom.createSvgElement(
Svg.FEFLOOD, {
'flood-color': this.REPLACEMENT_GLOW_COLOUR,
'flood-opacity': 1,
'result': 'outColor',
},
replacementGlowFilter);
dom.createSvgElement(
Svg.FECOMPOSITE, {
'in': 'outColor',
'in2': 'outBlur',
'operator': 'in',
'result': 'outGlow',
},
replacementGlowFilter);
dom.createSvgElement(
Svg.FECOMPOSITE, {
'in': 'SourceGraphic',
'in2': 'outGlow',
'operator': 'over',
},
replacementGlowFilter);
this.replacementGlowFilterId = replacementGlowFilter.id;
this.replacementGlowFilter_ = replacementGlowFilter;
}
override getCSS_(selector: string) {
return [
/* eslint-disable indent */
// Text.
selector + ' .blocklyText,',
selector + ' .blocklyFlyoutLabelText {',
'font: ' + this.FIELD_TEXT_FONTWEIGHT + ' ' + this.FIELD_TEXT_FONTSIZE +
'pt ' + this.FIELD_TEXT_FONTFAMILY + ';',
'}',
// Fields.
selector + ' .blocklyText {',
'fill: #fff;',
'}',
selector + ' .blocklyNonEditableText>rect:not(.blocklyDropdownRect),',
selector + ' .blocklyEditableText>rect:not(.blocklyDropdownRect) {',
'fill: ' + this.FIELD_BORDER_RECT_COLOUR + ';',
'}',
selector + ' .blocklyNonEditableText>text,',
selector + ' .blocklyEditableText>text,',
selector + ' .blocklyNonEditableText>g>text,',
selector + ' .blocklyEditableText>g>text {',
'fill: #575E75;',
'}', // Flyout labels.
selector + ' .blocklyFlyoutLabelText {',
'fill: #575E75;',
'}',
// Bubbles.
selector + ' .blocklyText.blocklyBubbleText {',
'fill: #575E75;',
'}',
// Editable field hover.
selector + ' .blocklyDraggable:not(.blocklyDisabled)',
' .blocklyEditableText:not(.editing):hover>rect,',
selector + ' .blocklyDraggable:not(.blocklyDisabled)',
' .blocklyEditableText:not(.editing):hover>.blocklyPath {',
'stroke: #fff;',
'stroke-width: 2;',
'}',
// Text field input.
selector + ' .blocklyHtmlInput {',
'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';',
'font-weight: ' + this.FIELD_TEXT_FONTWEIGHT + ';',
'color: #575E75;',
'}',
// Dropdown field.
selector + ' .blocklyDropdownText {',
'fill: #fff !important;',
'}', // Widget and Dropdown Div
selector + '.blocklyWidgetDiv .goog-menuitem,',
selector + '.blocklyDropDownDiv .goog-menuitem {',
'font-family: ' + this.FIELD_TEXT_FONTFAMILY + ';',
'}',
selector + '.blocklyDropDownDiv .goog-menuitem-content {',
'color: #fff;',
'}',
// Connection highlight.
selector + ' .blocklyHighlightedConnectionPath {',
'stroke: ' + this.SELECTED_GLOW_COLOUR + ';',
'}',
// Disabled outline paths.
selector + ' .blocklyDisabled > .blocklyOutlinePath {',
'fill: url(#blocklyDisabledPattern' + this.randomIdentifier + ')',
'}',
// Insertion marker.
selector + ' .blocklyInsertionMarker>.blocklyPath {',
'fill-opacity: ' + this.INSERTION_MARKER_OPACITY + ';',
'stroke: none;',
'}',
];
}
}
/* eslint-enable indent */