內建圖示會使用彈出式對話框的 UI,顯示額外資訊或編輯器。自訂圖示也可以複製此行為,以維持一致的外觀和風格。
如果圖示應顯示對話框,您必須實作 IHasBubble
介面。
顯示或隱藏泡泡
使用對話框的圖示應實作 setBubbleVisible
方法來顯示或隱藏對話框。
// Implement the setBubbleVisible method of the IHasBubble interface.
setBubbleVisible(visible) {
// State is already correct.
if (!!this.myBubble === visible) return;
if (visible) {
this.myBubble = new MyBubble(this.getAnchorLocation(), this.getOwnerRect());
} else {
this.myBubble?.dispose();
}
}
// Implement helper methods for getting the anchor location and bounds.
// Returns the location of the middle of this icon in workspace coordinates.
getAnchorLocation() {
const size = this.getSize();
const midIcon = new Blockly.utils.Coordinate(size.width / 2, size.height / 2);
return Blockly.utils.Coordinate.sum(this.workspaceLocation, midIcon);
}
// Returns the rect the bubble should avoid overlapping, i.e. the block this
// icon is appended to.
getOwnerRect() {
const bbox = this.sourceBlock.getSvgRoot().getBBox();
return new Blockly.utils.Rect(
bbox.y, bbox.y + bbox.height, bbox.x, bbox.x + bbox.width);
}
處理拖曳區塊
當圖示變更位置時,對話框不會自動隨著位置移動。你需要更新或隱藏泡泡的位置。您可以在 IIcon
介面的 onLocationChange
方法中執行這項操作。
onLocationChange(blockOrigin) {
super.onLocationChange(blockOrigin);
this.myBubble?.setAnchorLocation(this.getAnchorLocation());
}
傳回泡泡的顯示設定
IHasBubble
介面也要求您實作 isBubbleVisible
方法,以傳回對話框是否顯示。
isBubbleVisible() {
return !!this.myBubble;
}