Tui.editor 视频嵌入插件
tui.editor 是韩国 NHN 公司出品的在线编辑器,支持通过 Plugin 形式扩展编辑器功能,因业务需要,封装了视频嵌入插件。
视频插件实现逻辑比较简单,先在 Markdown 模式中定义视频展示语法,语法复用了代码标签,只是代码语言需要自定义,即通过自定义 code
标签的语言,使用 tui.editor
提供的 codeBlockManager
定制化展示想对应的语言。
源码如下:
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 const defaultList = { youku: 'http://player.youku.com/embed/' , bilibili: 'http://player.bilibili.com/player.html?aid=' , qq: 'https://v.qq.com/txp/iframe/player.html?vid=' , youtube: 'https://www.youtube.com/embed/' , }; const renderVideo = (wrapperId, sourceId, type, videoMap ) => { let el = document .querySelector('#' + wrapperId); if (type && videoMap[type]) { const url = videoMap[type]; el.innerHTML = `<iframe height=450 width=640 align='center' src='${url} ${sourceId} ' frameborder=0 allowfullscreen></iframe>` ; } }; export default function videoPlugin (editor, options = {} ) { const vList = options.list || {}; const { codeBlockManager } = Object .getPrototypeOf(editor).constructor; const videoMap = { ...defaultList, ...vList, }; Object .keys(videoMap).forEach((type ) => { codeBlockManager.setReplacer(type, function (sourceId ) { if (!sourceId) return ; var wrapperId = type + Math .random().toString(36 ).substr(2 , 10 ); setTimeout(renderVideo.bind(null , wrapperId, sourceId, type, videoMap), 0 ); return `<div style="text-align: center" id="${wrapperId} "></div>` ; }); }); }
我在这里预置了四种视频站点的链接,也提供了在配置插件时通过参数扩展/复写预置视频列表配置,像这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer' ;import videoPlugin from '@leeonfield/editor-plugin-video' ;const viewer = new Viewer({ plugins: [ [ videoPlugin, { list: { youtube: 'http://player.youku.com/embed/' , }, }, ], ], });
使用时只需要在 Markdown 模式下录入对应视频的的 embed id 即可
1 2 3 ``` youtube GveTAk727mM ```
效果如下