連線預覽工具會針對待處理連線建立視覺預覽畫面。這會顯示拖曳區塊後所連接的位置。
預設連線預覽工具會將插入標記放在區塊連接的位置。它也會醒目顯示連線,並在將被取代和中斷連線的區塊上淡出效果。
待處理連線的種類
待處理連線分為兩種。在一個案例中,捨棄的區塊會取代現有區塊,而現有區塊會中斷連線。在其他情況下,系統會在不中斷其他區塊連線的情況下插入已捨棄的區塊。
替換
當拖曳區塊上的連線連線至已有區塊的連線,而現在這裡已重新附加現有區塊時,系統就會進行替換。拖曳拖曳的區塊後,遭取代的區塊會中斷連線,而拖曳的區塊會就在原地進行連線。
根據預設,為了表示這一點,我們在要取代的區塊中加入淡出效果。
插入
在兩種情況下插入。當拖曳區塊的連線連結至沒有內容的連線時,就會發生這種情形。拖曳區塊中的連線前往已有區塊的連線,但可以插入兩個現有區塊之間,因此現有區塊不會中斷連線。
根據預設,我們會建立插入標記並醒目顯示要連接的連線。
建立自訂預覽器
如要使用其他影像內容預覽待處理連線,您可以建立自訂 IConnectionPreviewer
實作方式。
施工與處理
您必須為 IConnectionPreviewer
實作建構函式和處理方法。
每當區塊拖曳開始時,系統就會呼叫該建構函式,並傳遞正在拖曳的區塊。如果您需要根據區塊初始化任何狀態,可以在建構函式中進行。
class MyConnectionPreviewer implements IConnectionPreviewer {
constructor(draggedBlock: Blockly.BlockSvg) {
// Initialize state here.
}
}
區塊拖曳結束時,系統就會呼叫 dispose
方法。如果您需要在棄置 IConnectionPreviewer
執行個體時解除任何狀態,請在這裡執行。
dispose() {
// Dispose of and dereference any state.
}
建立預覽
您的 IConnectionPreviewer
必須實作邏輯,才能以視覺化方式預覽連線。
替換
如要預覽替換項目,請實作 previewReplacement
方法。
previewReplacement(draggedConn, staticConn, replacedBlock) {
// Visually indicate that the replacedBlock will be disconnected, and the
// draggedConn will be connected to the staticConn.
}
插入
如要預覽插入內容,請實作 previewConnection
方法。
previewConnection(draggedConn, staticConn) {
// Visually indicate the draggedConn will be connected to the staticConn.
}
如要根據拖曳區塊是否連結至空白輸入,或目前是在區塊之間插入,如要使用不同的預覽,您可以檢查 staticConn
目前是否已連線至其他連線。如果目前已連線 staticConn
,則會在區塊之間插入 draggedConn
。
previewConnection(draggedConn, staticConn) {
if (staticConn.targetConnection) {
// The dragged block is being inserted between blocks.
} else {
// The dragged block is connecting to an empty input.
}
}
CSS 預覽
如要預覽連結,請將 CSS 套用至區塊。舉例來說,只要將 blocklyReplaceable
CSS 類別新增至區塊,即可切換預設的取代淡出效果。
previewReplacement(draggedConn, staticConn, replacedBlock) {
Blockly.utils.dom.addClass(replacedblock.getSvgRoot(), 'my-custom-class');
}
轉譯器預覽
您可以實作具有特殊預覽掛鉤的自訂轉譯器來預覽連線。
previewReplacement(draggedConn, staticConn, replacedBlock) {
const renderer = replacedBlock.workspace.getRenderer()
if (renderer.addReplacementIndicator) {
renderer.addReplacementIndicator(replacedBlock);
}
}
隱藏預覽畫面
「IConnectionPreviewer
」必須能夠隱藏預覽畫面。當拖曳的區塊超出所有連線範圍時,系統就會呼叫此方法,因此不應顯示預覽畫面。也會在預覽工具丟棄前呼叫。
hidePreview() {
// Remove CSS classes, toggle renderer methods, etc.
}
註冊及使用
最後,IConnectionPreviewer
建立完成之後,您需要進行註冊這會將轉譯器與字串建立關聯,以便將其傳遞至插入設定。您也可以將 IConnectionPreviewer
類別 (例如建構函式) 直接傳遞至插入設定。
Blockly.registry.register(
Blockly.registry.Type.CONNECTION_PREVIEWER,
'MyConnectionPreviewer',
MyConnectionPreviewer,
);
// You can use the string.
const myWorkspace = Blockly.inject({
// options...
plugins: {
connectionPreviewer: 'myConnectionPreviewer',
},
};
// Or you can pass the class / constructor directly.
const myWorkspace = Blockly.inject({
// options...
plugins: {
connectionPreviewer: MyConnectionPreviewer,
},
};
如要進一步瞭解註冊,請參閱「插入子類別」。