富文本編輯器 quill.js 開發(五): 自定義插件

quill.js 中,擴展性最強大的功能就是插件
本文主要以一個圖片擴展的插件來介紹 quill 插件開發

quill.js 中他有着自己的名字: Modules,而他也內置了 5 種插件:

  • TOOLBAR
  • KEYBOARD
  • HISTORY
  • CLIPBOARD
  • SYNTAX

分別是: 自定義工具欄、鍵盤事件控制、撤銷/重做功能配置、剪貼板配置、語法高亮

本文中的例子主要來源於 quill 最有名插件之一:https://github.com/kensnyder/quill-image-resize-module

modules 模板

先建立一個簡單的 modules demo

創建文件 modules/index.ts

export default class QuillResize {
  private quill: any;

  constructor(quill, options = {}) {
    // 賦值, 備用
    this.quill = quill;

    this.onCreate()
  }

  onCreate () {
    console.log('onCreate')
    // 在這裏我們開始做一些事情
  }

}

App.tsx 引用 modules:

import ImageResize from './modules/index'

Quill.register('modules/resize', ImageResize);


function App() {

  const modules = useMemo(() => ({
    toolbar: {
      container: '#toolbar',
    },
    resize: { // resize 就是上面註冊的名字 'modules/resize'
      foo: 1 // 這裏傳一個自定義的參數
    }
  }), []);

  // ...

  return (<div className={'container'}>
    <CustomToolbar/>
    <ReactQuill ref={editorRef} theme="snow" value={value} modules={modules} onChange={setValue}/>
  </div>)
}

這就是 modules 的雛形, 現在我們可以做任何想做的事了!

圖片交互

我們需要縮放圖片,那麼就需要給圖片添加狀態,即點擊圖片之後,用戶知道它是能夠交互的

添加監聽事件,讓用戶知道高亮的是什麼元素:

export default class QuillResize {
  constructor(quill, options = {}) {
    this.quill = quill;

    this.quill.root.addEventListener('mousedown', this.handleClick, false);
  }

  handleClick = (evt)=> {
    let show = false;
    let blot;
    const target = evt.target;

    if (target && target.tagName) {
      // 在 quill 編輯器中找到對應的點擊結構
      blot = this.quill.constructor.find(target);
      if (blot) {
        // 如果有,再通過 judgeShow 函數判斷是否該高亮
        show = this.judgeShow(blot, target);
      }
    }
    // 如果需要高亮, 則阻止默認動作(如 a 標籤等等)
    if (show) {
      evt.preventDefault();
      return;
    }
    if (this.activeEle) {
      // 如果點擊在其他位置, 已經聚焦圖片了, 那就取消高亮
      this.hide();
    }
  }
}

handleClick 流程:

image

judgeShow 判斷是否應該聚焦圖片:

  judgeShow = (blot, target) => {
  let res = false;
  if (!blot) return res;
  // 數據的一些判斷和補充
  if (!target && blot.domNode) target = blot.domNode;

  // 參數, 支持最小是 10px 的圖片, 可從外部傳入
  const options = {
    limit: {
      minWidth: 10,
    },
  }

  if (!options) return res;
  // 如果當前聚焦的是再次點擊的,則直接 return
  if (this.activeEle === target) return true;

  // 判斷大小的限制
  const limit = options.limit || {};
  if (!limit.minWidth || (limit.minWidth && target.offsetWidth >= limit.minWidth)) {
    res = true;

    // 當前聚焦和點擊的圖片不是同一個的時候, 隱藏原有的
    if (this.activeEle) {
      this.hide();
    }
    // 重新賦值
    this.activeEle = target;
    this.blot = blot;

    // 調用 show 方法, 顯示聚焦樣式
    this.show();
  }

  return res;
}

顯示圖片高亮聚焦樣式

show = ()=> {
  this.showOverlay(); // 顯示樣式
  // this.initializeModules(); //初始化拖動事件/其他事件 這裏暫不開放
  // 如果有樣式, 則添加聚焦樣式
  if (this.activeEle) this.activeEle.classList.add(this.activeClass);
}

showOverlay = () => {
  if (this.overlay) {
    this.hideOverlay();
  }

  // 取消光標選中
  this.quill.setSelection(null);

  // 阻止用戶選中
  this.setUserSelect('none');

  // 創建一個遮罩
  this.overlay = document.createElement('div');
  // 添加遮罩樣式
  Object.assign(this.overlay.style, this.overlayStyle);
  // 插入到編輯器中
  this.quill.root.parentNode.appendChild(this.overlay);

  this.hideProxy = () => {
    if (!this.activeEle) return;
    this.hide();
  };
  // 監聽輸入事件, 發生變化則隱藏
  this.quill.root.addEventListener('input', this.hideProxy, true);

  // 監聽滾動事件, 遮罩要隨着滾動偏移
  this.quill.root.addEventListener('scroll', this.updateOverlayPosition);

  // 樣式上添加具體的座標
  this.repositionElements();
};

圖片聚焦樣式:

image

滾動事件:

image

模塊擴展

在圖片聚焦時,添加額外功能,如圖片的縮放

新增文件 Resize.ts

class Resize {
  onCreate = () => {
    this.boxes = [];

    // 添加手柄
    this.addBox('nwse-resize'); // top left
    this.addBox('nesw-resize'); // top right
    this.addBox('nwse-resize'); // bottom right
    this.addBox('nesw-resize'); // bottom left

    // 計算座標
    this.positionBoxes();
  };


  addBox = cursor => {
    const box = document.createElement('div');

    Object.assign(box.style, this.handleStyles);

    box.style.width = `${this.handleStyles.width}px`;
    box.style.height = `${this.handleStyles.height}px`;

    // 監聽動作, 拖動時觸發函數
    box.addEventListener('mousedown', this.handleMousedown, false);
    // 插入元素
    this.overlay.appendChild(box);
    // 記錄到 boxes 中
    this.boxes.push(box);
  };
}

image

按下手柄時觸發拖動事件

  handleMousedown = evt => {
  // 修改狀態
  this.blot.handling && this.blot.handling(true);
  this.dragBox = evt.target;
  this.dragStartX = evt.clientX;
  this.dragStartY = evt.clientY;
  // 存儲座標
  this.preDragSize = {
    width: this.activeEle?.offsetWidth || 0,
    height: this.activeEle?.offsetHeight || 0,
  };
  // 存儲原本尺寸
  this.naturalSize = this.getNaturalSize();

  const {width, height} = this.naturalSize;
  this.localRatio = height / width;
  this.editorMaxWidth = this.quill.container.clientWidth - 30;


  // 修改手柄的 cursor 屬性
  this.setCursor(this.dragBox!.style.cursor);

  // 監聽拖動和放開事件
  // 根據拖動的距離, 計算圖片的尺寸,進行縮放
  // 在 mouseup 中釋放監聽事件
  document.addEventListener('mousemove', this.handleDrag, false);
  document.addEventListener('mouseup', this.handleMouseup, false);
};

大體流程:
image

拖動效果:

image

總結

當前例子只講述了點擊圖片之後的縮放功能,另外還有很多地方值得我們進行擴展,
如: 點擊圖片的預覽、展示圖片的尺寸、添加圖片的工具按鈕、擴展到視頻組件等等

不過即使是一個簡單的例子,也能管中窺豹,入門插件的開發

當然這這也只是 quill 富文本的開發,在業界還有很多優秀的富文本編輯器,他們都有着不同的實現和特殊功能,這些都值得我們繼續深入學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章