tldraw/apps/docs/components/mdx-components/code.tsx
Mime Čuvalo 430924f8b6
docs: better code snippets (#2801)
Uses sandpack in all places so we can do richer code snippets.
Also, drive-by fix to fix sidebar logic.
Also, drive-by fix to hide keyboard hint (Cmd+K) for search on mobile.

### Change Type

- [x] `documentation` — Changes to the documentation only[^2]

### Release Notes

- Docs: reworks code snippets
2024-02-12 14:30:55 +00:00

41 lines
1 KiB
TypeScript

'use client'
import { SandpackCodeViewer, SandpackFiles, SandpackProvider } from '@codesandbox/sandpack-react'
import { useTheme } from 'next-themes'
export const Code = (props: any) => {
if (!props.className) {
return <code {...props} />
}
const language = props.className.replace('language-', '')
return <CodeBlock code={{ [`App.${language}`]: props.children.trim() }} />
}
export function CodeBlock({ code }: { code: SandpackFiles }) {
const { theme } = useTheme()
const trimmedCode = Object.fromEntries(
Object.entries(code).map(([key, value]) => [key, (value as string).trim()])
)
return (
<div className="code-example">
<SandpackProvider
className="sandpack"
key={`sandpack-${theme}`}
template="react-ts"
options={{ activeFile: Object.keys(code)[0] }}
customSetup={{
dependencies: {
'@tldraw/assets': 'latest',
'@tldraw/tldraw': 'latest',
},
}}
files={trimmedCode}
theme={theme === 'dark' ? 'dark' : 'light'}
>
<SandpackCodeViewer />
</SandpackProvider>
</div>
)
}