服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - 编程技术 - 一款功能强大的markdown编辑器tui.editor使用示例详解

一款功能强大的markdown编辑器tui.editor使用示例详解

2023-05-29 11:51Gerry0808 编程技术

这篇文章主要为大家介绍了一款功能强大的markdown编辑器tui.editor使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

简介

最近在捯饬自己的个人网站,想找一款类似于掘金的markdown编辑器,主要诉求包含实时预览、语法高亮、自动生成目录索引。对比了市面上主流的几款编辑器,最后采用了@toast-ui/editor。选择的主要原因就是开箱即用,内置一些实用的插件,如表格并且支持合并单元格、语法高亮、图形展示、uml绘制等;支持自定义插件扩展,因为这款编辑器是基于prosemirror,前身即codemirror,编辑器本身是偏底层的,提供了丰富的api供我们自定义开发,这也大大增强了编辑器的灵活性,如果想加一个目录索引,我们完全可以自定义开发一个插件使用。

在初次使用过程中,也遇到一些注意点,本文以vue3为例,简单介绍@toast-ui/editor的使用过程。

安装使用

安装

?
1
npm install @toast-ui/editor -S

初始化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import Editor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn';
export default {
    mounted () {
      const editor = new Editor({
        el: this.$refs.editor,
        language: 'zh-CN',
        initialEditType: 'markdown',
        previewStyle: 'vertical',
      });
    }
  }

通过以上两步,我们就能得到一个简易的编辑器了,如下图所示:

一款功能强大的markdown编辑器tui.editor使用示例详解

显然我们的目的不仅如此,markdown编辑器还缺少语法高亮、目录栏,接下来我们看下如何扩展tui

官方插件

官方内置了以下插件:

插件名称 用途
@toast-ui/editor-plugin-chart 图形渲染
@toast-ui/editor-plugin-code-syntax-highlight 语法高亮
@toast-ui/editor-plugin-color-syntax 文本添加颜色
@toast-ui/editor-plugin-table-merged-cell 合并单元格
@toast-ui/editor-plugin-uml 渲染UML

接下来我们配置代码语法高亮。

  • 安装插件
?
1
npm install @toast-ui/editor-plugin-code-syntax-highlight
  • 使用
?
1
2
3
4
5
6
7
8
9
import 'prismjs/themes/prism.css';
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css';
import Editor from '@toast-ui/editor';
// 支持所有语言语法高亮
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all.js';
const editor = new Editor({
  // ...
  plugins: [codeSyntaxHighlight]
});

功能拓展

目前编辑器包含了语法高亮,如果需要添加目录索引,可以监听文档编辑的change事件,获取markdown文档内容,通过正则表达式解析即可。具体实现如下:

