Skip to content

Commit

Permalink
#9 Implements syntax highlighting in article
Browse files Browse the repository at this point in the history
  • Loading branch information
raeperd committed Jan 10, 2022
1 parent a8d3fff commit d3e1f0b
Show file tree
Hide file tree
Showing 3 changed files with 233 additions and 0 deletions.
206 changes: 206 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-markdown": "^7.1.2",
"react-syntax-highlighter": "^15.4.5",
"rehype-katex": "^6.0.2",
"rehype-raw": "^6.1.1",
"remark": "13.0.0",
Expand All @@ -33,6 +34,7 @@
"@types/node": "^15.6.0",
"@types/react": "^17.0.6",
"@types/react-dom": "^17.0.5",
"@types/react-syntax-highlighter": "^13.5.2",
"@typescript-eslint/eslint-plugin": "^5.9.0",
"@typescript-eslint/parser": "^5.9.0",
"autoprefixer": "10.4.0",
Expand Down
25 changes: 25 additions & 0 deletions pages/articles/[slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import rehypeKatex from 'rehype-katex';
import remarkMath from 'remark-math';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism';
import { Article, findFirstArticleBySlug, getAllArticleSlugs } from '../../lib/article';

// TODO: Add tag link
Expand All @@ -18,6 +20,7 @@ export default function ArticlePage({ article }: ArticlePageProps) {
</header>
<section className="post-content">
<ReactMarkdown
components={SyntaxHighlight}
rehypePlugins={[rehypeRaw, rehypeKatex]}
remarkPlugins={[remarkGfm, remarkMath]}
>
Expand All @@ -33,6 +36,28 @@ export default function ArticlePage({ article }: ArticlePageProps) {
)
}

const SyntaxHighlight: object = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
code({ inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter
style={vscDarkPlus}
language={match[1]}
PreTag="div"
{...props}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
)
},
}

type ArticlePageProps = {
article: Article
}
Expand Down

0 comments on commit d3e1f0b

Please sign in to comment.