[英]Monaco editor copy/cut/paste action
我正在為我的項目使用monaco 編輯器,我可以為撤消/重做操作發出編輯器事件,如下所示:
editor.getModel().redo();
editor.getModel().undo();
這是一個非常常見的編輯器,所以我認為也應該有剪切/復制/粘貼操作,但不幸的是,我沒有看到類似的操作,如 editor.getModel().cut.. 等
我錯過了什么?
您可以觸發編輯器操作來復制/粘貼:
editorInstance.trigger('source','editor.action.clipboardCopyAction');
editorInstance.trigger('source','editor.action.clipboardPasteAction');
可用的動作可以用以下editorInstance.getActions().map(a => a.id)
列出: editorInstance.getActions().map(a => a.id)
我仍然沒有弄清楚要觸發的第一個參數有什么作用,所以我只提供了一個字符串,提示觸發該動作的原因。
您可以將本機瀏覽器事件與您的編輯器一起使用,並確保您的編輯器對這些操作具有“焦點”:
editor.focus();
document.execCommand('cut'); // copy paste, e.t.c
如果你想使用現代 API,那么你可以使用剪貼板 API,如下所示
對於切割:
function cutOrCopy(editor:monaco.editor.IStandaloneEditor, isCut:boolean) {
editor.focus();
// Get the current selection in the editor.
const selection = editor.getSelection();
if (!selection || selection.isEmpty()) {
navigator.clipboard.writeText("");
return;
}
// Get the text from that selection.
const data = editor.getModel()?.getValueInRange(selection);
// Set the clipboard contents.
navigator.clipboard.writeText(data || "");
if (isCut) {
// This is a cut operation, so replace the selection with an empty string.
editor.executeEdits("clipboard", [{
range: selection,
text: "",
forceMoveMarkers: true,
}]);
}
}
同樣對於粘貼
async function paste(editor:monaco.editor.IStandaloneEditor) {
editor.focus();
// Get the current clipboard contents
const text = await navigator.clipboard.readText();
// Get the current selection in the editor.
const selection = editor.getSelection();
if (!selection) {
return;
}
// Replace the current contents with the text from the clipboard.
editor.executeEdits("clipboard", [{
range: selection,
text: text,
forceMoveMarkers: true,
}]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.