Feature/highlightjs (#242)

* Add highlighting for code blocks

Signed-off-by: Tilman Vatteroth <tilman.vatteroth@tu-dortmund.de>
This commit is contained in:
mrdrogdrog 2020-06-22 22:39:14 +02:00 committed by GitHub
parent b3899cd1a5
commit e03da3bd76
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 170 additions and 2 deletions

View file

@ -0,0 +1,66 @@
import hljs from 'highlight.js'
import React, { useMemo } from 'react'
import ReactHtmlParser from 'react-html-parser'
import { ShowIf } from '../show-if/show-if'
import './highlighted-code.scss'
export interface HighlightedCodeProps {
code: string,
language?: string,
showGutter: boolean
}
export const escapeHtml = (unsafe: string): string => {
return unsafe
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}
const checkIfLanguageIsSupported = (language: string):boolean => {
return hljs.listLanguages().indexOf(language) > -1
}
const correctLanguage = (language: string|undefined): string|undefined => {
switch (language) {
case 'html':
return 'xml'
default:
return language
}
}
export const HighlightedCode: React.FC<HighlightedCodeProps> = ({ code, language, showGutter }) => {
const highlightedCode = useMemo(() => {
const replacedLanguage = correctLanguage(language)
return ((!!replacedLanguage && checkIfLanguageIsSupported(replacedLanguage)) ? hljs.highlight(replacedLanguage, code).value : escapeHtml(code))
.split('\n')
.filter(line => !!line)
.map(line => ReactHtmlParser(line))
}, [code, language])
return (
<code className={'hljs'}>
<ShowIf condition={showGutter}>
<span className={'linenumbers'}>
{
highlightedCode
.map((line, index) => {
return <span data-line-number={index + 1}/>
})
}
</span>
</ShowIf>
<span className={'code'}>
{
highlightedCode
.map((line, index) =>
<div key={index} className={'line'}>
{line}
</div>)
}
</span>
</code>)
}