mirror of
https://github.com/google/blockly.git
synced 2026-01-06 08:30:13 +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>
1025 lines
35 KiB
TypeScript
1025 lines
35 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2012 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview XML reader and writer.
|
|
*/
|
|
|
|
/**
|
|
* XML reader and writer.
|
|
* @namespace Blockly.Xml
|
|
*/
|
|
import * as goog from '../closure/goog/goog.js';
|
|
goog.declareModuleId('Blockly.Xml');
|
|
|
|
// Unused import preserved for side-effects. Remove if unneeded.
|
|
// import './comment.js';
|
|
// Unused import preserved for side-effects. Remove if unneeded.
|
|
// import './variables.js';
|
|
// Unused import preserved for side-effects. Remove if unneeded.
|
|
// import './workspace_comment.js';
|
|
// Unused import preserved for side-effects. Remove if unneeded.
|
|
// import './workspace_comment_svg.js';
|
|
|
|
import type {Block} from './block.js';
|
|
import type {BlockSvg} from './block_svg.js';
|
|
import type {Connection} from './connection.js';
|
|
import * as eventUtils from './events/utils.js';
|
|
import type {Field} from './field.js';
|
|
import {inputTypes} from './input_types.js';
|
|
import * as dom from './utils/dom.js';
|
|
import {Size} from './utils/size.js';
|
|
import * as utilsXml from './utils/xml.js';
|
|
import type {VariableModel} from './variable_model.js';
|
|
import * as Variables from './variables.js';
|
|
import type {Workspace} from './workspace.js';
|
|
import {WorkspaceComment} from './workspace_comment.js';
|
|
import {WorkspaceCommentSvg} from './workspace_comment_svg.js';
|
|
import type {WorkspaceSvg} from './workspace_svg.js';
|
|
|
|
|
|
/**
|
|
* Encode a block tree as XML.
|
|
* @param workspace The workspace containing blocks.
|
|
* @param opt_noId True if the encoder should skip the block IDs.
|
|
* @return XML DOM element.
|
|
* @alias Blockly.Xml.workspaceToDom
|
|
*/
|
|
export function workspaceToDom(
|
|
workspace: Workspace, opt_noId?: boolean): Element {
|
|
const treeXml = utilsXml.createElement('xml');
|
|
const variablesElement =
|
|
variablesToDom(Variables.allUsedVarModels(workspace));
|
|
if (variablesElement.hasChildNodes()) {
|
|
treeXml.appendChild(variablesElement);
|
|
}
|
|
const comments = workspace.getTopComments(true);
|
|
for (let i = 0; i < comments.length; i++) {
|
|
const comment = comments[i];
|
|
treeXml.appendChild(comment.toXmlWithXY(opt_noId));
|
|
}
|
|
const blocks = workspace.getTopBlocks(true);
|
|
for (let i = 0; i < blocks.length; i++) {
|
|
const block = blocks[i];
|
|
treeXml.appendChild(blockToDomWithXY(block, opt_noId));
|
|
}
|
|
return treeXml;
|
|
}
|
|
|
|
/**
|
|
* Encode a list of variables as XML.
|
|
* @param variableList List of all variable models.
|
|
* @return Tree of XML elements.
|
|
* @alias Blockly.Xml.variablesToDom
|
|
*/
|
|
export function variablesToDom(variableList: VariableModel[]): Element {
|
|
const variables = utilsXml.createElement('variables');
|
|
for (let i = 0; i < variableList.length; i++) {
|
|
const variable = variableList[i];
|
|
const element = utilsXml.createElement('variable');
|
|
element.appendChild(utilsXml.createTextNode(variable.name));
|
|
if (variable.type) {
|
|
element.setAttribute('type', variable.type);
|
|
}
|
|
element.id = variable.getId();
|
|
variables.appendChild(element);
|
|
}
|
|
return variables;
|
|
}
|
|
|
|
/**
|
|
* Encode a block subtree as XML with XY coordinates.
|
|
* @param block The root block to encode.
|
|
* @param opt_noId True if the encoder should skip the block ID.
|
|
* @return Tree of XML elements or an empty document fragment if the block was
|
|
* an insertion marker.
|
|
* @alias Blockly.Xml.blockToDomWithXY
|
|
*/
|
|
export function blockToDomWithXY(block: Block, opt_noId?: boolean): Element|
|
|
DocumentFragment {
|
|
if (block.isInsertionMarker()) { // Skip over insertion markers.
|
|
block = block.getChildren(false)[0];
|
|
if (!block) {
|
|
// Disappears when appended.
|
|
return new DocumentFragment();
|
|
}
|
|
}
|
|
|
|
let width = 0; // Not used in LTR.
|
|
if (block.workspace?.RTL) {
|
|
width = block.workspace.getWidth();
|
|
}
|
|
|
|
const element = blockToDom(block, opt_noId);
|
|
const xy = block.getRelativeToSurfaceXY();
|
|
// AnyDuringMigration because: Property 'setAttribute' does not exist on type
|
|
// 'Element | DocumentFragment'.
|
|
(element as AnyDuringMigration)
|
|
.setAttribute(
|
|
'x', Math.round(block.workspace?.RTL ? width - xy.x : xy.x));
|
|
// AnyDuringMigration because: Property 'setAttribute' does not exist on type
|
|
// 'Element | DocumentFragment'.
|
|
(element as AnyDuringMigration).setAttribute('y', Math.round(xy.y));
|
|
return element;
|
|
}
|
|
|
|
/**
|
|
* Encode a field as XML.
|
|
* @param field The field to encode.
|
|
* @return XML element, or null if the field did not need to be serialized.
|
|
*/
|
|
function fieldToDom(field: Field): Element|null {
|
|
if (field.isSerializable()) {
|
|
const container = utilsXml.createElement('field');
|
|
container.setAttribute('name', field.name || '');
|
|
return field.toXml(container);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Encode all of a block's fields as XML and attach them to the given tree of
|
|
* XML elements.
|
|
* @param block A block with fields to be encoded.
|
|
* @param element The XML element to which the field DOM should be attached.
|
|
*/
|
|
function allFieldsToDom(block: Block, element: Element) {
|
|
for (let i = 0; i < block.inputList.length; i++) {
|
|
const input = block.inputList[i];
|
|
for (let j = 0; j < input.fieldRow.length; j++) {
|
|
const field = input.fieldRow[j];
|
|
const fieldDom = fieldToDom(field);
|
|
if (fieldDom) {
|
|
element.appendChild(fieldDom);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Encode a block subtree as XML.
|
|
* @param block The root block to encode.
|
|
* @param opt_noId True if the encoder should skip the block ID.
|
|
* @return Tree of XML elements or an empty document fragment if the block was
|
|
* an insertion marker.
|
|
* @alias Blockly.Xml.blockToDom
|
|
*/
|
|
export function blockToDom(block: Block, opt_noId?: boolean): Element|
|
|
DocumentFragment {
|
|
// Skip over insertion markers.
|
|
if (block.isInsertionMarker()) {
|
|
const child = block.getChildren(false)[0];
|
|
if (child) {
|
|
return blockToDom(child);
|
|
} else {
|
|
// Disappears when appended.
|
|
return new DocumentFragment();
|
|
}
|
|
}
|
|
|
|
const element = utilsXml.createElement(block.isShadow() ? 'shadow' : 'block');
|
|
element.setAttribute('type', block.type);
|
|
if (!opt_noId) {
|
|
// It's important to use setAttribute here otherwise IE11 won't serialize
|
|
// the block's ID when domToText is called.
|
|
element.setAttribute('id', block.id);
|
|
}
|
|
if (block.mutationToDom) {
|
|
// Custom data for an advanced block.
|
|
const mutation = block.mutationToDom();
|
|
if (mutation && (mutation.hasChildNodes() || mutation.hasAttributes())) {
|
|
element.appendChild(mutation);
|
|
}
|
|
}
|
|
|
|
allFieldsToDom(block, element);
|
|
|
|
const commentText = block.getCommentText();
|
|
if (commentText) {
|
|
const size = block.commentModel.size;
|
|
const pinned = block.commentModel.pinned;
|
|
|
|
const commentElement = utilsXml.createElement('comment');
|
|
commentElement.appendChild(utilsXml.createTextNode(commentText));
|
|
// AnyDuringMigration because: Argument of type 'boolean' is not assignable
|
|
// to parameter of type 'string'.
|
|
commentElement.setAttribute('pinned', pinned as AnyDuringMigration);
|
|
// AnyDuringMigration because: Argument of type 'number' is not assignable
|
|
// to parameter of type 'string'.
|
|
commentElement.setAttribute('h', size.height as AnyDuringMigration);
|
|
// AnyDuringMigration because: Argument of type 'number' is not assignable
|
|
// to parameter of type 'string'.
|
|
commentElement.setAttribute('w', size.width as AnyDuringMigration);
|
|
|
|
element.appendChild(commentElement);
|
|
}
|
|
|
|
if (block.data) {
|
|
const dataElement = utilsXml.createElement('data');
|
|
dataElement.appendChild(utilsXml.createTextNode(block.data));
|
|
element.appendChild(dataElement);
|
|
}
|
|
|
|
for (let i = 0; i < block.inputList.length; i++) {
|
|
const input = block.inputList[i];
|
|
let container: Element;
|
|
let empty = true;
|
|
if (input.type === inputTypes.DUMMY) {
|
|
continue;
|
|
} else {
|
|
const childBlock = input.connection!.targetBlock();
|
|
if (input.type === inputTypes.VALUE) {
|
|
container = utilsXml.createElement('value');
|
|
} else if (input.type === inputTypes.STATEMENT) {
|
|
container = utilsXml.createElement('statement');
|
|
}
|
|
const childShadow = input.connection!.getShadowDom();
|
|
if (childShadow && (!childBlock || !childBlock.isShadow())) {
|
|
container!.appendChild(cloneShadow(childShadow, opt_noId));
|
|
}
|
|
if (childBlock) {
|
|
const childElem = blockToDom(childBlock, opt_noId);
|
|
if (childElem.nodeType === dom.NodeType.ELEMENT_NODE) {
|
|
container!.appendChild(childElem);
|
|
empty = false;
|
|
}
|
|
}
|
|
}
|
|
container!.setAttribute('name', input.name);
|
|
if (!empty) {
|
|
element.appendChild(container!);
|
|
}
|
|
}
|
|
if (block.inputsInline !== undefined &&
|
|
block.inputsInline !== block.inputsInlineDefault) {
|
|
element.setAttribute('inline', block.inputsInline.toString());
|
|
}
|
|
if (block.isCollapsed()) {
|
|
element.setAttribute('collapsed', 'true');
|
|
}
|
|
if (!block.isEnabled()) {
|
|
element.setAttribute('disabled', 'true');
|
|
}
|
|
if (!block.isDeletable() && !block.isShadow()) {
|
|
element.setAttribute('deletable', 'false');
|
|
}
|
|
if (!block.isMovable() && !block.isShadow()) {
|
|
element.setAttribute('movable', 'false');
|
|
}
|
|
if (!block.isEditable()) {
|
|
element.setAttribute('editable', 'false');
|
|
}
|
|
|
|
const nextBlock = block.getNextBlock();
|
|
let container: Element;
|
|
if (nextBlock) {
|
|
const nextElem = blockToDom(nextBlock, opt_noId);
|
|
if (nextElem.nodeType === dom.NodeType.ELEMENT_NODE) {
|
|
container = utilsXml.createElement('next');
|
|
container.appendChild(nextElem);
|
|
element.appendChild(container);
|
|
}
|
|
}
|
|
const nextShadow =
|
|
block.nextConnection && block.nextConnection.getShadowDom();
|
|
if (nextShadow && (!nextBlock || !nextBlock.isShadow())) {
|
|
container!.appendChild(cloneShadow(nextShadow, opt_noId));
|
|
}
|
|
|
|
return element;
|
|
}
|
|
|
|
/**
|
|
* Deeply clone the shadow's DOM so that changes don't back-wash to the block.
|
|
* @param shadow A tree of XML elements.
|
|
* @param opt_noId True if the encoder should skip the block ID.
|
|
* @return A tree of XML elements.
|
|
*/
|
|
function cloneShadow(shadow: Element, opt_noId?: boolean): Element {
|
|
shadow = shadow.cloneNode(true) as Element;
|
|
// Walk the tree looking for whitespace. Don't prune whitespace in a tag.
|
|
let node: Node|null = shadow;
|
|
let textNode;
|
|
while (node) {
|
|
if (opt_noId && node.nodeName === 'shadow') {
|
|
// Strip off IDs from shadow blocks. There should never be a 'block' as
|
|
// a child of a 'shadow', so no need to check that.
|
|
(node as Element).removeAttribute('id');
|
|
}
|
|
if (node.firstChild) {
|
|
node = node.firstChild;
|
|
} else {
|
|
while (node && !node.nextSibling) {
|
|
textNode = node;
|
|
node = node.parentNode;
|
|
if (textNode.nodeType === dom.NodeType.TEXT_NODE &&
|
|
(textNode as Text).data.trim() === '' &&
|
|
node?.firstChild !== textNode) {
|
|
// Prune whitespace after a tag.
|
|
dom.removeNode(textNode);
|
|
}
|
|
}
|
|
if (node) {
|
|
textNode = node;
|
|
node = node.nextSibling;
|
|
if (textNode.nodeType === dom.NodeType.TEXT_NODE &&
|
|
(textNode as Text).data.trim() === '') {
|
|
// Prune whitespace before a tag.
|
|
dom.removeNode(textNode);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return shadow;
|
|
}
|
|
|
|
/**
|
|
* Converts a DOM structure into plain text.
|
|
* Currently the text format is fairly ugly: all one line with no whitespace,
|
|
* unless the DOM itself has whitespace built-in.
|
|
* @param dom A tree of XML nodes.
|
|
* @return Text representation.
|
|
* @alias Blockly.Xml.domToText
|
|
*/
|
|
export function domToText(dom: Node): string {
|
|
const text = utilsXml.domToText(dom);
|
|
// Unpack self-closing tags. These tags fail when embedded in HTML.
|
|
// <block name="foo"/> -> <block name="foo"></block>
|
|
return text.replace(/<(\w+)([^<]*)\/>/g, '<$1$2></$1>');
|
|
}
|
|
|
|
/**
|
|
* Converts a DOM structure into properly indented text.
|
|
* @param dom A tree of XML elements.
|
|
* @return Text representation.
|
|
* @alias Blockly.Xml.domToPrettyText
|
|
*/
|
|
export function domToPrettyText(dom: Node): string {
|
|
// This function is not guaranteed to be correct for all XML.
|
|
// But it handles the XML that Blockly generates.
|
|
const blob = domToText(dom);
|
|
// Place every open and close tag on its own line.
|
|
const lines = blob.split('<');
|
|
// Indent every line.
|
|
let indent = '';
|
|
for (let i = 1; i < lines.length; i++) {
|
|
const line = lines[i];
|
|
if (line[0] === '/') {
|
|
indent = indent.substring(2);
|
|
}
|
|
lines[i] = indent + '<' + line;
|
|
if (line[0] !== '/' && line.slice(-2) !== '/>') {
|
|
indent += ' ';
|
|
}
|
|
}
|
|
// Pull simple tags back together.
|
|
// E.g. <foo></foo>
|
|
let text = lines.join('\n');
|
|
text = text.replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g, '$1</$2>');
|
|
// Trim leading blank line.
|
|
return text.replace(/^\n/, '');
|
|
}
|
|
|
|
/**
|
|
* Converts an XML string into a DOM structure.
|
|
* @param text An XML string.
|
|
* @return A DOM object representing the singular child of the document element.
|
|
* @throws if the text doesn't parse.
|
|
* @alias Blockly.Xml.textToDom
|
|
*/
|
|
export function textToDom(text: string): Element {
|
|
const doc = utilsXml.textToDomDocument(text);
|
|
if (!doc || !doc.documentElement ||
|
|
doc.getElementsByTagName('parsererror').length) {
|
|
throw Error('textToDom was unable to parse: ' + text);
|
|
}
|
|
return doc.documentElement;
|
|
}
|
|
|
|
/**
|
|
* Clear the given workspace then decode an XML DOM and
|
|
* create blocks on the workspace.
|
|
* @param xml XML DOM.
|
|
* @param workspace The workspace.
|
|
* @return An array containing new block IDs.
|
|
* @alias Blockly.Xml.clearWorkspaceAndLoadFromXml
|
|
*/
|
|
export function clearWorkspaceAndLoadFromXml(
|
|
xml: Element, workspace: WorkspaceSvg): string[] {
|
|
workspace.setResizesEnabled(false);
|
|
workspace.clear();
|
|
// AnyDuringMigration because: Argument of type 'WorkspaceSvg' is not
|
|
// assignable to parameter of type 'Workspace'.
|
|
const blockIds = domToWorkspace(xml, workspace as AnyDuringMigration);
|
|
workspace.setResizesEnabled(true);
|
|
return blockIds;
|
|
}
|
|
|
|
/**
|
|
* Decode an XML DOM and create blocks on the workspace.
|
|
* @param xml XML DOM.
|
|
* @param workspace The workspace.
|
|
* @return An array containing new block IDs.
|
|
* @suppress {strictModuleDepCheck} Suppress module check while workspace
|
|
* comments are not bundled in.
|
|
* @alias Blockly.Xml.domToWorkspace
|
|
*/
|
|
export function domToWorkspace(xml: Element, workspace: Workspace): string[] {
|
|
let width = 0; // Not used in LTR.
|
|
if (workspace.RTL) {
|
|
width = workspace.getWidth();
|
|
}
|
|
const newBlockIds = []; // A list of block IDs added by this call.
|
|
dom.startTextWidthCache();
|
|
const existingGroup = eventUtils.getGroup();
|
|
if (!existingGroup) {
|
|
eventUtils.setGroup(true);
|
|
}
|
|
|
|
// Disable workspace resizes as an optimization.
|
|
// Assume it is rendered so we can check.
|
|
if ((workspace as WorkspaceSvg).setResizesEnabled) {
|
|
(workspace as WorkspaceSvg).setResizesEnabled(false);
|
|
}
|
|
let variablesFirst = true;
|
|
try {
|
|
for (let i = 0, xmlChild; xmlChild = xml.childNodes[i]; i++) {
|
|
const name = xmlChild.nodeName.toLowerCase();
|
|
const xmlChildElement = xmlChild as Element;
|
|
if (name === 'block' ||
|
|
name === 'shadow' && !eventUtils.getRecordUndo()) {
|
|
// Allow top-level shadow blocks if recordUndo is disabled since
|
|
// that means an undo is in progress. Such a block is expected
|
|
// to be moved to a nested destination in the next operation.
|
|
const block = domToBlock(xmlChildElement, workspace);
|
|
newBlockIds.push(block.id);
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
const blockX = xmlChildElement.hasAttribute('x') ?
|
|
parseInt(
|
|
xmlChildElement.getAttribute('x') as AnyDuringMigration, 10) :
|
|
10;
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
const blockY = xmlChildElement.hasAttribute('y') ?
|
|
parseInt(
|
|
xmlChildElement.getAttribute('y') as AnyDuringMigration, 10) :
|
|
10;
|
|
if (!isNaN(blockX) && !isNaN(blockY)) {
|
|
block.moveBy(workspace.RTL ? width - blockX : blockX, blockY);
|
|
}
|
|
variablesFirst = false;
|
|
} else if (name === 'shadow') {
|
|
throw TypeError('Shadow block cannot be a top-level block.');
|
|
} else if (name === 'comment') {
|
|
if (workspace.rendered) {
|
|
WorkspaceCommentSvg.fromXmlRendered(
|
|
xmlChildElement, workspace as WorkspaceSvg, width);
|
|
} else {
|
|
WorkspaceComment.fromXml(xmlChildElement, workspace);
|
|
}
|
|
} else if (name === 'variables') {
|
|
if (variablesFirst) {
|
|
domToVariables(xmlChildElement, workspace);
|
|
} else {
|
|
throw Error(
|
|
'\'variables\' tag must exist once before block and ' +
|
|
'shadow tag elements in the workspace XML, but it was found in ' +
|
|
'another location.');
|
|
}
|
|
variablesFirst = false;
|
|
}
|
|
}
|
|
} finally {
|
|
if (!existingGroup) {
|
|
eventUtils.setGroup(false);
|
|
}
|
|
dom.stopTextWidthCache();
|
|
}
|
|
// Re-enable workspace resizing.
|
|
if ((workspace as WorkspaceSvg).setResizesEnabled) {
|
|
(workspace as WorkspaceSvg).setResizesEnabled(true);
|
|
}
|
|
eventUtils.fire(new (eventUtils.get(eventUtils.FINISHED_LOADING))!
|
|
(workspace));
|
|
return newBlockIds;
|
|
}
|
|
|
|
/**
|
|
* Decode an XML DOM and create blocks on the workspace. Position the new
|
|
* blocks immediately below prior blocks, aligned by their starting edge.
|
|
* @param xml The XML DOM.
|
|
* @param workspace The workspace to add to.
|
|
* @return An array containing new block IDs.
|
|
* @alias Blockly.Xml.appendDomToWorkspace
|
|
*/
|
|
export function appendDomToWorkspace(
|
|
xml: Element, workspace: WorkspaceSvg): string[] {
|
|
// First check if we have a WorkspaceSvg, otherwise the blocks have no shape
|
|
// and the position does not matter.
|
|
// Assume it is rendered so we can check.
|
|
if (!(workspace as WorkspaceSvg).getBlocksBoundingBox) {
|
|
return domToWorkspace(xml, workspace);
|
|
}
|
|
|
|
const bbox = (workspace as WorkspaceSvg).getBlocksBoundingBox();
|
|
// Load the new blocks into the workspace and get the IDs of the new blocks.
|
|
const newBlockIds = domToWorkspace(xml, workspace);
|
|
if (bbox && bbox.top !== bbox.bottom) { // Check if any previous block.
|
|
let offsetY = 0; // Offset to add to y of the new block.
|
|
let offsetX = 0;
|
|
const farY = bbox.bottom; // Bottom position.
|
|
const topX = workspace.RTL ? bbox.right : bbox.left; // X of bounding box.
|
|
// Check position of the new blocks.
|
|
let newLeftX = Infinity; // X of top left corner.
|
|
let newRightX = -Infinity; // X of top right corner.
|
|
let newY = Infinity; // Y of top corner.
|
|
const ySeparation = 10;
|
|
for (let i = 0; i < newBlockIds.length; i++) {
|
|
const blockXY =
|
|
workspace.getBlockById(newBlockIds[i])!.getRelativeToSurfaceXY();
|
|
if (blockXY.y < newY) {
|
|
newY = blockXY.y;
|
|
}
|
|
if (blockXY.x < newLeftX) { // if we left align also on x
|
|
newLeftX = blockXY.x;
|
|
}
|
|
if (blockXY.x > newRightX) { // if we right align also on x
|
|
newRightX = blockXY.x;
|
|
}
|
|
}
|
|
offsetY = farY - newY + ySeparation;
|
|
offsetX = workspace.RTL ? topX - newRightX : topX - newLeftX;
|
|
for (let i = 0; i < newBlockIds.length; i++) {
|
|
const block = workspace.getBlockById(newBlockIds[i]);
|
|
block!.moveBy(offsetX, offsetY);
|
|
}
|
|
}
|
|
return newBlockIds;
|
|
}
|
|
|
|
/**
|
|
* Decode an XML block tag and create a block (and possibly sub blocks) on the
|
|
* workspace.
|
|
* @param xmlBlock XML block element.
|
|
* @param workspace The workspace.
|
|
* @return The root block created.
|
|
* @alias Blockly.Xml.domToBlock
|
|
*/
|
|
export function domToBlock(xmlBlock: Element, workspace: Workspace): Block {
|
|
// Create top-level block.
|
|
eventUtils.disable();
|
|
const variablesBeforeCreation = workspace.getAllVariables();
|
|
let topBlock;
|
|
try {
|
|
topBlock = domToBlockHeadless(xmlBlock, workspace);
|
|
// Generate list of all blocks.
|
|
if (workspace.rendered) {
|
|
const topBlockSvg = topBlock as BlockSvg;
|
|
const blocks = topBlock.getDescendants(false);
|
|
topBlockSvg.setConnectionTracking(false);
|
|
// Render each block.
|
|
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
(blocks[i] as BlockSvg).initSvg();
|
|
}
|
|
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
(blocks[i] as BlockSvg).render(false);
|
|
}
|
|
// Populating the connection database may be deferred until after the
|
|
// blocks have rendered.
|
|
setTimeout(function() {
|
|
if (!topBlockSvg.disposed) {
|
|
topBlockSvg.setConnectionTracking(true);
|
|
}
|
|
}, 1);
|
|
topBlockSvg.updateDisabled();
|
|
// Allow the scrollbars to resize and move based on the new contents.
|
|
// TODO(@picklesrus): #387. Remove when domToBlock avoids resizing.
|
|
(workspace as WorkspaceSvg).resizeContents();
|
|
} else {
|
|
const blocks = topBlock.getDescendants(false);
|
|
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
blocks[i].initModel();
|
|
}
|
|
}
|
|
} finally {
|
|
eventUtils.enable();
|
|
}
|
|
if (eventUtils.isEnabled()) {
|
|
// AnyDuringMigration because: Property 'get' does not exist on type
|
|
// '(name: string) => void'.
|
|
const newVariables =
|
|
Variables.getAddedVariables(workspace, variablesBeforeCreation);
|
|
// Fire a VarCreate event for each (if any) new variable created.
|
|
for (let i = 0; i < newVariables.length; i++) {
|
|
const thisVariable = newVariables[i];
|
|
eventUtils.fire(new (eventUtils.get(eventUtils.VAR_CREATE))!
|
|
(thisVariable));
|
|
}
|
|
// Block events come after var events, in case they refer to newly created
|
|
// variables.
|
|
eventUtils.fire(new (eventUtils.get(eventUtils.CREATE))!(topBlock));
|
|
}
|
|
return topBlock;
|
|
}
|
|
|
|
/**
|
|
* Decode an XML list of variables and add the variables to the workspace.
|
|
* @param xmlVariables List of XML variable elements.
|
|
* @param workspace The workspace to which the variable should be added.
|
|
* @alias Blockly.Xml.domToVariables
|
|
*/
|
|
export function domToVariables(xmlVariables: Element, workspace: Workspace) {
|
|
for (let i = 0; i < xmlVariables.children.length; i++) {
|
|
const xmlChild = xmlVariables.children[i];
|
|
const type = xmlChild.getAttribute('type');
|
|
const id = xmlChild.getAttribute('id');
|
|
const name = xmlChild.textContent;
|
|
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
workspace.createVariable(name as AnyDuringMigration, type, id);
|
|
}
|
|
}
|
|
|
|
/** A mapping of nodeName to node for child nodes of xmlBlock. */
|
|
interface childNodeTagMap {
|
|
mutation: Element[];
|
|
comment: Element[];
|
|
data: Element[];
|
|
field: Element[];
|
|
input: Element[];
|
|
next: Element[];
|
|
}
|
|
|
|
/**
|
|
* Creates a mapping of childNodes for each supported XML tag for the provided
|
|
* xmlBlock. Logs a warning for any encountered unsupported tags.
|
|
* @param xmlBlock XML block element.
|
|
* @return The childNode map from nodeName to node.
|
|
*/
|
|
function mapSupportedXmlTags(xmlBlock: Element): childNodeTagMap {
|
|
const childNodeMap = {
|
|
mutation: new Array<Element>(),
|
|
comment: new Array<Element>(),
|
|
data: new Array<Element>(),
|
|
field: new Array<Element>(),
|
|
input: new Array<Element>(),
|
|
next: new Array<Element>()
|
|
};
|
|
for (let i = 0; i < xmlBlock.children.length; i++) {
|
|
const xmlChild = xmlBlock.children[i];
|
|
if (xmlChild.nodeType === dom.NodeType.TEXT_NODE) {
|
|
// Ignore any text at the <block> level. It's all whitespace anyway.
|
|
continue;
|
|
}
|
|
switch (xmlChild.nodeName.toLowerCase()) {
|
|
case 'mutation':
|
|
childNodeMap.mutation.push(xmlChild);
|
|
break;
|
|
case 'comment':
|
|
childNodeMap.comment.push(xmlChild);
|
|
break;
|
|
case 'data':
|
|
childNodeMap.data.push(xmlChild);
|
|
break;
|
|
case 'title':
|
|
// Titles were renamed to field in December 2013.
|
|
// Fall through.
|
|
case 'field':
|
|
childNodeMap.field.push(xmlChild);
|
|
break;
|
|
case 'value':
|
|
case 'statement':
|
|
childNodeMap.input.push(xmlChild);
|
|
break;
|
|
case 'next':
|
|
childNodeMap.next.push(xmlChild);
|
|
break;
|
|
default:
|
|
// Unknown tag; ignore. Same principle as HTML parsers.
|
|
console.warn('Ignoring unknown tag: ' + xmlChild.nodeName);
|
|
}
|
|
}
|
|
return childNodeMap;
|
|
}
|
|
|
|
/**
|
|
* Applies mutation tag child nodes to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param block The block to apply the child nodes on.
|
|
* @return True if mutation may have added some elements that need
|
|
* initialization (requiring initSvg call).
|
|
*/
|
|
function applyMutationTagNodes(xmlChildren: Element[], block: Block): boolean {
|
|
let shouldCallInitSvg = false;
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
// Custom data for an advanced block.
|
|
if (block.domToMutation) {
|
|
block.domToMutation(xmlChild);
|
|
if ((block as BlockSvg).initSvg) {
|
|
// Mutation may have added some elements that need initializing.
|
|
shouldCallInitSvg = true;
|
|
}
|
|
}
|
|
}
|
|
return shouldCallInitSvg;
|
|
}
|
|
|
|
/**
|
|
* Applies comment tag child nodes to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param block The block to apply the child nodes on.
|
|
*/
|
|
function applyCommentTagNodes(xmlChildren: Element[], block: Block) {
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
const text = xmlChild.textContent;
|
|
const pinned = xmlChild.getAttribute('pinned') === 'true';
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
const width =
|
|
parseInt(xmlChild.getAttribute('w') as AnyDuringMigration, 10);
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
const height =
|
|
parseInt(xmlChild.getAttribute('h') as AnyDuringMigration, 10);
|
|
|
|
block.setCommentText(text);
|
|
block.commentModel.pinned = pinned;
|
|
if (!isNaN(width) && !isNaN(height)) {
|
|
block.commentModel.size = new Size(width, height);
|
|
}
|
|
|
|
if (pinned && (block as BlockSvg).getCommentIcon && !block.isInFlyout) {
|
|
const blockSvg = block as BlockSvg;
|
|
setTimeout(function() {
|
|
blockSvg.getCommentIcon()!.setVisible(true);
|
|
}, 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Applies data tag child nodes to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param block The block to apply the child nodes on.
|
|
*/
|
|
function applyDataTagNodes(xmlChildren: Element[], block: Block) {
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
block.data = xmlChild.textContent;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Applies field tag child nodes to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param block The block to apply the child nodes on.
|
|
*/
|
|
function applyFieldTagNodes(xmlChildren: Element[], block: Block) {
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
const nodeName = xmlChild.getAttribute('name');
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
domToField(block, nodeName as AnyDuringMigration, xmlChild);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Finds any enclosed blocks or shadows within this XML node.
|
|
* @param xmlNode The XML node to extract child block info from.
|
|
* @return Any found child block.
|
|
*/
|
|
function findChildBlocks(xmlNode: Element):
|
|
{childBlockElement: Element|null, childShadowElement: Element|null} {
|
|
const childBlockInfo = {childBlockElement: null, childShadowElement: null};
|
|
for (let i = 0; i < xmlNode.childNodes.length; i++) {
|
|
const xmlChild = xmlNode.childNodes[i];
|
|
if (xmlChild.nodeType === dom.NodeType.ELEMENT_NODE) {
|
|
if (xmlChild.nodeName.toLowerCase() === 'block') {
|
|
// AnyDuringMigration because: Type 'Element' is not assignable to type
|
|
// 'null'.
|
|
childBlockInfo.childBlockElement =
|
|
xmlChild as Element as AnyDuringMigration;
|
|
} else if (xmlChild.nodeName.toLowerCase() === 'shadow') {
|
|
// AnyDuringMigration because: Type 'Element' is not assignable to type
|
|
// 'null'.
|
|
childBlockInfo.childShadowElement =
|
|
xmlChild as Element as AnyDuringMigration;
|
|
}
|
|
}
|
|
}
|
|
return childBlockInfo;
|
|
}
|
|
/**
|
|
* Applies input child nodes (value or statement) to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param workspace The workspace containing the given block.
|
|
* @param block The block to apply the child nodes on.
|
|
* @param prototypeName The prototype name of the block.
|
|
*/
|
|
function applyInputTagNodes(
|
|
xmlChildren: Element[], workspace: Workspace, block: Block,
|
|
prototypeName: string) {
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
const nodeName = xmlChild.getAttribute('name');
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string'.
|
|
const input = block.getInput(nodeName as AnyDuringMigration);
|
|
if (!input) {
|
|
console.warn(
|
|
'Ignoring non-existent input ' + nodeName + ' in block ' +
|
|
prototypeName);
|
|
break;
|
|
}
|
|
const childBlockInfo = findChildBlocks(xmlChild);
|
|
if (childBlockInfo.childBlockElement) {
|
|
if (!input.connection) {
|
|
throw TypeError('Input connection does not exist.');
|
|
}
|
|
domToBlockHeadless(
|
|
childBlockInfo.childBlockElement, workspace, input.connection, false);
|
|
}
|
|
// Set shadow after so we don't create a shadow we delete immediately.
|
|
if (childBlockInfo.childShadowElement) {
|
|
input.connection?.setShadowDom(childBlockInfo.childShadowElement);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Applies next child nodes to the given block.
|
|
* @param xmlChildren Child nodes.
|
|
* @param workspace The workspace containing the given block.
|
|
* @param block The block to apply the child nodes on.
|
|
*/
|
|
function applyNextTagNodes(
|
|
xmlChildren: Element[], workspace: Workspace, block: Block) {
|
|
for (let i = 0; i < xmlChildren.length; i++) {
|
|
const xmlChild = xmlChildren[i];
|
|
const childBlockInfo = findChildBlocks(xmlChild);
|
|
if (childBlockInfo.childBlockElement) {
|
|
if (!block.nextConnection) {
|
|
throw TypeError('Next statement does not exist.');
|
|
}
|
|
// If there is more than one XML 'next' tag.
|
|
if (block.nextConnection.isConnected()) {
|
|
throw TypeError('Next statement is already connected.');
|
|
}
|
|
// Create child block.
|
|
domToBlockHeadless(
|
|
childBlockInfo.childBlockElement, workspace, block.nextConnection,
|
|
true);
|
|
}
|
|
// Set shadow after so we don't create a shadow we delete immediately.
|
|
if (childBlockInfo.childShadowElement && block.nextConnection) {
|
|
block.nextConnection.setShadowDom(childBlockInfo.childShadowElement);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Decode an XML block tag and create a block (and possibly sub blocks) on the
|
|
* workspace.
|
|
* @param xmlBlock XML block element.
|
|
* @param workspace The workspace.
|
|
* @param parentConnection The parent connection to to connect this block to
|
|
* after instantiating.
|
|
* @param connectedToParentNext Whether the provided parent connection is a next
|
|
* connection, rather than output or statement.
|
|
* @return The root block created.
|
|
*/
|
|
function domToBlockHeadless(
|
|
xmlBlock: Element, workspace: Workspace, parentConnection?: Connection,
|
|
connectedToParentNext?: boolean): Block {
|
|
let block = null;
|
|
const prototypeName = xmlBlock.getAttribute('type');
|
|
if (!prototypeName) {
|
|
throw TypeError('Block type unspecified: ' + xmlBlock.outerHTML);
|
|
}
|
|
const id = xmlBlock.getAttribute('id');
|
|
// AnyDuringMigration because: Argument of type 'string | null' is not
|
|
// assignable to parameter of type 'string | undefined'.
|
|
block = workspace.newBlock(prototypeName, id as AnyDuringMigration);
|
|
|
|
// Preprocess childNodes so tags can be processed in a consistent order.
|
|
const xmlChildNameMap = mapSupportedXmlTags(xmlBlock);
|
|
|
|
const shouldCallInitSvg =
|
|
applyMutationTagNodes(xmlChildNameMap.mutation, block);
|
|
applyCommentTagNodes(xmlChildNameMap.comment, block);
|
|
applyDataTagNodes(xmlChildNameMap.data, block);
|
|
|
|
// Connect parent after processing mutation and before setting fields.
|
|
if (parentConnection) {
|
|
if (connectedToParentNext) {
|
|
if (block.previousConnection) {
|
|
parentConnection.connect(block.previousConnection);
|
|
} else {
|
|
throw TypeError('Next block does not have previous statement.');
|
|
}
|
|
} else {
|
|
if (block.outputConnection) {
|
|
parentConnection.connect(block.outputConnection);
|
|
} else if (block.previousConnection) {
|
|
parentConnection.connect(block.previousConnection);
|
|
} else {
|
|
throw TypeError(
|
|
'Child block does not have output or previous statement.');
|
|
}
|
|
}
|
|
}
|
|
|
|
applyFieldTagNodes(xmlChildNameMap.field, block);
|
|
applyInputTagNodes(xmlChildNameMap.input, workspace, block, prototypeName);
|
|
applyNextTagNodes(xmlChildNameMap.next, workspace, block);
|
|
|
|
if (shouldCallInitSvg) {
|
|
// This shouldn't even be called here
|
|
// (ref: https://github.com/google/blockly/pull/4296#issuecomment-884226021
|
|
// But the XML serializer/deserializer is iceboxed so I'm not going to fix
|
|
// it.
|
|
(block as BlockSvg).initSvg();
|
|
}
|
|
|
|
const inline = xmlBlock.getAttribute('inline');
|
|
if (inline) {
|
|
block.setInputsInline(inline === 'true');
|
|
}
|
|
const disabled = xmlBlock.getAttribute('disabled');
|
|
if (disabled) {
|
|
block.setEnabled(disabled !== 'true' && disabled !== 'disabled');
|
|
}
|
|
const deletable = xmlBlock.getAttribute('deletable');
|
|
if (deletable) {
|
|
block.setDeletable(deletable === 'true');
|
|
}
|
|
const movable = xmlBlock.getAttribute('movable');
|
|
if (movable) {
|
|
block.setMovable(movable === 'true');
|
|
}
|
|
const editable = xmlBlock.getAttribute('editable');
|
|
if (editable) {
|
|
block.setEditable(editable === 'true');
|
|
}
|
|
const collapsed = xmlBlock.getAttribute('collapsed');
|
|
if (collapsed) {
|
|
block.setCollapsed(collapsed === 'true');
|
|
}
|
|
if (xmlBlock.nodeName.toLowerCase() === 'shadow') {
|
|
// Ensure all children are also shadows.
|
|
const children = block.getChildren(false);
|
|
for (let i = 0; i < children.length; i++) {
|
|
const child = children[i];
|
|
if (!child.isShadow()) {
|
|
throw TypeError('Shadow block not allowed non-shadow child.');
|
|
}
|
|
}
|
|
// Ensure this block doesn't have any variable inputs.
|
|
if (block.getVarModels().length) {
|
|
throw TypeError('Shadow blocks cannot have variable references.');
|
|
}
|
|
block.setShadow(true);
|
|
}
|
|
return block;
|
|
}
|
|
|
|
/**
|
|
* Decode an XML field tag and set the value of that field on the given block.
|
|
* @param block The block that is currently being deserialized.
|
|
* @param fieldName The name of the field on the block.
|
|
* @param xml The field tag to decode.
|
|
*/
|
|
function domToField(block: Block, fieldName: string, xml: Element) {
|
|
const field = block.getField(fieldName);
|
|
if (!field) {
|
|
console.warn(
|
|
'Ignoring non-existent field ' + fieldName + ' in block ' + block.type);
|
|
return;
|
|
}
|
|
field.fromXml(xml);
|
|
}
|
|
|
|
/**
|
|
* Remove any 'next' block (statements in a stack).
|
|
* @param xmlBlock XML block element or an empty DocumentFragment if the block
|
|
* was an insertion marker.
|
|
* @alias Blockly.Xml.deleteNext
|
|
*/
|
|
export function deleteNext(xmlBlock: Element|DocumentFragment) {
|
|
for (let i = 0; i < xmlBlock.childNodes.length; i++) {
|
|
const child = xmlBlock.childNodes[i];
|
|
if (child.nodeName.toLowerCase() === 'next') {
|
|
xmlBlock.removeChild(child);
|
|
break;
|
|
}
|
|
}
|
|
}
|