Skip to content

Commit

Permalink
feat: add CodeBlock component
Browse files Browse the repository at this point in the history
  • Loading branch information
axnir committed May 7, 2023
1 parent ed532aa commit 60e3135
Show file tree
Hide file tree
Showing 4 changed files with 301 additions and 6 deletions.
55 changes: 55 additions & 0 deletions app/components/ui/CodeBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { getHighlighter, Lang, renderToHtml } from 'shiki';
import type {
CodeBlockObjectResponse,
TextRichTextItemResponse,
} from '@notionhq/client/build/src/api-endpoints';
import SITE_CONFIG from '@/site.config';

const lightTheme = SITE_CONFIG.codeTheme.light;
const darkTheme = SITE_CONFIG.codeTheme.dark;

export default async function CodeBlock(
props: CodeBlockObjectResponse['code']
) {
const { rich_text, language } = props;

const highlighter = await getHighlighter({
themes: [lightTheme, darkTheme],
langs: [language as Lang],
});

const code = (rich_text as TextRichTextItemResponse[])
.map((i) => i.plain_text)
.join('');

const tokens = highlighter.codeToThemedTokens(code, language);
const renderToHTML = (theme: 'light' | 'dark'): string => {
const themeName = theme === 'light' ? lightTheme : darkTheme;
const html = renderToHtml(tokens, {
fg: highlighter.getForegroundColor(themeName),
bg: theme === 'light' ? '#f6f8fa' : '#0d1117',
themeName,
elements: {
pre({ style, children }) {
return `<pre class="rounded-md mb-6 p-3 text-sm" style="tab-size: 2; ${style}">${children}</pre>`;
},
code({ children }) {
return `<code>${children}</code>`;
},
},
});
return html;
};

// TODOsupport dark mode
const lightHtml = renderToHTML('light');
// const darkHtml = renderToHTML('dark');

return (
<div
dangerouslySetInnerHTML={{
__html: lightHtml,
}}
></div>
);
}
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
"next": "13.2.1",
"probe-image-size": "^7.2.3",
"react": "18.2.0",
"react-dom": "18.2.0"
"react-copy-to-clipboard": "^5.1.0",
"react-dom": "18.2.0",
"react-use": "^17.4.0",
"shiki": "^0.14.2"
},
"devDependencies": {
"@commitlint/cli": "^17.6.1",
Expand Down
Loading

0 comments on commit 60e3135

Please sign in to comment.