Skip to content

Commit

Permalink
refactor: move children utils to own file
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Oct 16, 2020
1 parent 3beeeb8 commit 74b219e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 31 deletions.
33 changes: 2 additions & 31 deletions src/components/Tutorial.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React, { Children, cloneElement, isValidElement } from 'react';
import React, { Children } from 'react';
import PropTypes from 'prop-types';
import { isCodeBlock, isShellCommand, hasFileName } from '../utils/codeBlock';
import { isMdxType } from '../utils/mdx';
import { diffLines } from 'diff';
import useOnMount from '../hooks/useOnMount';
import TutorialEditor from './TutorialEditor';
import { reduceChildren, visit } from '../utils/children';

const Tutorial = ({ children }) => {
children = Children.toArray(children);
Expand Down Expand Up @@ -59,36 +60,6 @@ const parseProjectStateFromChildren = (children) => {
return project;
};

const visit = (children, guard, fn, parent = null) => {
Children.toArray(children).forEach((child, idx) => {
if (guard(child, idx, parent)) {
fn(child, idx, parent);
} else if (child.props?.children) {
visit(child.props.children, guard, fn, child);
}
});
};

const reduceChildren = (children, select, reducer, parent = null) => {
if (typeof children === 'string') {
return children;
}

return Children.map(children, (child, idx) => {
if (select(child, idx, parent)) {
return reducer(child, idx, parent);
}

if (child.props?.children) {
return cloneElement(child, {
children: reduceChildren(child.props.children, select, reducer, child),
});
}

return child;
});
};

const updateCodeBlocks = (children, project) => {
return reduceChildren(children, isProjectCodeBlock, (codeBlock) => {
const { fileName, code, ...props } = extractCodeBlockProps(codeBlock);
Expand Down
31 changes: 31 additions & 0 deletions src/utils/children.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Children, cloneElement } from 'react';

export const visit = (children, guard, fn, parent = null) => {
Children.toArray(children).forEach((child, idx) => {
if (guard(child, idx, parent)) {
fn(child, idx, parent);
} else if (child.props?.children) {
visit(child.props.children, guard, fn, child);
}
});
};

export const reduceChildren = (children, select, reducer, parent = null) => {
if (typeof children === 'string') {
return children;
}

return Children.map(children, (child, idx) => {
if (select(child, idx, parent)) {
return reducer(child, idx, parent);
}

if (child.props?.children) {
return cloneElement(child, {
children: reduceChildren(child.props.children, select, reducer, child),
});
}

return child;
});
};

0 comments on commit 74b219e

Please sign in to comment.