建立自訂程序區塊

如要建立自訂程序區塊,您必須:

  1. 按照使用程序頁面的說明安裝 @blockly/block-shareable-procedures 外掛程式。
  2. 使用 JSON 序列化系統,詳情請參閱總覽頁面

將資料模型新增至工作區

程序定義和程序呼叫端都會封鎖備份資料模型,這個模型會定義程序的簽章 (名稱、參數和回傳)。這可以提高應用程式設計方式的彈性 (例如,您可以在一個工作區中定義程序,並在另一個工作區中參照)。

這表示您必須將程序資料模型新增至工作區,才能使區塊正常運作。有很多方法可以達成這個目標 (例如自訂 UI)。

為此,@blockly/block-shareable-procedures 透過擁有 process-definition 區塊,在執行個體化至工作區時動態建立備份資料模型。如要自行實作,請在 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)。

建立 UI 以修改程序模型的選項,包括使用變動器 (內建程序封鎖)、含有點擊處理常式的映像檔欄位、完全外部設為「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);