Skip to content

Commit

Permalink
Add line highlighting for live code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
lex111 committed Oct 22, 2019
1 parent a200e47 commit a2947a4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
1 change: 1 addition & 0 deletions packages/docusaurus-theme-live-codeblock/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@philpl/buble": "^0.19.7",
"classnames": "^2.2.6",
"clipboard": "^2.0.4",
"parse-numeric-range": "^0.0.2",
"prism-react-renderer": "^1.0.1",
"react-live": "^2.1.2"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,20 @@ import classnames from 'classnames';
import Highlight, {defaultProps} from 'prism-react-renderer';
import defaultTheme from 'prism-react-renderer/themes/palenight';
import Clipboard from 'clipboard';
import rangeParser from 'parse-numeric-range';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import Playground from '@theme/Playground';
import styles from './styles.module.css';

export default ({children, className: languageClassName, live, ...props}) => {
const highlightLinesRangeRegex = /{([\d,-]+)}/;

export default ({
children,
className: languageClassName,
live,
metastring,
...props
}) => {
const {
siteConfig: {
themeConfig: {prismTheme},
Expand All @@ -23,6 +32,12 @@ export default ({children, className: languageClassName, live, ...props}) => {
const [showCopied, setShowCopied] = useState(false);
const target = useRef(null);
const button = useRef(null);
let highlightLines = [];

if (metastring && highlightLinesRangeRegex.test(metastring)) {
const highlightLinesRange = metastring.match(highlightLinesRangeRegex)[1];
highlightLines = rangeParser.parse(highlightLinesRange).filter(n => n > 0);
}

useEffect(() => {
let clipboard;
Expand Down Expand Up @@ -73,13 +88,21 @@ export default ({children, className: languageClassName, live, ...props}) => {
ref={target}
className={classnames(className, styles.codeBlock)}
style={style}>
{tokens.map((line, i) => (
<div key={i} {...getLineProps({line, key: i})}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({token, key})} />
))}
</div>
))}
{tokens.map((line, i) => {
const lineProps = getLineProps({line, key: i});

if (highlightLines.includes(i + 1)) {
lineProps.className = `${lineProps.className} highlight-line`;
}

return (
<div key={i} {...lineProps}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({token, key})} />
))}
</div>
);
})}
</pre>
<button
ref={button}
Expand Down

0 comments on commit a2947a4

Please sign in to comment.