refactor(blocks): Migrate blocks/text.js to TypeScript (#6958)

* refactor(blocks): auto-migration of blocks/text.js to ts

* refactor(blocks): fix up some types in blocks/text.ts

* refactor(blocks): improve some types in text.ts

* refactor(blocks): additional type cleanups

* chore: format

* chore: fix typo

* chore: respond to PR comments

* chore: respond to PR comments
This commit is contained in:
Rachel Fenichel
2023-04-28 10:54:28 -07:00
committed by GitHub
parent 5e186de179
commit d47369acfe

View File

@@ -6,40 +6,34 @@
/** /**
* @fileoverview Text blocks for Blockly. * @fileoverview Text blocks for Blockly.
* @suppress {checkTypes}
*/ */
'use strict';
goog.module('Blockly.libraryBlocks.texts'); import * as goog from '../closure/goog/goog.js';
goog.declareModuleId('Blockly.libraryBlocks.texts');
const Extensions = goog.require('Blockly.Extensions'); import * as Extensions from '../core/extensions.js';
const {Msg} = goog.require('Blockly.Msg'); import * as fieldRegistry from '../core/field_registry.js';
const fieldRegistry = goog.require('Blockly.fieldRegistry'); import * as xmlUtils from '../core/utils/xml.js';
/* eslint-disable-next-line no-unused-vars */ import {Align} from '../core/input.js';
const xmlUtils = goog.require('Blockly.utils.xml'); import type {Block} from '../core/block.js';
const {Align} = goog.require('Blockly.Input'); import type {BlockSvg} from '../core/block_svg.js';
/* eslint-disable-next-line no-unused-vars */ import {Connection} from '../core/connection.js';
const {Block} = goog.requireType('Blockly.Block'); import {ConnectionType} from '../core/connection_type.js';
// const {BlockDefinition} = goog.requireType('Blockly.blocks'); import {FieldImage} from '../core/field_image.js';
// TODO (6248): Properly import the BlockDefinition type. import {FieldDropdown} from '../core/field_dropdown.js';
/* eslint-disable-next-line no-unused-vars */ import {FieldTextInput} from '../core/field_textinput.js';
const BlockDefinition = Object; import {Msg} from '../core/msg.js';
const {ConnectionType} = goog.require('Blockly.ConnectionType'); import {Mutator} from '../core/mutator.js';
const {Mutator} = goog.require('Blockly.Mutator'); import type {Workspace} from '../core/workspace.js';
/* eslint-disable-next-line no-unused-vars */ import {createBlockDefinitionsFromJsonArray, defineBlocks} from '../core/common.js';
const {Workspace} = goog.requireType('Blockly.Workspace'); import '../core/field_multilineinput.js';
const {createBlockDefinitionsFromJsonArray, defineBlocks} = goog.require('Blockly.common'); import '../core/field_variable.js';
/** @suppress {extraRequire} */
goog.require('Blockly.FieldMultilineInput');
/** @suppress {extraRequire} */
goog.require('Blockly.FieldVariable');
/** /**
* A dictionary of the block definitions provided by this module. * A dictionary of the block definitions provided by this module.
* @type {!Object<string, !BlockDefinition>}
*/ */
const blocks = createBlockDefinitionsFromJsonArray([ export const blocks = createBlockDefinitionsFromJsonArray([
// Block for text value // Block for text value
{ {
'type': 'text', 'type': 'text',
@@ -243,14 +237,20 @@ const blocks = createBlockDefinitionsFromJsonArray([
'mutator': 'text_charAt_mutator', 'mutator': 'text_charAt_mutator',
}, },
]); ]);
exports.blocks = blocks;
blocks['text_getSubstring'] = { /** Type of a 'text_get_substring' block. */
type GetSubstringBlock = Block&GetSubstringMixin;
interface GetSubstringMixin extends GetSubstringType {
WHERE_OPTIONS_1: Array<[string, string]>;
WHERE_OPTIONS_2: Array<[string, string]>;
}
type GetSubstringType = typeof GET_SUBSTRING_BLOCK;
const GET_SUBSTRING_BLOCK = {
/** /**
* Block for getting substring. * Block for getting substring.
* @this {Block}
*/ */
init: function() { init: function(this: GetSubstringBlock) {
this['WHERE_OPTIONS_1'] = [ this['WHERE_OPTIONS_1'] = [
[Msg['TEXT_GET_SUBSTRING_START_FROM_START'], 'FROM_START'], [Msg['TEXT_GET_SUBSTRING_START_FROM_START'], 'FROM_START'],
[Msg['TEXT_GET_SUBSTRING_START_FROM_END'], 'FROM_END'], [Msg['TEXT_GET_SUBSTRING_START_FROM_END'], 'FROM_END'],
@@ -279,24 +279,24 @@ blocks['text_getSubstring'] = {
/** /**
* Create XML to represent whether there are 'AT' inputs. * Create XML to represent whether there are 'AT' inputs.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @return {!Element} XML storage element. *
* @this {Block} * @returns XML storage element.
*/ */
mutationToDom: function() { mutationToDom: function(this: GetSubstringBlock): Element {
const container = xmlUtils.createElement('mutation'); const container = xmlUtils.createElement('mutation');
const isAt1 = this.getInput('AT1').type === ConnectionType.INPUT_VALUE; const isAt1 = this.getInput('AT1')!.type === ConnectionType.INPUT_VALUE;
container.setAttribute('at1', isAt1); container.setAttribute('at1', `${isAt1}`);
const isAt2 = this.getInput('AT2').type === ConnectionType.INPUT_VALUE; const isAt2 = this.getInput('AT2')!.type === ConnectionType.INPUT_VALUE;
container.setAttribute('at2', isAt2); container.setAttribute('at2', `${isAt2}`);
return container; return container;
}, },
/** /**
* Parse XML to restore the 'AT' inputs. * Parse XML to restore the 'AT' inputs.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @param {!Element} xmlElement XML storage element. *
* @this {Block} * @param xmlElement XML storage element.
*/ */
domToMutation: function(xmlElement) { domToMutation: function(this: GetSubstringBlock, xmlElement: Element) {
const isAt1 = (xmlElement.getAttribute('at1') === 'true'); const isAt1 = (xmlElement.getAttribute('at1') === 'true');
const isAt2 = (xmlElement.getAttribute('at2') === 'true'); const isAt2 = (xmlElement.getAttribute('at2') === 'true');
this.updateAt_(1, isAt1); this.updateAt_(1, isAt1);
@@ -311,12 +311,11 @@ blocks['text_getSubstring'] = {
/** /**
* Create or delete an input for a numeric index. * Create or delete an input for a numeric index.
* This block has two such inputs, independent of each other. * This block has two such inputs, independent of each other.
* @param {number} n Specify first or second input (1 or 2). *
* @param {boolean} isAt True if the input should exist. * @param n Which input to modify (either 1 or 2).
* @private * @param isAt True if the input includes a value connection, false otherwise.
* @this {Block}
*/ */
updateAt_: function(n, isAt) { updateAt_: function(this: GetSubstringBlock, n: 1|2, isAt: boolean) {
// Create or delete an input for the numeric index. // Create or delete an input for the numeric index.
// Destroy old 'AT' and 'ORDINAL' inputs. // Destroy old 'AT' and 'ORDINAL' inputs.
this.removeInput('AT' + n); this.removeInput('AT' + n);
@@ -338,21 +337,20 @@ blocks['text_getSubstring'] = {
} }
const menu = fieldRegistry.fromJson({ const menu = fieldRegistry.fromJson({
type: 'field_dropdown', type: 'field_dropdown',
options: this['WHERE_OPTIONS_' + n], options:
}); this[('WHERE_OPTIONS_' + n) as 'WHERE_OPTIONS_1' | 'WHERE_OPTIONS_2'],
}) as FieldDropdown;
menu.setValidator( menu.setValidator(
/** /**
* @param {*} value The input value. * @param value The input value.
* @this {FieldDropdown} * @return Null if the field has been replaced; otherwise undefined.
* @return {null|undefined} Null if the field has been replaced;
* otherwise undefined.
*/ */
function(value) { function(this: FieldDropdown, value: any): null|undefined {
const newAt = (value === 'FROM_START') || (value === 'FROM_END'); const newAt = (value === 'FROM_START') || (value === 'FROM_END');
// The 'isAt' variable is available due to this function being a // The 'isAt' variable is available due to this function being a
// closure. // closure.
if (newAt !== isAt) { if (newAt !== isAt) {
const block = this.getSourceBlock(); const block = this.getSourceBlock() as GetSubstringBlock;
block.updateAt_(n, newAt); block.updateAt_(n, newAt);
// This menu has been destroyed and replaced. // This menu has been destroyed and replaced.
// Update the replacement. // Update the replacement.
@@ -362,7 +360,7 @@ blocks['text_getSubstring'] = {
return undefined; return undefined;
}); });
this.getInput('AT' + n).appendField(menu, 'WHERE' + n); this.getInput('AT' + n)!.appendField(menu, 'WHERE' + n);
if (n === 1) { if (n === 1) {
this.moveInputBefore('AT1', 'AT2'); this.moveInputBefore('AT1', 'AT2');
if (this.getInput('ORDINAL1')) { if (this.getInput('ORDINAL1')) {
@@ -372,12 +370,13 @@ blocks['text_getSubstring'] = {
}, },
}; };
blocks['text_getSubstring'] = GET_SUBSTRING_BLOCK;
blocks['text_changeCase'] = { blocks['text_changeCase'] = {
/** /**
* Block for changing capitalization. * Block for changing capitalization.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
const OPERATORS = [ const OPERATORS = [
[Msg['TEXT_CHANGECASE_OPERATOR_UPPERCASE'], 'UPPERCASE'], [Msg['TEXT_CHANGECASE_OPERATOR_UPPERCASE'], 'UPPERCASE'],
[Msg['TEXT_CHANGECASE_OPERATOR_LOWERCASE'], 'LOWERCASE'], [Msg['TEXT_CHANGECASE_OPERATOR_LOWERCASE'], 'LOWERCASE'],
@@ -389,7 +388,7 @@ blocks['text_changeCase'] = {
fieldRegistry.fromJson({ fieldRegistry.fromJson({
type: 'field_dropdown', type: 'field_dropdown',
options: OPERATORS, options: OPERATORS,
}), }) as FieldDropdown,
'CASE'); 'CASE');
this.setOutput(true, 'String'); this.setOutput(true, 'String');
this.setTooltip(Msg['TEXT_CHANGECASE_TOOLTIP']); this.setTooltip(Msg['TEXT_CHANGECASE_TOOLTIP']);
@@ -399,9 +398,8 @@ blocks['text_changeCase'] = {
blocks['text_trim'] = { blocks['text_trim'] = {
/** /**
* Block for trimming spaces. * Block for trimming spaces.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
const OPERATORS = [ const OPERATORS = [
[Msg['TEXT_TRIM_OPERATOR_BOTH'], 'BOTH'], [Msg['TEXT_TRIM_OPERATOR_BOTH'], 'BOTH'],
[Msg['TEXT_TRIM_OPERATOR_LEFT'], 'LEFT'], [Msg['TEXT_TRIM_OPERATOR_LEFT'], 'LEFT'],
@@ -413,7 +411,7 @@ blocks['text_trim'] = {
fieldRegistry.fromJson({ fieldRegistry.fromJson({
type: 'field_dropdown', type: 'field_dropdown',
options: OPERATORS, options: OPERATORS,
}), }) as FieldDropdown,
'MODE'); 'MODE');
this.setOutput(true, 'String'); this.setOutput(true, 'String');
this.setTooltip(Msg['TEXT_TRIM_TOOLTIP']); this.setTooltip(Msg['TEXT_TRIM_TOOLTIP']);
@@ -423,9 +421,8 @@ blocks['text_trim'] = {
blocks['text_print'] = { blocks['text_print'] = {
/** /**
* Block for print statement. * Block for print statement.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
this.jsonInit({ this.jsonInit({
'message0': Msg['TEXT_PRINT_TITLE'], 'message0': Msg['TEXT_PRINT_TITLE'],
'args0': [ 'args0': [
@@ -443,28 +440,30 @@ blocks['text_print'] = {
}, },
}; };
type PromptCommonBlock = Block&PromptCommonMixin;
interface PromptCommonMixin extends PromptCommonType {}
type PromptCommonType = typeof PROMPT_COMMON;
/** /**
* Common properties for the text_prompt_ext and text_prompt blocks * Common properties for the text_prompt_ext and text_prompt blocks
* definitions. * definitions.
*/ */
const TEXT_PROMPT_COMMON = { const PROMPT_COMMON = {
/** /**
* Modify this block to have the correct output type. * Modify this block to have the correct output type.
* @param {string} newOp Either 'TEXT' or 'NUMBER'. *
* @private * @param newOp The new output type. Should be either 'TEXT' or 'NUMBER'.
* @this {Block}
*/ */
updateType_: function(newOp) { updateType_: function(this: PromptCommonBlock, newOp: string) {
this.outputConnection.setCheck(newOp === 'NUMBER' ? 'Number' : 'String'); this.outputConnection!.setCheck(newOp === 'NUMBER' ? 'Number' : 'String');
}, },
/** /**
* Create XML to represent the output type. * Create XML to represent the output type.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @return {!Element} XML storage element. *
* @this {Block} * @returns XML storage element.
*/ */
mutationToDom: function() { mutationToDom: function(this: PromptCommonBlock): Element {
const container = xmlUtils.createElement('mutation'); const container = xmlUtils.createElement('mutation');
container.setAttribute('type', this.getFieldValue('TYPE')); container.setAttribute('type', this.getFieldValue('TYPE'));
return container; return container;
@@ -472,21 +471,20 @@ const TEXT_PROMPT_COMMON = {
/** /**
* Parse XML to restore the output type. * Parse XML to restore the output type.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @param {!Element} xmlElement XML storage element. *
* @this {Block} * @param xmlElement XML storage element.
*/ */
domToMutation: function(xmlElement) { domToMutation: function(this: PromptCommonBlock, xmlElement: Element) {
this.updateType_(xmlElement.getAttribute('type')); this.updateType_(xmlElement.getAttribute('type')!);
}, },
}; };
blocks['text_prompt_ext'] = { blocks['text_prompt_ext'] = {
...TEXT_PROMPT_COMMON, ...PROMPT_COMMON,
/** /**
* Block for prompt function (external message). * Block for prompt function (external message).
* @this {Block}
*/ */
init: function() { init: function(this: PromptCommonBlock) {
const TYPES = [ const TYPES = [
[Msg['TEXT_PROMPT_TYPE_TEXT'], 'TEXT'], [Msg['TEXT_PROMPT_TYPE_TEXT'], 'TEXT'],
[Msg['TEXT_PROMPT_TYPE_NUMBER'], 'NUMBER'], [Msg['TEXT_PROMPT_TYPE_NUMBER'], 'NUMBER'],
@@ -498,9 +496,10 @@ blocks['text_prompt_ext'] = {
const dropdown = fieldRegistry.fromJson({ const dropdown = fieldRegistry.fromJson({
type: 'field_dropdown', type: 'field_dropdown',
options: TYPES, options: TYPES,
}); }) as FieldDropdown;
dropdown.setValidator(function(newOp) { dropdown.setValidator(function(this: FieldDropdown, newOp: string) {
thisBlock.updateType_(newOp); thisBlock.updateType_(newOp);
return undefined; // FieldValidators can't be void. Use option as-is.
}); });
this.appendValueInput('TEXT').appendField(dropdown, 'TYPE'); this.appendValueInput('TEXT').appendField(dropdown, 'TYPE');
this.setOutput(true, 'String'); this.setOutput(true, 'String');
@@ -517,14 +516,15 @@ blocks['text_prompt_ext'] = {
// XML hooks are kept for backwards compatibility. // XML hooks are kept for backwards compatibility.
}; };
blocks['text_prompt'] = { type PromptBlock = Block&PromptCommonMixin&QuoteImageMixin;
...TEXT_PROMPT_COMMON,
const TEXT_PROMPT_BLOCK = {
...PROMPT_COMMON,
/** /**
* Block for prompt function (internal message). * Block for prompt function (internal message).
* The 'text_prompt_ext' block is preferred as it is more flexible. * The 'text_prompt_ext' block is preferred as it is more flexible.
* @this {Block}
*/ */
init: function() { init: function(this: PromptBlock) {
this.mixin(QUOTE_IMAGE_MIXIN); this.mixin(QUOTE_IMAGE_MIXIN);
const TYPES = [ const TYPES = [
[Msg['TEXT_PROMPT_TYPE_TEXT'], 'TEXT'], [Msg['TEXT_PROMPT_TYPE_TEXT'], 'TEXT'],
@@ -538,9 +538,10 @@ blocks['text_prompt'] = {
const dropdown = fieldRegistry.fromJson({ const dropdown = fieldRegistry.fromJson({
type: 'field_dropdown', type: 'field_dropdown',
options: TYPES, options: TYPES,
}); }) as FieldDropdown;
dropdown.setValidator(function(newOp) { dropdown.setValidator(function(this: FieldDropdown, newOp: string) {
thisBlock.updateType_(newOp); thisBlock.updateType_(newOp);
return undefined; // FieldValidators can't be void. Use option as-is.
}); });
this.appendDummyInput() this.appendDummyInput()
.appendField(dropdown, 'TYPE') .appendField(dropdown, 'TYPE')
@@ -549,7 +550,7 @@ blocks['text_prompt'] = {
fieldRegistry.fromJson({ fieldRegistry.fromJson({
type: 'field_input', type: 'field_input',
text: '', text: '',
}), }) as FieldTextInput,
'TEXT') 'TEXT')
.appendField(this.newQuote_(false)); .appendField(this.newQuote_(false));
this.setOutput(true, 'String'); this.setOutput(true, 'String');
@@ -561,12 +562,13 @@ blocks['text_prompt'] = {
}, },
}; };
blocks['text_prompt'] = TEXT_PROMPT_BLOCK;
blocks['text_count'] = { blocks['text_count'] = {
/** /**
* Block for counting how many times one string appears within another string. * Block for counting how many times one string appears within another string.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
this.jsonInit({ this.jsonInit({
'message0': Msg['TEXT_COUNT_MESSAGE0'], 'message0': Msg['TEXT_COUNT_MESSAGE0'],
'args0': [ 'args0': [
@@ -593,9 +595,8 @@ blocks['text_count'] = {
blocks['text_replace'] = { blocks['text_replace'] = {
/** /**
* Block for replacing one string with another in the text. * Block for replacing one string with another in the text.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
this.jsonInit({ this.jsonInit({
'message0': Msg['TEXT_REPLACE_MESSAGE0'], 'message0': Msg['TEXT_REPLACE_MESSAGE0'],
'args0': [ 'args0': [
@@ -627,9 +628,8 @@ blocks['text_replace'] = {
blocks['text_reverse'] = { blocks['text_reverse'] = {
/** /**
* Block for reversing a string. * Block for reversing a string.
* @this {Block}
*/ */
init: function() { init: function(this: Block) {
this.jsonInit({ this.jsonInit({
'message0': Msg['TEXT_REVERSE_MESSAGE0'], 'message0': Msg['TEXT_REVERSE_MESSAGE0'],
'args0': [ 'args0': [
@@ -648,16 +648,15 @@ blocks['text_reverse'] = {
}, },
}; };
/** /** Type of a block that has QUOTE_IMAGE_MIXIN */
* @mixin type QuoteImageBlock = Block&QuoteImageMixin;
* @package interface QuoteImageMixin extends QuoteImageMixinType {}
* @readonly type QuoteImageMixinType = typeof QUOTE_IMAGE_MIXIN;
*/
const QUOTE_IMAGE_MIXIN = { const QUOTE_IMAGE_MIXIN = {
/** /**
* Image data URI of an LTR opening double quote (same as RTL closing double * Image data URI of an LTR opening double quote (same as RTL closing double
* quote). * quote).
* @readonly
*/ */
QUOTE_IMAGE_LEFT_DATAURI: QUOTE_IMAGE_LEFT_DATAURI:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAA' + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAA' +
@@ -668,7 +667,6 @@ const QUOTE_IMAGE_MIXIN = {
/** /**
* Image data URI of an LTR closing double quote (same as RTL opening double * Image data URI of an LTR closing double quote (same as RTL opening double
* quote). * quote).
* @readonly
*/ */
QUOTE_IMAGE_RIGHT_DATAURI: QUOTE_IMAGE_RIGHT_DATAURI:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAA' + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAKCAQAAAAqJXdxAAAA' +
@@ -678,21 +676,19 @@ const QUOTE_IMAGE_MIXIN = {
'lLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==', 'lLtGIHQMaCVnwDnADZIFIrXsoXrgAAAABJRU5ErkJggg==',
/** /**
* Pixel width of QUOTE_IMAGE_LEFT_DATAURI and QUOTE_IMAGE_RIGHT_DATAURI. * Pixel width of QUOTE_IMAGE_LEFT_DATAURI and QUOTE_IMAGE_RIGHT_DATAURI.
* @readonly
*/ */
QUOTE_IMAGE_WIDTH: 12, QUOTE_IMAGE_WIDTH: 12,
/** /**
* Pixel height of QUOTE_IMAGE_LEFT_DATAURI and QUOTE_IMAGE_RIGHT_DATAURI. * Pixel height of QUOTE_IMAGE_LEFT_DATAURI and QUOTE_IMAGE_RIGHT_DATAURI.
* @readonly
*/ */
QUOTE_IMAGE_HEIGHT: 12, QUOTE_IMAGE_HEIGHT: 12,
/** /**
* Inserts appropriate quote images before and after the named field. * Inserts appropriate quote images before and after the named field.
* @param {string} fieldName The name of the field to wrap with quotes. *
* @this {Block} * @param fieldName The name of the field to wrap with quotes.
*/ */
quoteField_: function(fieldName) { quoteField_: function(this: QuoteImageBlock, fieldName: string) {
for (let i = 0, input; (input = this.inputList[i]); i++) { for (let i = 0, input; (input = this.inputList[i]); i++) {
for (let j = 0, field; (field = input.fieldRow[j]); j++) { for (let j = 0, field; (field = input.fieldRow[j]); j++) {
if (fieldName === field.name) { if (fieldName === field.name) {
@@ -709,12 +705,12 @@ const QUOTE_IMAGE_MIXIN = {
/** /**
* A helper function that generates a FieldImage of an opening or * A helper function that generates a FieldImage of an opening or
* closing double quote. The selected quote will be adapted for RTL blocks. * closing double quote. The selected quote will be adapted for RTL blocks.
* @param {boolean} open If the image should be open quote ( in LTR). *
* @param open If the image should be open quote ( in LTR).
* Otherwise, a closing quote is used ( in LTR). * Otherwise, a closing quote is used ( in LTR).
* @return {!FieldImage} The new field. * @returns The new field.
* @this {Block}
*/ */
newQuote_: function(open) { newQuote_: function(this: QuoteImageBlock, open: boolean): FieldImage {
const isLeft = this.RTL ? !open : open; const isLeft = this.RTL ? !open : open;
const dataUri = const dataUri =
isLeft ? this.QUOTE_IMAGE_LEFT_DATAURI : this.QUOTE_IMAGE_RIGHT_DATAURI; isLeft ? this.QUOTE_IMAGE_LEFT_DATAURI : this.QUOTE_IMAGE_RIGHT_DATAURI;
@@ -724,76 +720,88 @@ const QUOTE_IMAGE_MIXIN = {
width: this.QUOTE_IMAGE_WIDTH, width: this.QUOTE_IMAGE_WIDTH,
height: this.QUOTE_IMAGE_HEIGHT, height: this.QUOTE_IMAGE_HEIGHT,
alt: isLeft ? '\u201C' : '\u201D', alt: isLeft ? '\u201C' : '\u201D',
}); }) as FieldImage;
}, },
}; };
/** /**
* Wraps TEXT field with images of double quote characters. * Wraps TEXT field with images of double quote characters.
* @this {Block}
*/ */
const TEXT_QUOTES_EXTENSION = function() { const QUOTES_EXTENSION = function(this: QuoteImageBlock) {
this.mixin(QUOTE_IMAGE_MIXIN); this.mixin(QUOTE_IMAGE_MIXIN);
this.quoteField_('TEXT'); this.quoteField_('TEXT');
}; };
/** Type of a block that has TEXT_JOIN_MUTATOR_MIXIN */
type JoinMutatorBlock = Block&JoinMutatorMixin&QuoteImageMixin;
interface JoinMutatorMixin extends JoinMutatorMixinType {}
type JoinMutatorMixinType = typeof JOIN_MUTATOR_MIXIN;
/** Type of a item block in the text_join_mutator bubble. */
type JoinItemBlock = BlockSvg&JoinItemMixin;
interface JoinItemMixin {
valueConnection_: Connection|null
}
/** /**
* Mixin for mutator functions in the 'text_join_mutator' extension. * Mixin for mutator functions in the 'text_join_mutator' extension.
* @mixin
* @augments Block
* @package
*/ */
const TEXT_JOIN_MUTATOR_MIXIN = { const JOIN_MUTATOR_MIXIN = {
itemCount_: 0,
/** /**
* Create XML to represent number of text inputs. * Create XML to represent number of text inputs.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @return {!Element} XML storage element. *
* @this {Block} * @returns XML storage element.
*/ */
mutationToDom: function() { mutationToDom: function(this: JoinMutatorBlock): Element {
const container = xmlUtils.createElement('mutation'); const container = xmlUtils.createElement('mutation');
container.setAttribute('items', this.itemCount_); container.setAttribute('items', `${this.itemCount_}`);
return container; return container;
}, },
/** /**
* Parse XML to restore the text inputs. * Parse XML to restore the text inputs.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @param {!Element} xmlElement XML storage element. *
* @this {Block} * @param xmlElement XML storage element.
*/ */
domToMutation: function(xmlElement) { domToMutation: function(this: JoinMutatorBlock, xmlElement: Element) {
this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10); this.itemCount_ = parseInt(xmlElement.getAttribute('items')!, 10);
this.updateShape_(); this.updateShape_();
}, },
/** /**
* Returns the state of this block as a JSON serializable object. * Returns the state of this block as a JSON serializable object.
* @return {{itemCount: number}} The state of this block, ie the item count. *
* @returns The state of this block, ie the item count.
*/ */
saveExtraState: function() { saveExtraState: function(this: JoinMutatorBlock): {itemCount: number;} {
return { return {
'itemCount': this.itemCount_, 'itemCount': this.itemCount_,
}; };
}, },
/** /**
* Applies the given state to this block. * Applies the given state to this block.
* @param {*} state The state to apply to this block, ie the item count. *
* @param state The state to apply to this block, ie the item count.
*/ */
loadExtraState: function(state) { loadExtraState: function(this: JoinMutatorBlock, state: {[x: string]: any;}) {
this.itemCount_ = state['itemCount']; this.itemCount_ = state['itemCount'];
this.updateShape_(); this.updateShape_();
}, },
/** /**
* Populate the mutator's dialog with this block's components. * Populate the mutator's dialog with this block's components.
* @param {!Workspace} workspace Mutator's workspace. *
* @return {!Block} Root block in mutator. * @param workspace Mutator's workspace.
* @this {Block} * @returns Root block in mutator.
*/ */
decompose: function(workspace) { decompose: function(this: JoinMutatorBlock, workspace: Workspace): Block {
const containerBlock = workspace.newBlock('text_create_join_container'); const containerBlock =
workspace.newBlock('text_create_join_container') as BlockSvg;
containerBlock.initSvg(); containerBlock.initSvg();
let connection = containerBlock.getInput('STACK').connection; let connection = containerBlock.getInput('STACK')!.connection!;
for (let i = 0; i < this.itemCount_; i++) { for (let i = 0; i < this.itemCount_; i++) {
const itemBlock = workspace.newBlock('text_create_join_item'); const itemBlock =
workspace.newBlock('text_create_join_item') as JoinItemBlock;
itemBlock.initSvg(); itemBlock.initSvg();
connection.connect(itemBlock.previousConnection); connection.connect(itemBlock.previousConnection);
connection = itemBlock.nextConnection; connection = itemBlock.nextConnection;
@@ -802,24 +810,25 @@ const TEXT_JOIN_MUTATOR_MIXIN = {
}, },
/** /**
* Reconfigure this block based on the mutator dialog's components. * Reconfigure this block based on the mutator dialog's components.
* @param {!Block} containerBlock Root block in mutator. *
* @this {Block} * @param containerBlock Root block in mutator.
*/ */
compose: function(containerBlock) { compose: function(this: JoinMutatorBlock, containerBlock: Block) {
let itemBlock = containerBlock.getInputTargetBlock('STACK'); let itemBlock =
containerBlock.getInputTargetBlock('STACK') as JoinItemBlock;
// Count number of inputs. // Count number of inputs.
const connections = []; const connections = [];
while (itemBlock) { while (itemBlock) {
if (itemBlock.isInsertionMarker()) { if (itemBlock.isInsertionMarker()) {
itemBlock = itemBlock.getNextBlock(); itemBlock = itemBlock.getNextBlock() as JoinItemBlock;
continue; continue;
} }
connections.push(itemBlock.valueConnection_); connections.push(itemBlock.valueConnection_);
itemBlock = itemBlock.getNextBlock(); itemBlock = itemBlock.getNextBlock() as JoinItemBlock;
} }
// Disconnect any children that don't belong. // Disconnect any children that don't belong.
for (let i = 0; i < this.itemCount_; i++) { for (let i = 0; i < this.itemCount_; i++) {
const connection = this.getInput('ADD' + i).connection.targetConnection; const connection = this.getInput('ADD' + i)!.connection!.targetConnection;
if (connection && connections.indexOf(connection) === -1) { if (connection && connections.indexOf(connection) === -1) {
connection.disconnect(); connection.disconnect();
} }
@@ -828,15 +837,15 @@ const TEXT_JOIN_MUTATOR_MIXIN = {
this.updateShape_(); this.updateShape_();
// Reconnect any child blocks. // Reconnect any child blocks.
for (let i = 0; i < this.itemCount_; i++) { for (let i = 0; i < this.itemCount_; i++) {
Mutator.reconnect(connections[i], this, 'ADD' + i); Mutator.reconnect(connections[i]!, this, 'ADD' + i);
} }
}, },
/** /**
* Store pointers to any connected child blocks. * Store pointers to any connected child blocks.
* @param {!Block} containerBlock Root block in mutator. *
* @this {Block} * @param containerBlock Root block in mutator.
*/ */
saveConnections: function(containerBlock) { saveConnections: function(this: JoinMutatorBlock, containerBlock: Block) {
let itemBlock = containerBlock.getInputTargetBlock('STACK'); let itemBlock = containerBlock.getInputTargetBlock('STACK');
let i = 0; let i = 0;
while (itemBlock) { while (itemBlock) {
@@ -845,17 +854,16 @@ const TEXT_JOIN_MUTATOR_MIXIN = {
continue; continue;
} }
const input = this.getInput('ADD' + i); const input = this.getInput('ADD' + i);
itemBlock.valueConnection_ = input && input.connection.targetConnection; (itemBlock as JoinItemBlock).valueConnection_ =
input && input.connection!.targetConnection;
itemBlock = itemBlock.getNextBlock(); itemBlock = itemBlock.getNextBlock();
i++; i++;
} }
}, },
/** /**
* Modify this block to have the correct number of inputs. * Modify this block to have the correct number of inputs.
* @private
* @this {Block}
*/ */
updateShape_: function() { updateShape_: function(this: JoinMutatorBlock) {
if (this.itemCount_ && this.getInput('EMPTY')) { if (this.itemCount_ && this.getInput('EMPTY')) {
this.removeInput('EMPTY'); this.removeInput('EMPTY');
} else if (!this.itemCount_ && !this.getInput('EMPTY')) { } else if (!this.itemCount_ && !this.getInput('EMPTY')) {
@@ -881,16 +889,15 @@ const TEXT_JOIN_MUTATOR_MIXIN = {
/** /**
* Performs final setup of a text_join block. * Performs final setup of a text_join block.
* @this {Block}
*/ */
const TEXT_JOIN_EXTENSION = function() { const JOIN_EXTENSION = function(this: JoinMutatorBlock) {
// Add the quote mixin for the itemCount_ = 0 case. // Add the quote mixin for the itemCount_ = 0 case.
this.mixin(QUOTE_IMAGE_MIXIN); this.mixin(QUOTE_IMAGE_MIXIN);
// Initialize the mutator values. // Initialize the mutator values.
this.itemCount_ = 2; this.itemCount_ = 2;
this.updateShape_(); this.updateShape_();
// Configure the mutator UI. // Configure the mutator UI.
this.setMutator(new Mutator(['text_create_join_item'], this)); this.setMutator(new Mutator(['text_create_join_item']));
}; };
// Update the tooltip of 'text_append' block to reference the variable. // Update the tooltip of 'text_append' block to reference the variable.
@@ -900,42 +907,43 @@ Extensions.register(
/** /**
* Update the tooltip of 'text_append' block to reference the variable. * Update the tooltip of 'text_append' block to reference the variable.
* @this {Block}
*/ */
const TEXT_INDEXOF_TOOLTIP_EXTENSION = function() { const INDEXOF_TOOLTIP_EXTENSION = function(this: Block) {
// Assign 'this' to a variable for use in the tooltip closure below. this.setTooltip(() => {
const thisBlock = this;
this.setTooltip(function() {
return Msg['TEXT_INDEXOF_TOOLTIP'].replace( return Msg['TEXT_INDEXOF_TOOLTIP'].replace(
'%1', thisBlock.workspace.options.oneBasedIndex ? '0' : '-1'); '%1', this.workspace.options.oneBasedIndex ? '0' : '-1');
}); });
}; };
/** Type of a block that has TEXT_CHARAT_MUTATOR_MIXIN */
type CharAtBlock = Block&CharAtMixin;
interface CharAtMixin extends CharAtMixinType {}
type CharAtMixinType = typeof CHARAT_MUTATOR_MIXIN;
/** /**
* Mixin for mutator functions in the 'text_charAt_mutator' extension. * Mixin for mutator functions in the 'text_charAt_mutator' extension.
* @mixin
* @augments Block
* @package
*/ */
const TEXT_CHARAT_MUTATOR_MIXIN = { const CHARAT_MUTATOR_MIXIN = {
isAt_: false,
/** /**
* Create XML to represent whether there is an 'AT' input. * Create XML to represent whether there is an 'AT' input.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @return {!Element} XML storage element. *
* @this {Block} * @returns XML storage element.
*/ */
mutationToDom: function() { mutationToDom: function(this: CharAtBlock): Element {
const container = xmlUtils.createElement('mutation'); const container = xmlUtils.createElement('mutation');
container.setAttribute('at', !!this.isAt_); container.setAttribute('at', `${this.isAt_}`);
return container; return container;
}, },
/** /**
* Parse XML to restore the 'AT' input. * Parse XML to restore the 'AT' input.
* Backwards compatible serialization implementation. * Backwards compatible serialization implementation.
* @param {!Element} xmlElement XML storage element. *
* @this {Block} * @param xmlElement XML storage element.
*/ */
domToMutation: function(xmlElement) { domToMutation: function(this: CharAtBlock, xmlElement: Element) {
// Note: Until January 2013 this block did not have mutations, // Note: Until January 2013 this block did not have mutations,
// so 'at' defaults to true. // so 'at' defaults to true.
const isAt = (xmlElement.getAttribute('at') !== 'false'); const isAt = (xmlElement.getAttribute('at') !== 'false');
@@ -949,11 +957,10 @@ const TEXT_CHARAT_MUTATOR_MIXIN = {
/** /**
* Create or delete an input for the numeric index. * Create or delete an input for the numeric index.
* @param {boolean} isAt True if the input should exist. *
* @private * @param isAt True if the input should exist.
* @this {Block}
*/ */
updateAt_: function(isAt) { updateAt_: function(this: CharAtBlock, isAt: boolean) {
// Destroy old 'AT' and 'ORDINAL' inputs. // Destroy old 'AT' and 'ORDINAL' inputs.
this.removeInput('AT', true); this.removeInput('AT', true);
this.removeInput('ORDINAL', true); this.removeInput('ORDINAL', true);
@@ -976,22 +983,17 @@ const TEXT_CHARAT_MUTATOR_MIXIN = {
/** /**
* Does the initial mutator update of text_charAt and adds the tooltip * Does the initial mutator update of text_charAt and adds the tooltip
* @this {Block}
*/ */
const TEXT_CHARAT_EXTENSION = function() { const CHARAT_EXTENSION = function(this: CharAtBlock) {
const dropdown = this.getField('WHERE'); const dropdown = this.getField('WHERE') as FieldDropdown;
dropdown.setValidator( dropdown.setValidator(function(this: FieldDropdown, value: any) {
/** const newAt = (value === 'FROM_START') || (value === 'FROM_END');
* @param {*} value The input value. const block = this.getSourceBlock() as CharAtBlock;
* @this {FieldDropdown} if (newAt !== block.isAt_) {
*/ block.updateAt_(newAt);
function(value) { }
const newAt = (value === 'FROM_START') || (value === 'FROM_END'); return undefined; // FieldValidators can't be void. Use option as-is.
if (newAt !== this.isAt_) { });
const block = this.getSourceBlock();
block.updateAt_(newAt);
}
});
this.updateAt_(true); this.updateAt_(true);
// Assign 'this' to a variable for use in the tooltip closure below. // Assign 'this' to a variable for use in the tooltip closure below.
const thisBlock = this; const thisBlock = this;
@@ -1012,15 +1014,15 @@ const TEXT_CHARAT_EXTENSION = function() {
}); });
}; };
Extensions.register('text_indexOf_tooltip', TEXT_INDEXOF_TOOLTIP_EXTENSION); Extensions.register('text_indexOf_tooltip', INDEXOF_TOOLTIP_EXTENSION);
Extensions.register('text_quotes', TEXT_QUOTES_EXTENSION); Extensions.register('text_quotes', QUOTES_EXTENSION);
Extensions.registerMutator( Extensions.registerMutator(
'text_join_mutator', TEXT_JOIN_MUTATOR_MIXIN, TEXT_JOIN_EXTENSION); 'text_join_mutator', JOIN_MUTATOR_MIXIN, JOIN_EXTENSION);
Extensions.registerMutator( Extensions.registerMutator(
'text_charAt_mutator', TEXT_CHARAT_MUTATOR_MIXIN, TEXT_CHARAT_EXTENSION); 'text_charAt_mutator', CHARAT_MUTATOR_MIXIN, CHARAT_EXTENSION);
// Register provided blocks. // Register provided blocks.
defineBlocks(blocks); defineBlocks(blocks);