Skip to content

Instantly share code, notes, and snippets.

@abhishekjakhar
Created March 24, 2023 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishekjakhar/2f84ce1eb34692fe888b0d97d8da9d44 to your computer and use it in GitHub Desktop.
Save abhishekjakhar/2f84ce1eb34692fe888b0d97d8da9d44 to your computer and use it in GitHub Desktop.
import type { SandpackFile } from '@codesandbox/sandpack-react';
export const createFileMap = (codeSnippets: React.ReactElement[]) => {
return codeSnippets.reduce(
(result: Record<string, SandpackFile>, codeSnippet: React.ReactElement) => {
if (codeSnippet.type !== 'pre') {
return result;
}
const { props } = codeSnippet.props.children;
let filePath;
let fileHidden = false;
let fileActive = false;
if (props.meta) {
const [name, ...params] = props.meta.split(' ');
filePath = '/' + name;
if (params.includes('hidden')) {
fileHidden = true;
}
if (params.includes('active')) {
fileActive = true;
}
} else {
if (props.className === 'language-js') {
filePath = '/App.js';
} else if (props.className === 'language-css') {
filePath = '/styles.css';
} else {
throw new Error(
`Code block is missing a filename: ${props.children}`
);
}
}
if (result[filePath]) {
throw new Error(
`File ${filePath} was defined multiple times. Each file snippet should have a unique path name`
);
}
result[filePath] = {
code: (props.children || '') as string,
hidden: fileHidden,
active: fileActive,
};
return result;
},
{}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment