code-hike / bright

React Server Component for syntax highlighting
https://bright.codehike.org
1.43k stars 18 forks source link

Attempting to adjust 'code' in mdx-components breaks #37

Closed jer-k closed 6 months ago

jer-k commented 8 months ago

Following the instructions from https://bright.codehike.org/

import { Code } from "bright"

// You need this file to use MDX in server components // Learn more from the Next.js docs

export function useMDXComponents(components) { return { ...components, pre: Code } }

I set this up and it is working great. I have .mdx files where I'll do

here is some text `some_file_name.txt` some text

and it renders the HTML as <p>here is some text<code>some_file_name.txt</code> some text</p>. I was trying to figure out how to change the styling of the <code> tags. I followed the Next Mdx guide and did something simple like

code: ({children}) => <div>{children}</div>,

This breaks when bright has been imported. When bright is no imported, it works as expected (albeit looking quite weird).

Some related issues seem to be

The error I see

Unhandled Runtime Error
Error: Cannot read properties of undefined (reading 'children')

Call Stack
children
node_modules/bright/dist/index.mjs (516:44)
Array.map
<anonymous>
map
node_modules/bright/dist/index.mjs (512:54)

I am using https://github.com/code-hike/bright/releases/tag/bright%400.8.4

jer-k commented 8 months ago

This seems to be caused by the way that MDX renders. https://mdxjs.com/table-of-components/ we can see

image

that single backticks renders <code> as well as triple backtick doing a <pre> and a <code>. When I console log what is being the props are from here https://github.com/code-hike/bright/blob/main/lib/src/index.tsx#L200 I get

what is c.props {
  className: 'language-js',
  children: 'let hello = "hello brightness"\nconsole.log(hello, "my old friend")\n'
}

I added a change to make the code look like

    const subProps = React.Children.toArray(children as any).map((c: any) => {
      let codeProps = c.props?.children?.props
      if (!codeProps) {
        codeProps = c.props;
      }
      return {
        code: trimTrailingNewline(codeProps.children),
        ...getLanguageAndTitle(codeProps.className),
      }
    })
    return {
      subProps,
    }

In mdx-components I have

export function useMDXComponents(components: MDXComponents) {
  return { ...components, pre: Code, code: ({children}) => <code>{children}</code>  }
}

The demo page has

image

The result is

image

Not sure if this change would break other things?

pomber commented 6 months ago

Thanks for reporting and researching. Should be fixed on v0.8.5.

okorie2 commented 1 month ago

@pomber I use v0.8.5 and still experience same issue.