使用带有图标的弹出式气泡

内置图标使用弹出式气泡样式的界面显示额外信息或编辑器。自定义图标也可以复制此行为,以保持一致的外观和风格。

如果图标应显示一个气泡,您需要实现 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;
}