rehype-pretty / rehype-pretty-code

Beautiful code blocks for Markdown or MDX.

Home Page:https://rehype-pretty.pages.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Preserve Whitespace

kennetpostigo opened this issue · comments

Hi I'm using Next.js 14 with rehype-pretty-code. I'm trying to highlight some code on the client, however I'm running into the case where whitespace isn't being preserved and i'm not sure why, I copied the server component example to ported it to run on the client:

export function Code({ code }: { code: string }) {
  const [highlightedCode, setHighlightedCode] = React.useState('');

  React.useEffect(() => {
    highlightCode(code).then(setHighlightedCode);
  }, [code]);

  return (
    <section
      dangerouslySetInnerHTML={{
        __html: highlightedCode,
      }}
    />
  );
}

async function highlightCode(code: string) {
  const file = await unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypePrettyCode, {
      defaultLang: 'plaintext',
      keepBackground: false,
      theme: { dark: 'github-light', light: 'github-light' },
    })
    .use(rehypeStringify)
    .process(code);

  return String(file);
}

It ends up rendering like so:
image

The provided code string was:

export const codeString = `
\`\`\`tsx
import { Button } from './Button';
import { XStack } from './XStack';

export const Component = () => {
  return (
    <XStack width="100%" justifyContent="space-around">
      <Button variant="primary" size="xs">
        <Button.Text>Button</Button.Text>
      </Button>

      <Button variant="primary" size="sm">
        <Button.Text>Button</Button.Text>
      </Button>

      <Button variant="primary" size="md">
        <Button.Text>Button</Button.Text>
      </Button>

      <Button variant="primary" size="lg">
        <Button.Text>Button</Button.Text>
      </Button>
    </XStack>
  );
};
\`\`\`
`;

What can I do to prevent whitespace from being removed when highlighting on the client?

Do you have a reproduction? I'm not sure what would cause this. The grid: true prop could cause a problem, but I don't see why here. Some alternative issue: #180