mirror of
https://github.com/google/blockly.git
synced 2026-01-08 17:40:09 +01:00
* 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>
549 lines
17 KiB
TypeScript
549 lines
17 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2013 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Angle input field.
|
|
*/
|
|
|
|
/**
|
|
* Angle input field.
|
|
* @class
|
|
*/
|
|
import * as goog from '../closure/goog/goog.js';
|
|
goog.declareModuleId('Blockly.FieldAngle');
|
|
|
|
import {BlockSvg} from './block_svg.js';
|
|
import * as browserEvents from './browser_events.js';
|
|
import * as Css from './css.js';
|
|
import * as dropDownDiv from './dropdowndiv.js';
|
|
import {Field} from './field.js';
|
|
import * as fieldRegistry from './field_registry.js';
|
|
import {FieldTextInput} from './field_textinput.js';
|
|
import * as dom from './utils/dom.js';
|
|
import {KeyCodes} from './utils/keycodes.js';
|
|
import * as math from './utils/math.js';
|
|
import type {Sentinel} from './utils/sentinel.js';
|
|
import {Svg} from './utils/svg.js';
|
|
import * as userAgent from './utils/useragent.js';
|
|
import * as WidgetDiv from './widgetdiv.js';
|
|
|
|
|
|
/**
|
|
* Class for an editable angle field.
|
|
* @alias Blockly.FieldAngle
|
|
*/
|
|
export class FieldAngle extends FieldTextInput {
|
|
/** The default value for this field. */
|
|
// protected override DEFAULT_VALUE = 0;
|
|
|
|
/**
|
|
* The default amount to round angles to when using a mouse or keyboard nav
|
|
* input. Must be a positive integer to support keyboard navigation.
|
|
*/
|
|
static readonly ROUND = 15;
|
|
|
|
/** Half the width of protractor image. */
|
|
static readonly HALF = 100 / 2;
|
|
|
|
/**
|
|
* Default property describing which direction makes an angle field's value
|
|
* increase. Angle increases clockwise (true) or counterclockwise (false).
|
|
*/
|
|
static readonly CLOCKWISE = false;
|
|
|
|
/**
|
|
* The default offset of 0 degrees (and all angles). Always offsets in the
|
|
* counterclockwise direction, regardless of the field's clockwise property.
|
|
* Usually either 0 (0 = right) or 90 (0 = up).
|
|
*/
|
|
static readonly OFFSET = 0;
|
|
|
|
/**
|
|
* The default maximum angle to allow before wrapping.
|
|
* Usually either 360 (for 0 to 359.9) or 180 (for -179.9 to 180).
|
|
*/
|
|
static readonly WRAP = 360;
|
|
|
|
/**
|
|
* Radius of protractor circle. Slightly smaller than protractor size since
|
|
* otherwise SVG crops off half the border at the edges.
|
|
*/
|
|
static readonly RADIUS: number = FieldAngle.HALF - 1;
|
|
private clockwise_: boolean;
|
|
private offset_: number;
|
|
private wrap_: number;
|
|
private round_: number;
|
|
|
|
/** The angle picker's SVG element. */
|
|
private editor_: SVGElement|null = null;
|
|
|
|
/** The angle picker's gauge path depending on the value. */
|
|
gauge_: SVGElement|null = null;
|
|
|
|
/** The angle picker's line drawn representing the value's angle. */
|
|
line_: SVGElement|null = null;
|
|
|
|
/** The degree symbol for this field. */
|
|
// AnyDuringMigration because: Type 'null' is not assignable to type
|
|
// 'SVGTSpanElement'.
|
|
protected symbol_: SVGTSpanElement = null as AnyDuringMigration;
|
|
|
|
/** Wrapper click event data. */
|
|
private clickWrapper_: browserEvents.Data|null = null;
|
|
|
|
/** Surface click event data. */
|
|
private clickSurfaceWrapper_: browserEvents.Data|null = null;
|
|
|
|
/** Surface mouse move event data. */
|
|
private moveSurfaceWrapper_: browserEvents.Data|null = null;
|
|
|
|
/**
|
|
* Serializable fields are saved by the serializer, non-serializable fields
|
|
* are not. Editable fields should also be serializable.
|
|
*/
|
|
override SERIALIZABLE = true;
|
|
|
|
/**
|
|
* @param opt_value The initial value of the field. Should cast to a number.
|
|
* Defaults to 0. Also accepts Field.SKIP_SETUP if you wish to skip setup
|
|
* (only used by subclasses that want to handle configuration and setting
|
|
* the field value after their own constructors have run).
|
|
* @param opt_validator A function that is called to validate changes to the
|
|
* field's value. Takes in a number & returns a validated number, or null
|
|
* to abort the change.
|
|
* @param opt_config A map of options used to configure the field.
|
|
* See the [field creation documentation]{@link
|
|
* https://developers.google.com/blockly/guides/create-custom-blocks/fields/built-in-fields/angle#creation}
|
|
* for a list of properties this parameter supports.
|
|
*/
|
|
constructor(
|
|
opt_value?: string|number|Sentinel, opt_validator?: Function,
|
|
opt_config?: AnyDuringMigration) {
|
|
super(Field.SKIP_SETUP);
|
|
|
|
/**
|
|
* Should the angle increase as the angle picker is moved clockwise (true)
|
|
* or counterclockwise (false)
|
|
* @see FieldAngle.CLOCKWISE
|
|
*/
|
|
this.clockwise_ = FieldAngle.CLOCKWISE;
|
|
|
|
/**
|
|
* The offset of zero degrees (and all other angles).
|
|
* @see FieldAngle.OFFSET
|
|
*/
|
|
this.offset_ = FieldAngle.OFFSET;
|
|
|
|
/**
|
|
* The maximum angle to allow before wrapping.
|
|
* @see FieldAngle.WRAP
|
|
*/
|
|
this.wrap_ = FieldAngle.WRAP;
|
|
|
|
/**
|
|
* The amount to round angles to when using a mouse or keyboard nav input.
|
|
* @see FieldAngle.ROUND
|
|
*/
|
|
this.round_ = FieldAngle.ROUND;
|
|
|
|
if (opt_value === Field.SKIP_SETUP) {
|
|
return;
|
|
}
|
|
if (opt_config) {
|
|
this.configure_(opt_config);
|
|
}
|
|
this.setValue(opt_value);
|
|
if (opt_validator) {
|
|
this.setValidator(opt_validator);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Configure the field based on the given map of options.
|
|
* @param config A map of options to configure the field based on.
|
|
*/
|
|
override configure_(config: AnyDuringMigration) {
|
|
super.configure_(config);
|
|
|
|
switch (config['mode']) {
|
|
case 'compass':
|
|
this.clockwise_ = true;
|
|
this.offset_ = 90;
|
|
break;
|
|
case 'protractor':
|
|
// This is the default mode, so we could do nothing. But just to
|
|
// future-proof, we'll set it anyway.
|
|
this.clockwise_ = false;
|
|
this.offset_ = 0;
|
|
break;
|
|
}
|
|
|
|
// Allow individual settings to override the mode setting.
|
|
const clockwise = config['clockwise'];
|
|
if (typeof clockwise === 'boolean') {
|
|
this.clockwise_ = clockwise;
|
|
}
|
|
|
|
// If these are passed as null then we should leave them on the default.
|
|
let offset = config['offset'];
|
|
if (offset !== null) {
|
|
offset = Number(offset);
|
|
if (!isNaN(offset)) {
|
|
this.offset_ = offset;
|
|
}
|
|
}
|
|
let wrap = config['wrap'];
|
|
if (wrap !== null) {
|
|
wrap = Number(wrap);
|
|
if (!isNaN(wrap)) {
|
|
this.wrap_ = wrap;
|
|
}
|
|
}
|
|
let round = config['round'];
|
|
if (round !== null) {
|
|
round = Number(round);
|
|
if (!isNaN(round)) {
|
|
this.round_ = round;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create the block UI for this field.
|
|
* @internal
|
|
*/
|
|
override initView() {
|
|
super.initView();
|
|
// Add the degree symbol to the left of the number, even in RTL (issue
|
|
// #2380)
|
|
this.symbol_ = dom.createSvgElement(Svg.TSPAN, {});
|
|
this.symbol_.appendChild(document.createTextNode('\u00B0'));
|
|
this.textElement_.appendChild(this.symbol_);
|
|
}
|
|
|
|
/** Updates the graph when the field rerenders. */
|
|
protected override render_() {
|
|
super.render_();
|
|
this.updateGraph_();
|
|
}
|
|
|
|
/**
|
|
* Create and show the angle field's editor.
|
|
* @param opt_e Optional mouse event that triggered the field to open, or
|
|
* undefined if triggered programmatically.
|
|
*/
|
|
protected override showEditor_(opt_e?: Event) {
|
|
// Mobile browsers have issues with in-line textareas (focus & keyboards).
|
|
const noFocus = userAgent.MOBILE || userAgent.ANDROID || userAgent.IPAD;
|
|
super.showEditor_(opt_e, noFocus);
|
|
|
|
this.dropdownCreate_();
|
|
// AnyDuringMigration because: Argument of type 'SVGElement | null' is not
|
|
// assignable to parameter of type 'Node'.
|
|
dropDownDiv.getContentDiv().appendChild(this.editor_ as AnyDuringMigration);
|
|
|
|
if (this.sourceBlock_ instanceof BlockSvg) {
|
|
dropDownDiv.setColour(
|
|
this.sourceBlock_.style.colourPrimary,
|
|
this.sourceBlock_.style.colourTertiary);
|
|
}
|
|
|
|
// AnyDuringMigration because: Argument of type 'this' is not assignable to
|
|
// parameter of type 'Field'.
|
|
dropDownDiv.showPositionedByField(
|
|
this as AnyDuringMigration, this.dropdownDispose_.bind(this));
|
|
|
|
this.updateGraph_();
|
|
}
|
|
|
|
/** Create the angle dropdown editor. */
|
|
private dropdownCreate_() {
|
|
const svg = dom.createSvgElement(Svg.SVG, {
|
|
'xmlns': dom.SVG_NS,
|
|
'xmlns:html': dom.HTML_NS,
|
|
'xmlns:xlink': dom.XLINK_NS,
|
|
'version': '1.1',
|
|
'height': FieldAngle.HALF * 2 + 'px',
|
|
'width': FieldAngle.HALF * 2 + 'px',
|
|
'style': 'touch-action: none',
|
|
});
|
|
const circle = dom.createSvgElement(
|
|
Svg.CIRCLE, {
|
|
'cx': FieldAngle.HALF,
|
|
'cy': FieldAngle.HALF,
|
|
'r': FieldAngle.RADIUS,
|
|
'class': 'blocklyAngleCircle',
|
|
},
|
|
svg);
|
|
this.gauge_ =
|
|
dom.createSvgElement(Svg.PATH, {'class': 'blocklyAngleGauge'}, svg);
|
|
this.line_ = dom.createSvgElement(
|
|
Svg.LINE, {
|
|
'x1': FieldAngle.HALF,
|
|
'y1': FieldAngle.HALF,
|
|
'class': 'blocklyAngleLine',
|
|
},
|
|
svg);
|
|
// Draw markers around the edge.
|
|
for (let angle = 0; angle < 360; angle += 15) {
|
|
dom.createSvgElement(
|
|
Svg.LINE, {
|
|
'x1': FieldAngle.HALF + FieldAngle.RADIUS,
|
|
'y1': FieldAngle.HALF,
|
|
'x2': FieldAngle.HALF + FieldAngle.RADIUS -
|
|
(angle % 45 === 0 ? 10 : 5),
|
|
'y2': FieldAngle.HALF,
|
|
'class': 'blocklyAngleMarks',
|
|
'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' +
|
|
FieldAngle.HALF + ')',
|
|
},
|
|
svg);
|
|
}
|
|
|
|
// The angle picker is different from other fields in that it updates on
|
|
// mousemove even if it's not in the middle of a drag. In future we may
|
|
// change this behaviour.
|
|
this.clickWrapper_ =
|
|
browserEvents.conditionalBind(svg, 'click', this, this.hide_);
|
|
// On touch devices, the picker's value is only updated with a drag. Add
|
|
// a click handler on the drag surface to update the value if the surface
|
|
// is clicked.
|
|
this.clickSurfaceWrapper_ = browserEvents.conditionalBind(
|
|
circle, 'click', this, this.onMouseMove_, true, true);
|
|
this.moveSurfaceWrapper_ = browserEvents.conditionalBind(
|
|
circle, 'mousemove', this, this.onMouseMove_, true, true);
|
|
this.editor_ = svg;
|
|
}
|
|
|
|
/** Disposes of events and DOM-references belonging to the angle editor. */
|
|
private dropdownDispose_() {
|
|
if (this.clickWrapper_) {
|
|
browserEvents.unbind(this.clickWrapper_);
|
|
this.clickWrapper_ = null;
|
|
}
|
|
if (this.clickSurfaceWrapper_) {
|
|
browserEvents.unbind(this.clickSurfaceWrapper_);
|
|
this.clickSurfaceWrapper_ = null;
|
|
}
|
|
if (this.moveSurfaceWrapper_) {
|
|
browserEvents.unbind(this.moveSurfaceWrapper_);
|
|
this.moveSurfaceWrapper_ = null;
|
|
}
|
|
this.gauge_ = null;
|
|
this.line_ = null;
|
|
}
|
|
|
|
/** Hide the editor. */
|
|
private hide_() {
|
|
dropDownDiv.hideIfOwner(this);
|
|
WidgetDiv.hide();
|
|
}
|
|
|
|
/**
|
|
* Set the angle to match the mouse's position.
|
|
* @param e Mouse move event.
|
|
*/
|
|
protected onMouseMove_(e: Event) {
|
|
// Calculate angle.
|
|
const bBox = this.gauge_!.ownerSVGElement!.getBoundingClientRect();
|
|
// AnyDuringMigration because: Property 'clientX' does not exist on type
|
|
// 'Event'.
|
|
const dx = (e as AnyDuringMigration).clientX - bBox.left - FieldAngle.HALF;
|
|
// AnyDuringMigration because: Property 'clientY' does not exist on type
|
|
// 'Event'.
|
|
const dy = (e as AnyDuringMigration).clientY - bBox.top - FieldAngle.HALF;
|
|
let angle = Math.atan(-dy / dx);
|
|
if (isNaN(angle)) {
|
|
// This shouldn't happen, but let's not let this error propagate further.
|
|
return;
|
|
}
|
|
angle = math.toDegrees(angle);
|
|
// 0: East, 90: North, 180: West, 270: South.
|
|
if (dx < 0) {
|
|
angle += 180;
|
|
} else if (dy > 0) {
|
|
angle += 360;
|
|
}
|
|
|
|
// Do offsetting.
|
|
if (this.clockwise_) {
|
|
angle = this.offset_ + 360 - angle;
|
|
} else {
|
|
angle = 360 - (this.offset_ - angle);
|
|
}
|
|
|
|
this.displayMouseOrKeyboardValue_(angle);
|
|
}
|
|
|
|
/**
|
|
* Handles and displays values that are input via mouse or arrow key input.
|
|
* These values need to be rounded and wrapped before being displayed so
|
|
* that the text input's value is appropriate.
|
|
* @param angle New angle.
|
|
*/
|
|
private displayMouseOrKeyboardValue_(angle: number) {
|
|
if (this.round_) {
|
|
angle = Math.round(angle / this.round_) * this.round_;
|
|
}
|
|
angle = this.wrapValue_(angle);
|
|
if (angle !== this.value_) {
|
|
this.setEditorValue_(angle);
|
|
}
|
|
}
|
|
|
|
/** Redraw the graph with the current angle. */
|
|
private updateGraph_() {
|
|
if (!this.gauge_) {
|
|
return;
|
|
}
|
|
// Always display the input (i.e. getText) even if it is invalid.
|
|
let angleDegrees = Number(this.getText()) + this.offset_;
|
|
angleDegrees %= 360;
|
|
let angleRadians = math.toRadians(angleDegrees);
|
|
const path = ['M ', FieldAngle.HALF, ',', FieldAngle.HALF];
|
|
let x2 = FieldAngle.HALF;
|
|
let y2 = FieldAngle.HALF;
|
|
if (!isNaN(angleRadians)) {
|
|
const clockwiseFlag = Number(this.clockwise_);
|
|
const angle1 = math.toRadians(this.offset_);
|
|
const x1 = Math.cos(angle1) * FieldAngle.RADIUS;
|
|
const y1 = Math.sin(angle1) * -FieldAngle.RADIUS;
|
|
if (clockwiseFlag) {
|
|
angleRadians = 2 * angle1 - angleRadians;
|
|
}
|
|
x2 += Math.cos(angleRadians) * FieldAngle.RADIUS;
|
|
y2 -= Math.sin(angleRadians) * FieldAngle.RADIUS;
|
|
// Don't ask how the flag calculations work. They just do.
|
|
let largeFlag =
|
|
Math.abs(Math.floor((angleRadians - angle1) / Math.PI) % 2);
|
|
if (clockwiseFlag) {
|
|
largeFlag = 1 - largeFlag;
|
|
}
|
|
path.push(
|
|
' l ', x1, ',', y1, ' A ', FieldAngle.RADIUS, ',', FieldAngle.RADIUS,
|
|
' 0 ', largeFlag, ' ', clockwiseFlag, ' ', x2, ',', y2, ' z');
|
|
}
|
|
this.gauge_.setAttribute('d', path.join(''));
|
|
// AnyDuringMigration because: Argument of type 'number' is not assignable
|
|
// to parameter of type 'string'.
|
|
this.line_!.setAttribute('x2', x2 as AnyDuringMigration);
|
|
// AnyDuringMigration because: Argument of type 'number' is not assignable
|
|
// to parameter of type 'string'.
|
|
this.line_!.setAttribute('y2', y2 as AnyDuringMigration);
|
|
}
|
|
|
|
/**
|
|
* Handle key down to the editor.
|
|
* @param e Keyboard event.
|
|
*/
|
|
protected override onHtmlInputKeyDown_(e: Event) {
|
|
super.onHtmlInputKeyDown_(e);
|
|
|
|
let multiplier;
|
|
// AnyDuringMigration because: Property 'keyCode' does not exist on type
|
|
// 'Event'.
|
|
if ((e as AnyDuringMigration).keyCode === KeyCodes.LEFT) {
|
|
// decrement (increment in RTL)
|
|
multiplier = this.sourceBlock_.RTL ? 1 : -1;
|
|
// AnyDuringMigration because: Property 'keyCode' does not exist on type
|
|
// 'Event'.
|
|
} else if ((e as AnyDuringMigration).keyCode === KeyCodes.RIGHT) {
|
|
// increment (decrement in RTL)
|
|
multiplier = this.sourceBlock_.RTL ? -1 : 1;
|
|
// AnyDuringMigration because: Property 'keyCode' does not exist on type
|
|
// 'Event'.
|
|
} else if ((e as AnyDuringMigration).keyCode === KeyCodes.DOWN) {
|
|
// decrement
|
|
multiplier = -1;
|
|
// AnyDuringMigration because: Property 'keyCode' does not exist on type
|
|
// 'Event'.
|
|
} else if ((e as AnyDuringMigration).keyCode === KeyCodes.UP) {
|
|
// increment
|
|
multiplier = 1;
|
|
}
|
|
if (multiplier) {
|
|
const value = this.getValue() as number;
|
|
this.displayMouseOrKeyboardValue_(value + multiplier * this.round_);
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Ensure that the input value is a valid angle.
|
|
* @param opt_newValue The input value.
|
|
* @return A valid angle, or null if invalid.
|
|
*/
|
|
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
|
|
number|null {
|
|
const value = Number(opt_newValue);
|
|
if (isNaN(value) || !isFinite(value)) {
|
|
return null;
|
|
}
|
|
return this.wrapValue_(value);
|
|
}
|
|
|
|
/**
|
|
* Wraps the value so that it is in the range (-360 + wrap, wrap).
|
|
* @param value The value to wrap.
|
|
* @return The wrapped value.
|
|
*/
|
|
private wrapValue_(value: number): number {
|
|
value %= 360;
|
|
if (value < 0) {
|
|
value += 360;
|
|
}
|
|
if (value > this.wrap_) {
|
|
value -= 360;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
/**
|
|
* Construct a FieldAngle from a JSON arg object.
|
|
* @param options A JSON object with options (angle).
|
|
* @return The new field instance.
|
|
* @nocollapse
|
|
* @internal
|
|
*/
|
|
static override fromJson(options: AnyDuringMigration): FieldAngle {
|
|
// `this` might be a subclass of FieldAngle if that class doesn't override
|
|
// the static fromJson method.
|
|
return new this(options['angle'], undefined, options);
|
|
}
|
|
}
|
|
|
|
/** CSS for angle field. See css.js for use. */
|
|
Css.register(`
|
|
.blocklyAngleCircle {
|
|
stroke: #444;
|
|
stroke-width: 1;
|
|
fill: #ddd;
|
|
fill-opacity: .8;
|
|
}
|
|
|
|
.blocklyAngleMarks {
|
|
stroke: #444;
|
|
stroke-width: 1;
|
|
}
|
|
|
|
.blocklyAngleGauge {
|
|
fill: #f88;
|
|
fill-opacity: .8;
|
|
pointer-events: none;
|
|
}
|
|
|
|
.blocklyAngleLine {
|
|
stroke: #f00;
|
|
stroke-width: 2;
|
|
stroke-linecap: round;
|
|
pointer-events: none;
|
|
}
|
|
`);
|
|
|
|
fieldRegistry.register('field_angle', FieldAngle);
|
|
|
|
(FieldAngle.prototype as AnyDuringMigration).DEFAULT_VALUE = 0; |