All files / src/module plugin.ts

100% Statements 24/24
90% Branches 9/10
100% Functions 3/3
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54          1x     2x 1x     1x 14x 14x 3x     11x       5x 5x 5x   4x       1x     1x 1x 1x           1x 1x 1x           1x     1x  
/**
 * @description link-card plugin
 * @author wangfupeng
 */
 
import { DomEditor, IDomEditor, SlateTransforms } from '@wangeditor/editor'
 
function withSwiperCard<T extends IDomEditor>(editor: T) {
  const { isVoid, normalizeNode } = editor
  const newEditor = editor
 
  // 重写 isVoid
  newEditor.isVoid = (elem: any) => {
    const type = DomEditor.getNodeType(elem)
    if (type === 'swiper-card') {
      return true
    }
 
    return isVoid(elem)
  }
 
  // 重新 normalize
  newEditor.normalizeNode = ([node, path]) => {
    const type = DomEditor.getNodeType(node)
    if (type !== 'swiper-card') {
      // 未命中 link-card ,执行默认的 normalizeNode
      return normalizeNode([node, path])
    }
 
    // editor 顶级 node
    const topLevelNodes = newEditor.children || []
 
    // --------------------- link-card 后面必须跟一个 p header blockquote(否则后面无法继续输入文字) ---------------------
    const nextNode = topLevelNodes[path[0] + 1] || {}
    const nextNodeType = DomEditor.getNodeType(nextNode)
    if (
      nextNodeType !== 'paragraph' &&
      nextNodeType !== 'blockquote' &&
      !nextNodeType.startsWith('header')
    ) {
      // link-card node 后面不是 p 或 header ,则插入一个空 p
      const p = { type: 'paragraph', children: [{ text: '' }] }
      const insertPath = [path[0] + 1]
      SlateTransforms.insertNodes(newEditor, p, {
        at: insertPath, // 在 link-card 后面插入
      })
    }
  }
 
  return newEditor
}
 
export default withSwiperCard