feat: add highlight for code block (#291)

* feat: add highlight for code block

* chore: update test
This commit is contained in:
boojack 2022-10-14 22:29:28 +08:00 committed by GitHub
parent 65a61ed270
commit eefd0444c8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 24 additions and 9 deletions

View file

@ -13,6 +13,7 @@
"copy-to-clipboard": "^3.3.2",
"dayjs": "^1.11.3",
"emoji-picker-react": "^3.6.2",
"highlight.js": "^11.6.0",
"i18next": "^21.9.2",
"lodash-es": "^4.17.21",
"qs": "^6.11.0",

View file

@ -9,9 +9,8 @@ describe("test marked parser", () => {
markdown: `\`\`\`
hello world!
\`\`\``,
want: `<pre lang=''>
hello world!
</pre>`,
want: `<pre><code class="language-plaintext">hello world!
</code></pre>`,
},
{
markdown: `test code block
@ -21,9 +20,8 @@ console.log("hello world!")
\`\`\``,
want: `<p>test code block</p>
<p></p>
<pre lang='js'>
console.log("hello world!")
</pre>`,
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"hello world!"</span>)
</code></pre>`,
},
];

View file

@ -1,4 +1,5 @@
import { escape } from "lodash-es";
import hljs from "highlight.js";
export const CODE_BLOCK_REG = /^```(\S*?)\s([\s\S]*?)```(\n?)/;
@ -8,7 +9,12 @@ const renderer = (rawStr: string): string => {
return rawStr;
}
return `<pre lang='${escape(matchResult[1])}'>\n${escape(matchResult[2])}</pre>${matchResult[3]}`;
const language = escape(matchResult[1]) || "plaintext";
const highlightedCodes = hljs.highlight(matchResult[2], {
language,
}).value;
return `<pre><code class="language-${language}">${highlightedCodes}</code></pre>${matchResult[3]}`;
};
export default {

View file

@ -19,7 +19,7 @@
}
.img {
@apply float-left max-w-full;
@apply float-left max-w-full rounded cursor-pointer hover:shadow;
}
.tag-span {
@ -48,7 +48,11 @@
}
pre {
@apply w-full my-1 py-2 px-3 rounded text-sm bg-gray-100 whitespace-pre-wrap;
@apply w-full my-1 p-3 rounded bg-gray-100 whitespace-pre-wrap;
code {
@apply block;
}
}
code {

View file

@ -4,6 +4,7 @@ import store from "./store";
import App from "./App";
import "./i18n";
import "./helpers/polyfill";
import "highlight.js/styles/github.css";
import "./less/global.less";
import "./css/index.css";

View file

@ -2160,6 +2160,11 @@ has@^1.0.3:
dependencies:
function-bind "^1.1.1"
highlight.js@^11.6.0:
version "11.6.0"
resolved "https://registry.yarnpkg.com/highlight.js/-/highlight.js-11.6.0.tgz#a50e9da05763f1bb0c1322c8f4f755242cff3f5a"
integrity sha512-ig1eqDzJaB0pqEvlPVIpSSyMaO92bH1N2rJpLMN/nX396wTpDA4Eq0uK+7I/2XG17pFaaKE0kjV/XPeGt7Evjw==
hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2:
version "3.3.2"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"