mirror of
https://github.com/hedgedoc/hedgedoc.git
synced 2025-05-14 15:14:56 -04:00
Feature/highlightjs (#242)
* Add highlighting for code blocks Signed-off-by: Tilman Vatteroth <tilman.vatteroth@tu-dortmund.de>
This commit is contained in:
parent
b3899cd1a5
commit
e03da3bd76
10 changed files with 170 additions and 2 deletions
66
src/components/common/highlighted-code/highlighted-code.tsx
Normal file
66
src/components/common/highlighted-code/highlighted-code.tsx
Normal 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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
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>)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue