你可以覆寫內建的留言圖示。舉例來說,您可能希望留言的彈出式泡泡看起來不一樣。
如要覆寫註解圖示,請擴充 CommentIcon
、覆寫 ICommentIcon
中的所選方法,然後註冊新圖示。
Extend CommentIcon
首先,請延長 CommentIcon
。
class MyCommentIcon extends Blockly.icons.CommentIcon {
constructor(sourceBlock) {
super(sourceBlock);
}
}
覆寫 ICommentIcon 和 Icon 中的方法
如要自訂圖示,您可以覆寫 ICommentIcon
中的方法 (詳情請見下節) 和 Blockly.icons.Icon
(詳情請見「建立自訂圖示」)。請勿覆寫 getType
,該方法必須傳回 Blockly.icons.IconType.COMMENT
。
文字
ICommentIcon
介面要求註解必須包含文字。
getText
方法必須傳回留言文字。setText
方法必須設定留言文字,並更新所有視覺元素。
getText() {
return this.text;
}
setText(text) {
this.text = text;
this.myRenderMethod();
}
泡泡
自訂留言圖示必須實作 IHasBubble
介面,才能支援序列化。即使圖示在技術上沒有泡泡,您也應將顯示資訊儲存在類別中,以便維持儲存的狀態。否則,如果您載入的儲存檔包含留言是否開啟的資訊,就會遺失使用者的資訊。
bubbleIsVisible() {
return this.bubbleVisible;
}
setBubbleVisible(visible: boolean) {
this.bubbleVisible = visible;
}
如要進一步瞭解泡泡,請參閱「使用彈出式泡泡」。
ICommentIcon
介面需要 getBubbleSize
方法 (會傳回大小) 和 setBubbleSize
方法 (會設定大小)。即使圖示在技術上沒有泡泡,也應儲存狀態,這與先前的理由相同。
getBubbleSize() {
return this.bubbleSize;
}
setBubbleSize(size) {
this.bubbleSize = size;
this.myRenderMethod();
}
ICommentIcon
也需要 getBubbleLocation
和 setBubbleLocation
方法,用來取得及設定工作區中泡泡的位置。
setBubbleLocation(location) {
this.bubbleLocation = location;
}
getBubbleLocation() {
return this.bubbleLocation;
}
儲存及載入
自訂留言圖示必須實作 ISerializable
介面。狀態應符合 CommentState
介面。
saveState() {
return {
text: this.text,
pinned: this.bubbleVisible,
height: this.bubbleSize.height,
width: this.bubbleSize.width,
x: this.bubbleLocation.x,
y: this.bubbleLocation.y,
}
}
loadState(state) {
this.setText(state.text);
this.setBubbleVisible(state.pinned);
this.setBubbleSize(new Blockly.utils.Size(state.width, state.height));
this.setBubbleLocation(new Blockly.utils.Coordinate(state.x, state.y));
}
如要進一步瞭解圖示序列化,請參閱「儲存及載入圖示」。
註冊圖示
最後,取消註冊現有的註解圖示,並註冊您的註解圖示,讓 Blockly 可以例項化。取消註冊時使用字串 'comment'
,註冊時則使用 IconTypes.COMMENT
。
Blockly.icons.registry.unregister('comment');
Blockly.icons.registry.register(Blockly.icons.IconType.COMMENT, myCommentIcon);
註冊圖示後,Blockly 會使用該圖示取代內建的註解圖示,例如使用者點選內容選單中的「新增註解」時,或是您呼叫 myBlock.setCommentText()
時。