diff --git a/src/components/CodeHighlight.js b/src/components/CodeHighlight.js index 4819d1fdd..9e922795f 100644 --- a/src/components/CodeHighlight.js +++ b/src/components/CodeHighlight.js @@ -4,54 +4,84 @@ import cx from 'classnames'; import Highlight from 'prism-react-renderer'; import Prism from 'prismjs'; import styles from './CodeHighlight.module.scss'; +import { partition, range } from '../utils/array'; const CodeHighlight = ({ className, children, + highlightedLines: highlightedLineString, language, lineNumbers, wrap, -}) => ( - - {({ tokens, getLineProps, getTokenProps }) => { - const lineNumberWidth = String(tokens.length).length; +}) => { + const highlightedLines = getHighlightedLines(highlightedLineString); - return ( -
-          
-            {tokens.map((line, i) => (
-              // eslint-disable-next-line react/jsx-key
-              
- {lineNumbers && ( -
{i + 1}
- )} -
- {line.map((token, key) => ( - // eslint-disable-next-line react/jsx-key - - ))} + return ( + + {({ tokens, getLineProps, getTokenProps }) => { + const lineNumberWidth = String(tokens.length).length; + + return ( +
+            
+              {tokens.map((line, i) => (
+                // eslint-disable-next-line react/jsx-key
+                
+ {lineNumbers && ( +
{i + 1}
+ )} +
+ {line.map((token, key) => ( + // eslint-disable-next-line react/jsx-key + + ))} +
-
- ))} - -
- ); - }} -
-); + ))} + + + ); + }} + + ); +}; + +const getHighlightedLines = (highlightedLineString) => { + if (!highlightedLineString) { + return new Set(); + } + + const groups = highlightedLineString.split(',').map((str) => str.trim()); + const [ranges, lines] = partition(groups, (group) => group.includes('-')); + + const lineRanges = ranges + .map((range) => range.split('-').map(Number)) + .reduce((acc, [a, b]) => acc.concat(range(a, b)), []); + + return new Set(lines.map(Number).concat(lineRanges)); +}; CodeHighlight.propTypes = { className: PropTypes.string, children: PropTypes.string.isRequired, + highlightedLines: PropTypes.string, language: PropTypes.string, lineNumbers: PropTypes.bool, wrap: PropTypes.bool,