diff options
Diffstat (limited to 'packages/gitbook-plugin-highlight/src/CodeBlock.js')
-rw-r--r-- | packages/gitbook-plugin-highlight/src/CodeBlock.js | 46 |
1 files changed, 43 insertions, 3 deletions
diff --git a/packages/gitbook-plugin-highlight/src/CodeBlock.js b/packages/gitbook-plugin-highlight/src/CodeBlock.js index f55524f..89f6793 100644 --- a/packages/gitbook-plugin-highlight/src/CodeBlock.js +++ b/packages/gitbook-plugin-highlight/src/CodeBlock.js @@ -1,14 +1,54 @@ +const hljs = require('highlight.js'); const GitBook = require('gitbook-core'); const { React } = GitBook; +const getLanguage = require('./getLanguage'); + +/** + * Get children as text + * @param {React.Children} children + * @return {String} + */ +function getChildrenToText(children) { + return React.Children.map(children, child => { + if (typeof child === 'string') { + return child; + } else { + return child.props.children ? + getChildrenToText(child.props.children) : ''; + } + }).join(''); +} + const CodeBlock = React.createClass({ propTypes: { - children: React.PropTypes.children + children: React.PropTypes.node, + className: React.PropTypes.string }, render() { - const { children } = this.props; - return <span />; + const { children, className } = this.props; + const content = getChildrenToText(children); + const lang = getLanguage(className); + + const includeCSS = <GitBook.ImportCSS href="gitbook/highlight/white.css" />; + + try { + const html = hljs.highlight(lang, content).value; + return ( + <code> + {includeCSS} + <span dangerouslySetInnerHTML={{__html: html}} /> + </code> + ); + } catch (e) { + return ( + <code> + {includeCSS} + {content} + </code> + ); + } } }); |