Created
March 24, 2023 06:31
-
-
Save abhishekjakhar/2f84ce1eb34692fe888b0d97d8da9d44 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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