Tinymce - 宇宙第一富文本编辑器?[3]

5,023 阅读4分钟

自定义插件

Tinymce官方提供了丰富的插件,足以满足关于一般富文本的需求,也可以通过进一步的配置,让其更符合实际的业务场景。但是,如果这还满足不了你的需求,想进一步的定制化呢?

Tinymce提供了丰富的接口,用以编写自定义的插件。并且,官方的插件源码也非常清晰易懂,在写自己的插件的时候,可以做一个详细的参考。

编写插件

其实编写一个插件很简单,只需要做3件事情。

  1. 制作一个Svg格式的图标,这个图标用于在工具栏(toolbar)的展示。(按钮长什么样)
  2. 给工具栏新增一个按钮,并给这个按钮设置点击、下拉等要触发的事件。(按钮可以做什么)
  3. 注册一个命令,对按钮的操作可以触发这个命令,命令的回调方法里对编辑器内容进行操作。(具体怎么做)

行高插件

因为公司这边的业务要求时,开发一个功能与微信公众号文章编辑器基本功能对称的富文本编辑器。而微信编辑器有一个设置行高的功能,Tinymce官方没有提供,虽然可以通过配置格式化样式进行简单的开发,但为了统一体验,就仿照微信编辑器在工具栏新增了一个可以设置行距的按钮。

import Tinymce from 'tinymce'

Tinymce.PluginManager.add('lineheight', function (editor) {
  // 执行方法
  const actionFunction = function (editor, val) {
    const value = val || editor.getParam('lineheight_default_value', 1.5)
    editor.formatter.apply('lineheight', { value })
  }

  // 命令
  editor.addCommand('mceLineHeight', function (ui, value) {
    actionFunction(editor, value)
  })

  // toolbar 按钮 图标
  editor.ui.registry.addIcon('lineheight', `
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
      <path d="M5,5 L19,5 L19,7 L5,7 L5,5 Z M13,9 L19,9 L19,11 L13,11 L13,9 Z M13,13 L19,13 L19,15 L13,15 L13,13 Z M5,17 L19,17 L19,19 L5,19 L5,17 Z M11.07,11.46 L8.91,9.84 L6.75,11.46 L5.79,10.18 L8.43,8.2 C8.71444444,7.98666667 9.10555556,7.98666667 9.39,8.2 L12.03,10.18 L11.07,11.46 Z M8.91,14.16 L11.07,12.54 L12.03,13.82 L9.39,15.8 C9.10555556,16.0133333 8.71444444,16.0133333 8.43,15.8 L5.79,13.82 L6.75,12.54 L8.91,14.16 Z" id="行间距"></path>
    </svg>
  `)

  // toolbar 按钮功能
  editor.ui.registry.addSplitButton('lineheight', {
    tooltip: '行间距',
    // 图标
    icon: 'lineheight',
    // 初始化
    onSetup (api) {
      editor.formatter.register({
        lineheight: {
          selector: 'p,h1,h2,h3,h4,h5,h6,table,td,th,div,ul,ol,li,section,article,header,footer,figcaption',
          styles: { 'line-height': '%value' }
        }
      })
    },
    // 图标点击
    onAction (api) {
      return editor.execCommand('mceLineHeight')
    },
    // 列表项点击
    onItemAction (buttonApi, value) {
      return editor.execCommand('mceLineHeight', false, value)
    },
    // 初始化列表
    fetch (callback) {
      const items = [
        {
          type: 'choiceitem',
          text: '1',
          value: 1
        },
        {
          type: 'choiceitem',
          text: '1.5',
          value: 1.5
        },
        {
          type: 'choiceitem',
          text: '1.75',
          value: 1.75
        },
        {
          type: 'choiceitem',
          text: '2',
          value: 2
        },
        {
          type: 'choiceitem',
          text: '3',
          value: 3
        },
        {
          type: 'choiceitem',
          text: '4',
          value: 4
        },
        {
          type: 'choiceitem',
          text: '5',
          value: 5
        }
      ]
      callback(items)
    }
  })
})

这个插件只是对当前内容的一种格式化。比较简单。

引入时机

插件一定要在tinymce引入之后,实例初始化之前引入。如果插件出现重名,会优先使用自己项目中的插件。换言之,初始化的时候,会先找已注册的插件,没有找到的话,会根据配置,去相对路径取插件文件。

import Tinymce from 'tinymce'
import './plugins/lineheight'

Tinymce.init({
    selector: '.textarea',
    plugins: ['lineheight']
})

预览插件

因为编辑器自带的插件不能满足业务需求,所以自己写了一个预览插件。

import Tinymce from 'tinymce'

