建立自訂對話框

對話框是一種彈出式 UI,看起來像漫畫中的對話框。它們有一個指向區塊的「尾」,以及包含任意 SVG 元素的「head」。

說明標題和尾部有標籤的泡泡

如果內建對話框不適用於您的用途,您可以將 Bubble 類別設為子類別,建立自訂對話框。

建立檢視畫面

對話框的檢視畫面是指位於泡泡的「頭」內部的所有 SVG 元素。這些元素會在對話框的建構函式內建立,且應為 this.contentContainer 元素的子項,以便在刪除圖示時自動清理這些元素。

Blockly.utils.dom 模組提供簡潔的介面,可將 svgs 執行個體化。

class MyBubble extends Blockly.bubbles.Bubble {
  // See the Blockly.bubbles.Bubble class for information about what these
  // parameters are.
  constructor(workspace, anchor, ownerRect) {
    super(workspace, anchor, ownerRect);

    this.text = Blockly.utils.dom.createSvgElement(
          Blockly.utils.Svg.TEXT,
          {'class': 'my-bubble-class'},
          this.contentContainer);
    const node = Blockly.utils.dom.createTextNode('some text');
    this.text.appendChild(node);
  }
}

設定大小

對話框的大小需要使用 setSize 設定,以便讓外框能正確圍住對話框的內容。請勿在建構期間及 UI 元素大小變更時進行設定。

constructor(workspace, anchor, ownerRect) {
  // Create the view elements... (see above)

  const bbox = this.text.getBBox();
  this.setSize(
    new Blockly.utils.Size(
      bbox.width + Blockly.bubbles.Bubble.BORDER_WIDTH * 2,
      bbox.height + Blockly.bubbles.Bubble.BORDER_WIDTH * 2,
    ),
    true
  );
}

丟棄泡泡

對話框在處理時應清除任何隨機元素或外部參照。根據預設,附加至 this.contentContainer 的所有內容都會遭到刪除,但您必須手動清理其他參照。請在 dispose 方法中完成這項操作。

dispose() {
  super.dispose();

  // Dispose of other references.
  this.myArbitraryReference.dispose();
}