Override built-in icons

Blockly has three kinds of built-in icons: comments, warnings, and mutators.

Comment icons are overridable. This means you can tell Blockly to instantiate your own comment icon class when you call methods like myBlock.setCommentText(). You may want to do this if, for example, you want the comment's pop-up bubble to look different.

A block with the comment icon highlighted

Warning and mutator icons are not overridable.

Comment icon

To override the comment icon, you need to create a custom icon that implements the ICommentIcon interface, and then register it.

Basic implementation

Before adding comment-specific logic, complete the basic implementation of your custom icon.

Type

The getType method must return the comment icon IconType.

class MyCommentIcon extends Blockly.icons.Icon {
  getType() {
    return Blockly.icons.IconType.COMMENT;
  }
}

Text

The ICommentIcon interface requires that the comment has text. The getText method must return the text of the comment. The setText method must set the text of the comment and update any visuals.

getText() {
  return this.text;
}

setText(text) {
  this.text = text;
  this.myRenderMethod();
}

Bubble

Your custom comment icon must implement the IHasBubble interface to support serialization. Even if your icon doesn't technically have a bubble, you should store the visibility information on your class so that the saved state is maintained. Otherwise you'll lose information from the user if you load a save that includes whether the comment was open or not.

bubbleIsVisible() {
  return this.bubbleVisible;
}

setBubbleVisible(visible: boolean) {
  this.bubbleVisible = visible;
}

For more information about bubbles, see Using pop-up bubbles.

The ICommentIcon interface also requires a getBubbleSize method that returns a size, and a setBubbleSize that sets it. The same reasoning from earlier of saving state even if your icon doesn't technically have a bubble applies here as well.

getBubbleSize() {
  return this.bubbleSize;
}

setBubbleSize(size) {
  this.bubbleSize = size;
  this.myRenderMethod();
}

Save and load

Your custom comment icon must implement the ISerializable interface. The state should conform to the CommentState interface.

saveState() {
  return {
    text: this.text,
    pinned: this.bubbleVisible,
    height: this.bubbleSize.height,
    width: this.bubbleSize.width,
  }
}

loadState(state) {
  this.setText(state.text);
  this.setBubbleVisible(state.pinned);
  this.setBubbleSize(new Blockly.utils.Size(state.width, state.height));
}

For more information about icon serialization see Save and load icons.

Registration

Finally, you need to register your icon so that Blockly can instantiate it. Be sure to use the IconTypes.COMMENT type.

Blockly.icons.registry.register(Blockly.icons.IconType.COMMENT, myCommentIcon);