Tinymce.PluginManager.add('preview', function (editor) {
  const adaptStyle = `
    body {
      width: 375px !important;
      height: 667px !important;
      overflow-x: hidden !important;
      overflow-y: auto !important;
      margin: 0 !important;
      padding: 0 !important;
      font-size: 17px;
    }
    .adaptive-screen-width {
      width: 100% !important;
      height: auto;
    }
  
  `

  const Settings = {
    getContentStyle (editor) {
      return editor.getParam('content_style', '')
    },
    shouldUseContentCssCors (editor) {
      return editor.getParam('content_css_cors', false, 'boolean')
    },
    getBodyId (editor) {
      let bodyId = editor.settings.body_id || 'tinymce'
      if (bodyId.indexOf('=') !== -1) {
        bodyId = editor.getParam('body_id', '', 'hash')
        bodyId = bodyId[editor.id] || bodyId
      }
      return bodyId
    },
    getBodyClass (editor) {
      let bodyClass = editor.settings.body_class || ''
      if (bodyClass.indexOf('=') !== -1) {
        bodyClass = editor.getParam('body_class', '', 'hash')
        bodyClass = bodyClass[editor.id] || ''
      }
      return bodyClass
    },
    getDirAttr (editor) {
      const encode = editor.dom.encode
      let directionality = editor.getBody().dir
      return directionality ? ' dir="' + encode(directionality) + '"' : ''
    }
  }

  const getPreviewFrame = function (editor) {
    // <head>
    let headHtml = ''
    const encode = editor.dom.encode
    const contentStyle = Settings.getContentStyle(editor)
    headHtml += `<base href="${encode(editor.documentBaseURI.getURI())}">`
    if (contentStyle) {
      headHtml += `<style type="text/css">${contentStyle + adaptStyle}</style>`
    }
    const cors = Settings.shouldUseContentCssCors(editor) ? ' crossorigin="anonymous"' : ''
    Array.from(editor.contentCSS).forEach(url => {
      headHtml += `<link type="text/css" rel="stylesheet" href="${encode(editor.documentBaseURI.toAbsolute(url))}" ${cors}>`
    })
    // <body>
    const bodyId = Settings.getBodyId(editor)
    const bodyClass = Settings.getBodyClass(editor)
    const dirAttr = Settings.getDirAttr(editor)
    // 禁用点击事件
    const preventClicksOnLinksScript = '<script>document.addEventListener && document.addEventListener("click", function(e) {for (var elm = e.target; elm; elm = elm.parentNode) {if (elm.nodeName === "A") {e.preventDefault();}}}, false);</script> '
    // html
    const html = `
      <!DOCTYPE html>
        <html lang="zh_cn">
          <head>${headHtml}</head>
          <body id="${encode(bodyId)}" class="mce-content-body ${encode(bodyClass)}" ${dirAttr}>
            ${editor.getContent()}
            ${preventClicksOnLinksScript}
          </body>
        </html>  
    `
    // iframe
    return `
      <iframe sandbox="allow-scripts allow-same-origin" frameborder="0" width="395" height="667" srcdoc="${encode(html)}">
      </iframe>
    `
  }

  const getPreviewDialog = function (editor) {
    let frame = getPreviewFrame(editor)
    const id = 'tinymce-editor-preview-dialog-wrapper'
    const closeEvent = `
      onclick="document.getElementById('${id}').remove()"
    `
    const dialog = document.createElement('div')
    dialog.id = id
    dialog.innerHTML = `
      <div class="tinymce-editor-preview-dialog-mask"></div>
      <div class="tinymce-editor-preview-dialog">
        <div class="tinymce-editor-preview-dialog-header">
            <div class="tinymce-editor-preview-dialog-header-title">预览</div>
            <div class="tinymce-editor-preview-dialog-header-close" ${closeEvent} title="关闭">
              <svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">
                <path d="M17.953 7.453L13.422 12l4.531 4.547-1.406 1.406L12 13.422l-4.547 4.531-1.406-1.406L10.578 12
                 6.047 7.453l1.406-1.406L12 10.578l4.547-4.531z" fill-rule="evenodd"></path>
              </svg>
            </div>
        </div>
        <div class="tinymce-editor-preview-dialog-body">${frame}</div>
        <div class="tinymce-editor-preview-dialog-footer">
            <div class="tinymce-editor-preview-dialog-footer-btn" ${closeEvent}>关闭</div>
        </div>
      </div>
    `
    return dialog
  }

  const actionFunction = (editor, value) => {
    const dialog = getPreviewDialog(editor)
    if (document.getElementById(dialog.id)) {
      console.warn('当前页面只能有一个弹窗')
    } else {
      document.body.appendChild(dialog)
    }
  }

  editor.addCommand('mcePreview', function () {
    actionFunction(editor)
  })

  editor.ui.registry.addButton('preview', {
    icon: 'preview',
    tooltip: 'Preview',
    onAction: function () {
      return editor.execCommand('mcePreview')
    }
  })
})

这个插件根据编辑器官方的预览插件改写而成,定制化了一些样式。如前所述,因为与官方插件重名,所以官方的插件文件将不再会被加载。这个插件比行高插件稍微复杂了点,但是它没有对内容进行改动。

音频插件

开发中

参考

  1. tinymce官方文档