ckeditor5:在工具栏上添加一个按钮

插件开发之,在工具栏上添加一个按钮
更新于: 2021-12-19 12:57:29

搭建基础项目

.
├── app.js
├── index.html
├── package-lock.json
├── package.json
├── src
│   └── index.js
└── webpack.config.js

从 editor 中得到 t, local, ui

const { t, locale, ui } = this.editor;

导入 buttonviewui 包,并创建一个 button 的实例

const buttonView = new ButtonView(locale);

buttonView.set({
  label: t("your button text"),
  withText: true,
  tooltip: false,
});

注册到 editorui 库中去

ui.componentFactory.add("inline-tag", () => {
  // 上一步产生的 buttonview
  return buttonView;
});

用配置让其显示

ClassicEditor.create(document.querySelector("#editor"), {
  plugins: [Essentials, Paragraph, Bold, Italic, InlineTag],
  toolbar: ["bold", "italic", "inline-tag"],
  placeholderConfig: {
    types: ["date", "color", "first name", "surname"],
  },
});

效果如下

ckeditor 工具栏点击按钮效果

完整代码如下:

 src/index.js

import Plugin from "@ckeditor/ckeditor5-core/src/plugin";
import ButtonView from "@ckeditor/ckeditor5-ui/src/button/buttonview";

export default class InlineTag extends Plugin {
  init() {
    const { t, locale, ui } = this.editor;
    ui.componentFactory.add("inline-tag", () => {
      const btn = new ButtonView(locale);
      btn.set({
        label: t("Inline Tag"),
        withText: true,
        tooltip: false,
      });
      this.listenTo(btn, "execute", () => console.log("hello ckeditor5"));
      return btn;
    });
  }
}

app.js

import ClassicEditor from "@ckeditor/ckeditor5-editor-classic/src/classiceditor";
import Essentials from "@ckeditor/ckeditor5-essentials/src/essentials";
import Paragraph from "@ckeditor/ckeditor5-paragraph/src/paragraph";
import Bold from "@ckeditor/ckeditor5-basic-styles/src/bold";
import Italic from "@ckeditor/ckeditor5-basic-styles/src/italic";
import CKEditorInspector from "@ckeditor/ckeditor5-inspector";
import InlineTag from "./src";

ClassicEditor.create(document.querySelector("#editor"), {
  plugins: [Essentials, Paragraph, Bold, Italic, InlineTag],
  toolbar: ["bold", "italic", "inline-tag"],
  placeholderConfig: {
    types: ["date", "color", "first name", "surname"],
  },
})
  .then((editor) => {
    console.log("Editor was initialized", editor);
    CKEditorInspector.attach(editor);
    window.editor = editor;
  })
  .catch((error) => {
    console.error(error.stack);
  });