Skip to content

Commit

Permalink
feat: highlight lines that are new
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Oct 14, 2020
1 parent ed33c14 commit c484371
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@xstate/react": "^1.0.0-rc.6",
"classnames": "^2.2.6",
"date-fns": "^2.16.1",
"diff": "^4.0.2",
"eslint-plugin-react-hooks": "^4.1.2",
"gatsby": "^2.24.2",
"gatsby-image": "^2.4.14",
Expand Down
8 changes: 7 additions & 1 deletion src/components/Tutorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Children, cloneElement } from 'react';
import PropTypes from 'prop-types';
import parseCodeBlockProps from '../utils/parseCodeBlockProps';
import { isCodeBlock, isShellCommand } from '../utils/codeBlock';
import { diffLines } from 'diff';

const Tutorial = ({ children }) => {
children = Children.toArray(children);
Expand Down Expand Up @@ -34,12 +35,17 @@ const Tutorial = ({ children }) => {
);

const { fileName, code, language } = parseCodeBlockProps(codeBlock);
const { code: prevCode } = previousStep.get(fileName);

return [
...steps,
cloneElement(stepElement, {
initialSelectedFile: fileName,
step: previousStep.set(fileName, { code, language }),
step: previousStep.set(fileName, {
code,
language,
diff: diffLines(prevCode, code),
}),
index: idx,
totalSteps: arr.length,
children: Children.toArray(stepElement.props.children).filter(
Expand Down
26 changes: 25 additions & 1 deletion src/components/TutorialEditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,28 @@ import { darken } from 'polished';

const TutorialEditor = ({ initialSelectedFile, files }) => {
const [selectedFile, setSelectedFile] = useState(initialSelectedFile);
const { language, code } = files.get(selectedFile);
const { diff } = files.get(selectedFile);

const [highlightedLines] = diff.reduce(
([highlightedLines, lineNumber], change) => {
const { count, added, removed } = change;
// Include current line when counting the end of the range
const rangeEnd = lineNumber + count - 1;

return [
added
? [
...highlightedLines,
lineNumber === rangeEnd
? lineNumber
: `${lineNumber}-${lineNumber + count - 1}`,
]
: highlightedLines,
removed ? lineNumber : lineNumber + count,
];
},
[[], 1]
);

return (
<div>
Expand Down Expand Up @@ -47,6 +68,9 @@ const TutorialEditor = ({ initialSelectedFile, files }) => {
lineNumbers
language={language}
fileName={fileName}
highlightedLines={
fileName === selectedFile ? highlightedLines.join(',') : null
}
css={css`
display: ${fileName === selectedFile ? 'block' : 'none'};
Expand Down

0 comments on commit c484371

Please sign in to comment.