?
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
const editor = new Editor({
  // ...
  events: {
    change: this.handleContentChange.bind(this)
  },
});
methods: {
  handleContentChange () {
    const mdText = this.editor.mdEditor.getMarkdown()
    this.parseMdTitle(mdText)
  },
  parseMdTitle (mdText) { // 解析markdown title
    const pattern = /^(#+)\s+(.+)/mg
    let result = mdText.match(pattern)
    if (!result) return
    const catalogList = result.map((vv, index) => {
      const levelText = vv.match(/^(#+)/)
      return {
        level: levelText[0].length, // 目录级别
        index,
        cls: `heading-${levelText[0].length}`,
        content: vv.slice(levelText[0].length).trim(), // 内容
      }
    })
    this.catalogList = catalogList
  }
}

以上仅仅是一些基础的使用。markdown基础语法无法满足我们需要时、需要手动修改渲染样式等需求,tui.editor也提供相应的能力。如需要修改标题的默认渲染样式,我们可以使用customHTMLRenderer,这一块官方文档较少,可以从源码看出默认书写规则,内置schema位置详见源码libs\toastmark\src\html\baseConvertors.ts

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
new Editor({
  // ...
  customHTMLRenderer: {
    heading (node, { entering }) {
      const spec = {
        type: entering ? 'openTag' : 'closeTag',
        tagName: `h${node.level}`,
        outerNewLine: true,
      };
      // 给每个header添加class
      if (entering) spec.attributes = {
        'class': `heading${node.level}`
      }
      return spec
    }
  }
})

最新3.0版本的编辑器是基于Prosemirror,有兴趣的小伙伴可以去看下,功能十分强大,也是level1级富文本编辑器的典型代表。

编辑器最终效果图如下:

一款功能强大的markdown编辑器tui.editor使用示例详解

实现源码

?
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<template>
  <div class="full">
    <div class="markdown-editor" ref="editor"></div>
    <div class="catalog-container" v-if="catalogList.length > 0">
      <div class="catalog-title">目录</div>
      <template v-for="(item, index) in catalogList" :key="index">
        <div class="catalog-item" :class="item.cls">
          <a :href="'#heading' + (index + 1)" rel="external nofollow" >{{item.content}}</a>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
  import Editor from '@toast-ui/editor'
  import '@toast-ui/editor/dist/toastui-editor.css'
  import '@toast-ui/editor/dist/i18n/zh-cn';
  import 'prismjs/themes/prism.css';
  import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css';
  import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all.js';
  import '@toast-ui/editor-plugin-table-merged-cell/dist/toastui-editor-plugin-table-merged-cell.css';
  import tableMergedCell from '@toast-ui/editor-plugin-table-merged-cell';
  export default {
    data () {
      return {
        catalogList: []
      }
    },
    mounted () {
      this.editor = new Editor({
        el: this.$refs.editor,
        language: 'zh-CN',
        initialEditType: 'markdown',
        previewStyle: 'vertical',
        placeholder: '请输入内容',
        plugins: [codeSyntaxHighlight, tableMergedCell],
        events: {
          change: this.handleContentChange.bind(this)
        },
        customHTMLRenderer: {
          heading (node, { entering }) {
            const spec = {
              type: entering ? 'openTag' : 'closeTag',
              tagName: `h${node.level}`,
              outerNewLine: true,
            };
            // 添加自定义属性
            if (entering) spec.attributes = {
              'class': `heading${node.level}`
            }
            return spec
          }
        }
      })
    },
    methods: {
      handleContentChange () {
        const mdText = this.editor.mdEditor.getMarkdown()
        this.parseMdTitle(mdText)
      },
      parseMdTitle (mdText) { // 解析markdown title
        const pattern = /^(#+)\s+(.+)/mg
        let result = mdText.match(pattern)
        if (!result) return
        const catalogList = result.map((vv, index) => {
          const levelText = vv.match(/^(#+)/)
          return {
            level: levelText[0].length, // 目录级别
            index,
            cls: `heading-${levelText[0].length}`,
            content: vv.slice(levelText[0].length).trim(), // 内容
          }
        })
        this.catalogList = catalogList
      }
    }
  }
</script>
<style scoped>
  .full {
    position: relative
  }
  .catalog-container {
    box-sizing: border-box;
    position: absolute;
    right: 0;
    bottom: 32px;
    width: 200px;
    height: 300px;
    padding: 16px 0;
    background-color: rgba(255, 255, 255, .65);
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  .catalog-title {
    text-align: center;
    padding-bottom: 12px;
  }
  .catalog-item {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 4px 8px;
    font-size: 14px;
    user-select: none;
  }
  .catalog-item a {
    color: rgba(0, 0, 0, .65);
    text-decoration: none;
  }
  .heading-2 {
    padding-left: 24px;
  }
  .heading-3 {
    padding-left: 48px;
  }
  .catalog-item a:hover {
    color: cadetblue;
  }
  .markdown-editor {
    height: 100% !important;
    background: #fff;
    border-radius: 4px;
  }
</style>

参考资料

以上就是一款功能强大的markdown编辑器tui.editor使用示例详解的详细内容,更多关于markdown编辑器tui.editor的资料请关注服务器之家其它相关文章!

原文链接:https://juejin.cn/post/7201398466630516797

延伸 · 阅读

精彩推荐