Skip to content

Commit

Permalink
Create ShikiHihlighter component and use it in CodeHighlight
Browse files Browse the repository at this point in the history
`ShikiHihlighter` uses the `useShiki` hook to highlight code and provides a component to easily use syntax highlighting

The `ShikiHihlighter` component is then used in `CodeHighlight`, where `isInline` is used to determine what to render.
  • Loading branch information
AVGVSTVS96 committed Jun 29, 2024
1 parent f9dffe6 commit 33bda0e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 18 deletions.
25 changes: 7 additions & 18 deletions src/components/ChatUI/CodeHighlight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import type { ReactNode } from 'react';
import type { BundledLanguage } from 'shiki';
import type { Element } from 'hast';
import { isInlineCode } from '@utils/isInlineCode';
import { useShikiHighlighter } from '@hooks/useShiki';

import { ShikiHighlighter } from './ShikiHihlighter';

interface CodeHighlightProps {
className?: string | undefined;
Expand All @@ -17,28 +16,18 @@ export const CodeHighlight = ({
node,
...props
}: CodeHighlightProps): JSX.Element => {
const theme = 'houston';
const code = String(children);
const match = className?.match(/language-(\w+)/);
const language = match ? (match[1] as BundledLanguage) : undefined;

const isInline: boolean | undefined = node ? isInlineCode(node) : undefined;

const highlightedCode: ReactNode | null = useShikiHighlighter(
code,
language,
theme,
);

return !isInline ? (
<div className='relative'>
{language ? (
<span className='absolute right-3 top-2 text-xs tracking-tighter text-muted-foreground/85'>
{language}
</span>
) : null}
{highlightedCode}
</div>
<ShikiHighlighter
language={language as BundledLanguage}
theme={'houston'}
{...props}>
{String(children)}
</ShikiHighlighter>
) : (
<code className={className} {...props}>
{children}
Expand Down
34 changes: 34 additions & 0 deletions src/components/ChatUI/ShikiHihlighter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type React from 'react';
import { useShikiHighlighter } from '@/hooks/useShiki';
import type { BundledTheme, BundledLanguage } from 'shiki';

interface ShikiHighlighterProps {
language: BundledLanguage;
children: string;
theme: BundledTheme;
PreTag?: keyof JSX.IntrinsicElements;
}

export const ShikiHighlighter: React.FC<ShikiHighlighterProps> = ({
language,
children,
theme,
PreTag = 'pre',
}) => {
const highlightedCode = useShikiHighlighter(
children,
language,
theme,
);

return (
<PreTag className="shiki not-prose relative [&_pre]:overflow-auto [&_pre]:rounded-lg [&_pre]:px-6 [&_pre]:py-5">
{language ? (
<span className="absolute right-3 top-2 text-xs tracking-tighter text-muted-foreground/85">
{language}
</span>
) : null}
{highlightedCode}
</PreTag>
);
};

0 comments on commit 33bda0e

Please sign in to comment.