美文网首页
react中解析MarkDown添加高亮添加行号

react中解析MarkDown添加高亮添加行号

作者: Demonskp | 来源:发表于2020-07-28 17:07 被阅读0次

react中解析MarkDown添加高亮添加行号

之前在做一个和数据库表血缘关系相关的一个需求,需要在页面上显示某个表的创建的脚本。因此我们需要对传过来的脚本进行解析并对关键词进行高亮,同时也需要为脚本添加一个行号。

效果:

code_line_number.png

解析MarkDown语法

解析MarkDown语法的库有挺多的,这里我使用的是marked这个库。使用起来挺简单的,但是由于我是在React当中使用它的,所以也需要对官网的例子做一些改变。


  const [html, setHtml] = useState();

  useEffect(() => {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false,
      //....
    });

    setHtml(content ? marked(content) : null);
  }, [content]);

只有当传入的文本(content)发生改变的时候才重新生成html。

添加高亮

添加高亮可以通过highlight.js来实现。

把上一步预留的位置,替换成highlight的回调函数即可。

  const [html, setHtml] = useState();
  useEffect(() => {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false,
      highlight(code) {
        return hljs.highlightAuto(code).value;
      },
    });

    setHtml(content ? marked(content) : null);
  }, [content]);

添加行号

添加行号这一步就会复杂一些,一开始在网上查找资料,有一个highlight.js的插件(highlightjs-line-numbers.js)是可以直接添加行号的。

但是有个问题在于,这个插件只能用在浏览器环境直接引用。所以并不靠谱。
(着急的同学可以看看,highlightjs-line-numbers2.js。看到示例是vue的。)

所以我们自己找到了一个方案。通过CSS content的相关属性生成对应的行号。

通过beforeNumber这个方法,为经过highlight.js处理后的code代码块生成对应的行号块。每有一行代码就能在行号块当中添加一个span标签。最后将这个行号块也添加在code代码块当中。


/**
 * 为代码块显示添加行号
 * @param {String} code MD的代码内容
 */
function beforNumber(code) {
  if (!code.trim()) {
    return code;
  }
  const list = code.split('\n');
  const spanList = ['<span aria-hidden="true" line-row>'];
  list.forEach(() => {
    spanList.push('<span></span>');
  });
  spanList.push('</span>');
  list.push(spanList.join(''));
  return list.join('\n');
}

在CSS当中,我们在行号块里面添加一个计数器,然后在行号块的span从这个计数器取数,通过before来显示取出来的行号。最后将code和行号块的位置调整一下就能正常显示了。

...

  span[line-row] {
    position: absolute;
    pointer-events: none;
    top: 0;
    font-size: 100%;
    left: -3.8em;
    width: 3em;
    letter-spacing: -1px;
    border-right: 1px solid #999;
    user-select: none;
    counter-reset: linenumber;
  }

  span[line-row]>span {
    pointer-events: none;
    display: block;
    counter-increment: linenumber;
  }

  span[line-row]>span::before {
    content: counter(linenumber);
    color: #999;
    display: block;
    padding-right: .8em;
    text-align: right
  }
...

全部代码

组件:


// index.jsx
import React, { useEffect, useState } from 'react';
import marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
import styles from './index.less';

/**
 * 为代码块显示添加行号
 * @param {String} code MD的代码内容
 */
function beforNumber(code) {
  if (!code.trim()) {
    return code;
  }
  const list = code.split('\n');
  const spanList = ['<span aria-hidden="true" line-row>'];
  list.forEach(() => {
    spanList.push('<span></span>');
  });
  spanList.push('</span>');
  list.push(spanList.join(''));
  return list.join('\n');
}

function Markdown({ content }) {
  const [html, setHtml] = useState();
  useEffect(() => {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false,
      highlight(code) {
        return beforNumber(hljs.highlightAuto(code).value);
      },
    });

    setHtml(content ? marked(content) : null);
  }, [content]);

  return (
    <div className={styles.centent}>
      <div
        id="content"
        className="article-detail"
        dangerouslySetInnerHTML={{
          __html: html,
        }}
      />
    </div>
  );
}

export default Markdown;

组件样式:

// index.less
.centent {

  /*对 markdown 样式的补充*/
  code,
  pre {
    color: #ccc;
    background: none;
    font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
    font-size: 1em;
    text-align: left;
    white-space: pre;
    word-spacing: normal;
    word-break: normal;
    word-wrap: normal;
    line-height: 1.5;
    tab-size: 4;
    hyphens: none;
    overflow-y: hidden;
  }

  pre {
    background: #2d2d2d;
    position: relative;
    padding-left: 3.8em;
  }

  code {
    position: relative;
    white-space: inherit
  }

  span[line-row] {
    position: absolute;
    pointer-events: none;
    top: 0;
    font-size: 100%;
    left: -3.8em;
    width: 3em;
    letter-spacing: -1px;
    border-right: 1px solid #999;
    user-select: none;
    counter-reset: linenumber;
  }

  span[line-row]>span {
    pointer-events: none;
    display: block;
    counter-increment: linenumber;
  }

  span[line-row]>span::before {
    content: counter(linenumber);
    color: #999;
    display: block;
    padding-right: .8em;
    text-align: right
  }

  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 1em;
  }

  strong {
    font-weight: bold;
  }

  p>code:not([class]) {
    padding: 2px 4px;
    font-size: 90%;
    color: #c7254e;
    background-color: #f9f2f4;
    border-radius: 4px;
  }

  p img {
    /* 图片居中 */
    margin: 0 auto;
    display: flex;
  }

  #content {
    font-family: "Microsoft YaHei", 'sans-serif';
    font-size: 16px;
    line-height: 30px;
  }

  #content .desc ul,
  #content .desc ol {
    color: #333333;
    margin: 1.5em 0 0 25px;
  }

  #content .desc h1,
  #content .desc h2 {
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }

  #content .desc a {
    color: #009a61;
  }
}

相关文章

网友评论

      本文标题:react中解析MarkDown添加高亮添加行号

      本文链接:https://www.haomeiwen.com/subject/ruxqrktx.html