mirror of
https://github.com/google/blockly.git
synced 2026-01-04 15:40:08 +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>
312 lines
9.7 KiB
TypeScript
312 lines
9.7 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2016 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Number input field
|
|
*/
|
|
|
|
/**
|
|
* Number input field
|
|
* @class
|
|
*/
|
|
import * as goog from '../closure/goog/goog.js';
|
|
goog.declareModuleId('Blockly.FieldNumber');
|
|
|
|
import {Field} from './field.js';
|
|
import * as fieldRegistry from './field_registry.js';
|
|
import {FieldTextInput} from './field_textinput.js';
|
|
import * as aria from './utils/aria.js';
|
|
import type {Sentinel} from './utils/sentinel.js';
|
|
|
|
|
|
/**
|
|
* Class for an editable number field.
|
|
* @alias Blockly.FieldNumber
|
|
*/
|
|
export class FieldNumber extends FieldTextInput {
|
|
/** The minimum value this number field can contain. */
|
|
protected min_: number = -Infinity;
|
|
|
|
/** The maximum value this number field can contain. */
|
|
protected max_: number = Infinity;
|
|
|
|
/** The multiple to which this fields value is rounded. */
|
|
protected precision_ = 0;
|
|
|
|
/**
|
|
* The number of decimal places to allow, or null to allow any number of
|
|
* decimal digits.
|
|
*/
|
|
private decimalPlaces_: number|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_min Minimum value. Will only be used if opt_config is not
|
|
* provided.
|
|
* @param opt_max Maximum value. Will only be used if opt_config is not
|
|
* provided.
|
|
* @param opt_precision Precision for value. Will only be used if opt_config
|
|
* is not provided.
|
|
* @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/number#creation}
|
|
* for a list of properties this parameter supports.
|
|
*/
|
|
constructor(
|
|
opt_value?: string|number|Sentinel, opt_min?: string|number|null,
|
|
opt_max?: string|number|null, opt_precision?: string|number|null,
|
|
opt_validator?: Function|null, opt_config?: AnyDuringMigration) {
|
|
// Pass SENTINEL so that we can define properties before value validation.
|
|
super(Field.SKIP_SETUP);
|
|
|
|
if (opt_value === Field.SKIP_SETUP) {
|
|
return;
|
|
}
|
|
if (opt_config) {
|
|
this.configure_(opt_config);
|
|
} else {
|
|
this.setConstraints(opt_min, opt_max, opt_precision);
|
|
}
|
|
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);
|
|
this.setMinInternal_(config['min']);
|
|
this.setMaxInternal_(config['max']);
|
|
this.setPrecisionInternal_(config['precision']);
|
|
}
|
|
|
|
/**
|
|
* Set the maximum, minimum and precision constraints on this field.
|
|
* Any of these properties may be undefined or NaN to be disabled.
|
|
* Setting precision (usually a power of 10) enforces a minimum step between
|
|
* values. That is, the user's value will rounded to the closest multiple of
|
|
* precision. The least significant digit place is inferred from the
|
|
* precision. Integers values can be enforces by choosing an integer
|
|
* precision.
|
|
* @param min Minimum value.
|
|
* @param max Maximum value.
|
|
* @param precision Precision for value.
|
|
*/
|
|
setConstraints(
|
|
min: number|string|undefined|null, max: number|string|undefined|null,
|
|
precision: number|string|undefined|null) {
|
|
this.setMinInternal_(min);
|
|
this.setMaxInternal_(max);
|
|
this.setPrecisionInternal_(precision);
|
|
this.setValue(this.getValue());
|
|
}
|
|
|
|
/**
|
|
* Sets the minimum value this field can contain. Updates the value to
|
|
* reflect.
|
|
* @param min Minimum value.
|
|
*/
|
|
setMin(min: number|string|undefined|null) {
|
|
this.setMinInternal_(min);
|
|
this.setValue(this.getValue());
|
|
}
|
|
|
|
/**
|
|
* Sets the minimum value this field can contain. Called internally to avoid
|
|
* value updates.
|
|
* @param min Minimum value.
|
|
*/
|
|
private setMinInternal_(min: number|string|undefined|null) {
|
|
if (min == null) {
|
|
this.min_ = -Infinity;
|
|
} else {
|
|
min = Number(min);
|
|
if (!isNaN(min)) {
|
|
this.min_ = min;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the current minimum value this field can contain. Default is
|
|
* -Infinity.
|
|
* @return The current minimum value this field can contain.
|
|
*/
|
|
getMin(): number {
|
|
return this.min_;
|
|
}
|
|
|
|
/**
|
|
* Sets the maximum value this field can contain. Updates the value to
|
|
* reflect.
|
|
* @param max Maximum value.
|
|
*/
|
|
setMax(max: number|string|undefined|null) {
|
|
this.setMaxInternal_(max);
|
|
this.setValue(this.getValue());
|
|
}
|
|
|
|
/**
|
|
* Sets the maximum value this field can contain. Called internally to avoid
|
|
* value updates.
|
|
* @param max Maximum value.
|
|
*/
|
|
private setMaxInternal_(max: number|string|undefined|null) {
|
|
if (max == null) {
|
|
this.max_ = Infinity;
|
|
} else {
|
|
max = Number(max);
|
|
if (!isNaN(max)) {
|
|
this.max_ = max;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the current maximum value this field can contain. Default is
|
|
* Infinity.
|
|
* @return The current maximum value this field can contain.
|
|
*/
|
|
getMax(): number {
|
|
return this.max_;
|
|
}
|
|
|
|
/**
|
|
* Sets the precision of this field's value, i.e. the number to which the
|
|
* value is rounded. Updates the field to reflect.
|
|
* @param precision The number to which the field's value is rounded.
|
|
*/
|
|
setPrecision(precision: number|string|undefined|null) {
|
|
this.setPrecisionInternal_(precision);
|
|
this.setValue(this.getValue());
|
|
}
|
|
|
|
/**
|
|
* Sets the precision of this field's value. Called internally to avoid
|
|
* value updates.
|
|
* @param precision The number to which the field's value is rounded.
|
|
*/
|
|
private setPrecisionInternal_(precision: number|string|undefined|null) {
|
|
this.precision_ = Number(precision) || 0;
|
|
let precisionString = String(this.precision_);
|
|
if (precisionString.indexOf('e') !== -1) {
|
|
// String() is fast. But it turns .0000001 into '1e-7'.
|
|
// Use the much slower toLocaleString to access all the digits.
|
|
precisionString =
|
|
this.precision_.toLocaleString('en-US', {maximumFractionDigits: 20});
|
|
}
|
|
const decimalIndex = precisionString.indexOf('.');
|
|
if (decimalIndex === -1) {
|
|
// If the precision is 0 (float) allow any number of decimals,
|
|
// otherwise allow none.
|
|
this.decimalPlaces_ = precision ? 0 : null;
|
|
} else {
|
|
this.decimalPlaces_ = precisionString.length - decimalIndex - 1;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the current precision of this field. The precision being the
|
|
* number to which the field's value is rounded. A precision of 0 means that
|
|
* the value is not rounded.
|
|
* @return The number to which this field's value is rounded.
|
|
*/
|
|
getPrecision(): number {
|
|
return this.precision_;
|
|
}
|
|
|
|
/**
|
|
* Ensure that the input value is a valid number (must fulfill the
|
|
* constraints placed on the field).
|
|
* @param opt_newValue The input value.
|
|
* @return A valid number, or null if invalid.
|
|
*/
|
|
protected override doClassValidation_(opt_newValue?: AnyDuringMigration):
|
|
number|null {
|
|
if (opt_newValue === null) {
|
|
return null;
|
|
}
|
|
// Clean up text.
|
|
let newValue = String(opt_newValue);
|
|
// TODO: Handle cases like 'ten', '1.203,14', etc.
|
|
// 'O' is sometimes mistaken for '0' by inexperienced users.
|
|
newValue = newValue.replace(/O/ig, '0');
|
|
// Strip out thousands separators.
|
|
newValue = newValue.replace(/,/g, '');
|
|
// Ignore case of 'Infinity'.
|
|
newValue = newValue.replace(/infinity/i, 'Infinity');
|
|
|
|
// Clean up number.
|
|
let n = Number(newValue || 0);
|
|
if (isNaN(n)) {
|
|
// Invalid number.
|
|
return null;
|
|
}
|
|
// Get the value in range.
|
|
n = Math.min(Math.max(n, this.min_), this.max_);
|
|
// Round to nearest multiple of precision.
|
|
if (this.precision_ && isFinite(n)) {
|
|
n = Math.round(n / this.precision_) * this.precision_;
|
|
}
|
|
// Clean up floating point errors.
|
|
if (this.decimalPlaces_ !== null) {
|
|
n = Number(n.toFixed(this.decimalPlaces_));
|
|
}
|
|
return n;
|
|
}
|
|
|
|
/**
|
|
* Create the number input editor widget.
|
|
* @return The newly created number input editor.
|
|
*/
|
|
protected override widgetCreate_(): HTMLElement {
|
|
const htmlInput = super.widgetCreate_();
|
|
|
|
// Set the accessibility state
|
|
if (this.min_ > -Infinity) {
|
|
aria.setState(htmlInput, aria.State.VALUEMIN, this.min_);
|
|
}
|
|
if (this.max_ < Infinity) {
|
|
aria.setState(htmlInput, aria.State.VALUEMAX, this.max_);
|
|
}
|
|
return htmlInput;
|
|
}
|
|
|
|
/**
|
|
* Construct a FieldNumber from a JSON arg object.
|
|
* @param options A JSON object with options (value, min, max, and precision).
|
|
* @return The new field instance.
|
|
* @nocollapse
|
|
* @internal
|
|
*/
|
|
static override fromJson(options: AnyDuringMigration): FieldNumber {
|
|
// `this` might be a subclass of FieldNumber if that class doesn't override
|
|
// the static fromJson method.
|
|
return new this(
|
|
options['value'], undefined, undefined, undefined, undefined, options);
|
|
}
|
|
}
|
|
|
|
fieldRegistry.register('field_number', FieldNumber);
|
|
|
|
(FieldNumber.prototype as AnyDuringMigration).DEFAULT_VALUE = 0;
|