如何扩展一个自定义编辑器?

从HBuilderX 2.9.2及以上版本开始支持

  • 通过 customEditors 配置扩展点,声明需要注册的自定义编辑器。
  1. //package.json
  2. //...NOTEpackage.json不支持注释,以下代码使用时需要将注释删掉
  3. "contributes": {
  4. "customEditors": [{
  5. "viewType": "catEdit.catScratch", // 自定义编辑器类型id
  6. "displayName": "Cat Scratch",
  7. "selector": [{
  8. "fileNamePattern": "*.cscratch" // 文件名匹配模式
  9. }],
  10. "priority": "default"
  11. },
  12. ...]
  13. }
  • 插件代码继承CustomEditorProvider等

    HBuilderX使用WebViewPanel来作为自定义编辑器的视图,WebViewPanel的用法也可以参考视图扩展中部分示例。

  1. var hx = require("hbuilderx");
  2. // 引入主要的类
  3. let CustomDocument = hx.CustomEditor.CustomDocument;
  4. let CustomEditorProvider = hx.CustomEditor.CustomEditorProvider;
  5. let CustomDocumentEditEvent = hx.CustomEditor.CustomDocumentEditEvent;
  6. // 继承CustomDocument
  7. class CatCustomDocument extends CustomDocument {
  8. constructor(uri) {
  9. super(uri)
  10. }
  11. dispose() {
  12. super.dispose();
  13. }
  14. }
  15. // 继承CustomEditorProvider,实现必要的方法
  16. class CatCustomEditorProvider extends CustomEditorProvider{
  17. constructor(context){
  18. super()
  19. }
  20. openCustomDocument(uri){
  21. // 创建CustomDocument
  22. return Promise.resolve(new CatCustomDocument(uri));
  23. }
  24. resolveCustomEditor(document, webViewPanel){
  25. // 关联CustomDocument与WebViewPanel
  26. }
  27. saveCustomDocument(document) {
  28. // 保存document
  29. return true;
  30. }
  31. saveCustomDocumentAs(document, destination) {
  32. // document另存为至destination
  33. return true;
  34. }
  35. }

自定义编辑器提供了新的插件激活事件onCustomEditor

  1. // package.json 申明可以激活插件的自定义编辑器类型
  2. "activationEvents": [
  3. "onCustomEditor:catEdit.catScratch"
  4. ]
  1. // 插件激活入口, 通常是extension.js文件
  2. function activate(context) {
  3. hx.window.registerCustomEditorProvider("catEdit.catScratch", new CatCustomEditorProvider());
  4. }
  • 其他
  1. // 在合适的位置向HBuilderX发送文档变动事件,编辑器标签卡变为dirty状态
  2. provider.onDidChangeCustomDocument.fire(new CustomDocumentEditEvent(document));