创建自定义过程块

创建自定义过程块要求您执行以下操作:

  1. 按照使用过程页面中的说明安装 @blockly/block-shareable-procedures 插件。
  2. 使用 JSON 序列化系统,如概览页面中所述。

将数据模型添加到工作区

过程定义和过程调用方块都会引用后备数据模型,该数据模型会定义过程的签名(名称、参数和返回)。这样可以更灵活地设计应用(例如,您可以允许在一个工作区中定义过程,并在另一个工作区中引用过程)。

这意味着,您需要将过程数据模型添加到工作区,才能让您的块正常运行。您可以通过多种方式(例如自定义界面)实现这一目标。

@blockly/block-shareable-procedures 可以通过让过程定义块在实例化到工作区时动态创建其后备数据模型来实现此目的。如需自行实现此实现,您可以在 init 中创建模型并在 destroy 中将其删除。

import {ObservableProcedureModel} from '@blockly/block-shareable-procedures';

Blockly.Blocks['my_procedure_def'] = {
  init: function() {
    this.model = new ObservableProcedureModel('default name');
    this.workspace.getProcedureMap().add(model);
    // etc...
  }

  destroy: function() {
    // (Optionally) Destroy the model when the definition block is deleted.

    // Insertion markers reference the model of the original block.
    if (this.isInsertionMarker()) return;
    this.workpace.getProcedureMap().delete(model.getId());
  }
}

返回有关块的信息

过程定义和过程调用块需要实现 getProcedureModelisProcedureDefgetVarModels 方法。这些是 Blockly 代码用于获取有关过程块的信息的钩子。

Blockly.Blocks['my_procedure_def'] = {
  getProcedureModel() {
    return this.model;
  },

  isProcedureDef() {
    return true;
  },

  getVarModels() {
    // If your procedure references variables
    // then you should return those models here.
    return [];
  },
};

Blockly.Blocks['my_procedure_call'] = {
  getProcedureModel() {
    return this.model;
  },

  isProcedureDef() {
    return false;
  },

  getVarModels() {
    // If your procedure references variables
    // then you should return those models here.
    return [];
  },
};

有更新时触发重新渲染

您的过程定义和过程调用块需要实现 doProcedureUpdate 方法。这是数据模型调用的钩子,用于指示您的过程块自行重新渲染。

Blockly.Blocks['my_procedure_def'] = {
  doProcedureUpdate() {
    this.setFieldValue('NAME', this.model.getName());
    this.setFieldValue(
        'PARAMS',
        this.model.getParameters()
            .map((p) => p.getName())
            .join(','));
    this.setFieldValue(
        'RETURN', this.model.getReturnTypes().join(',');
  }
};

Blockly.Blocks['my_procedure_call'] = {
  doProcedureUpdate() {
    // Similar to the def block above...
  }
};

添加自定义序列化

过程块的序列化必须执行两项单独的操作。

  1. 从 JSON 加载时,您的块需要获取其后备数据模型的引用,因为块和模型是单独序列化的。
  2. 复制和粘贴过程块时,该块需要对其过程模型的整个状态进行序列化,以便能够复制它。

这两个操作都通过 saveExtraStateloadExtraState 进行处理。另请注意,自定义过程块仅在使用 JSON 序列化系统时才受支持,因此我们只需要定义 JSON 序列化钩子。

import {
    ObservableProcedureModel,
    ObservableParameterModel,
    isProcedureBlock
} from '@blockly/block-shareable-procedures';

Blockly.Blocks['my_procedure_def'] = {
  // When doFullSerialization is true, we should serialize the full state of
  // the model.
  saveExtraState(doFullSerialization) {
    const state = Object.create(null);
    state['procedureId']: this.model.getId();

    if (doFullSerialization) {
      state['name'] = this.model.getName();
      state['parameters'] = this.model.getParameters().map((p) => {
        return {name: p.getName(), p.getId()};
      });
      state['returnTypes'] = this.model.getReturnTypes();

      // Flag for deserialization.
      state['createNewModel'] = true;
    }

    return state;
  },

  loadExtraState(state) {
    const id = state['procedureId']
    const map = this.workspace.getProcedureMap();

    if (map.has(id) && !state['createNewModel']) {
      // Delete the existing model (created in init).
      map.delete(this.model.getId());
      // Grab a reference to the model we're supposed to reference.
      this.model = map.get(id);
      this.doProcedureUpdate();
      return;
    }

    // There is no existing procedure model (we are likely pasting), so
    // generate it from JSON.
    this.model
        .setName(state['name'])
        .setReturnTypes(state['returnTypes']);
    for (const [i, param] of state['parameters'].entries()) {
      this.model.insertParameter(
          i,
          new ObservableParameterModel(
              this.workspace, param['name'], param['id']));
    }
    this.doProcedureUpdate();
  },
};

Blockly.Blocks['my_procedure_call'] = {
  saveExtraState() {
    return {
      'procedureId': this.model.getId(),
    };
  },

  loadExtraState(state) {
    // Delete our existing model (created in init).
    this.workspace.getProcedureMap().delete(model.getId());
    // Grab a reference to the new model.
    this.model = this.workspace.getProcedureMap()
        .get(state['procedureId']);
    if (this.model) this.doProcedureUpdate();
  },

  // Handle pasting after the procedure definition has been deleted.
  onchange(event) {
    if (event.type === Blockly.Events.BLOCK_CREATE &&
        event.blockId === this.id) {
      if(!this.model) { // Our procedure definition doesn't exist =(
        this.dispose();
      }
    }
  }
};

(可选)修改过程模型

您还可以为用户提供修改手术模型的功能。调用 insertParameterdeleteParametersetReturnTypes 方法会自动触发块重新渲染(通过 doProcedureUpdate)。

用于创建界面来修改过程模型的选项包括:使用更改器(内置过程块使用)、带有点击处理程序的图片字段,以及完全位于 Blockly 之外的一些内容等。

将方块添加到工具箱

Blockly 的内置动态过程类别特定于 Blockly 的内置过程块。因此,为了能够访问数据块,您需要定义自己的自定义动态类别,并将其添加到工具箱中

const proceduresFlyoutCallback = function(workspace) {
  const blockList = [];
  blockList.push({
    'kind': 'block',
    'type': 'my_procedure_def',
  });
  for (const model of
        workspace.getProcedureMap().getProcedures()) {
    blockList.push({
      'kind': 'block',
      'type': 'my_procedure_call',
      'extraState': {
        'procedureId': model.getId(),
      },
    });
  }
  return blockList;
};

myWorkspace.registerToolboxCategoryCallback(
    'MY_PROCEDURES', proceduresFlyoutCallback);