Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can rehypeStarryNight be used in react-markdown? #39

Closed
caihai123 opened this issue Mar 26, 2024 · 2 comments
Closed

Can rehypeStarryNight be used in react-markdown? #39

caihai123 opened this issue Mar 26, 2024 · 2 comments

Comments

@caihai123
Copy link

/**
 * @typedef {import('@wooorm/starry-night').Grammar} Grammar
 * @typedef {import('hast').ElementContent} ElementContent
 * @typedef {import('hast').Root} Root
 */

/**
 * @typedef Options
 *   Configuration (optional)
 * @property {Array<Grammar> | null | undefined} [grammars]
 *   Grammars to support (default: `common`).
 */

import {common, createStarryNight} from '@wooorm/starry-night'
import {toString} from 'hast-util-to-string'
import {visit} from 'unist-util-visit'

/**
 * Highlight code with `starry-night`.
 *
 * @param {Options | null | undefined} [options]
 *   Configuration (optional).
 * @returns
 *   Transform.
 */
export default function rehypeStarryNight(options) {
  const settings = options || {}
  const grammars = settings.grammars || common
  const starryNightPromise = createStarryNight(grammars)
  const prefix = 'language-'

  /**
   * Transform.
   *
   * @param {Root} tree
   *   Tree.
   * @returns {Promise<undefined>}
   *   Nothing.
   */
  return async function (tree) {
    const starryNight = await starryNightPromise

    visit(tree, 'element', function (node, index, parent) {
      if (!parent || index === undefined || node.tagName !== 'pre') {
        return
      }

      const head = node.children[0]

      if (!head || head.type !== 'element' || head.tagName !== 'code') {
        return
      }

      const classes = head.properties.className

      if (!Array.isArray(classes)) return

      const language = classes.find(function (d) {
        return typeof d === 'string' && d.startsWith(prefix)
      })

      if (typeof language !== 'string') return

      const scope = starryNight.flagToScope(language.slice(prefix.length))

      // Maybe warn?
      if (!scope) return

      const fragment = starryNight.highlight(toString(head), scope)
      const children = /** @type {Array<ElementContent>} */ (fragment.children)

      parent.children.splice(index, 1, {
        type: 'element',
        tagName: 'div',
        properties: {
          className: [
            'highlight',
            'highlight-' + scope.replace(/^source\./, '').replace(/\./g, '-')
          ]
        },
        children: [{type: 'element', tagName: 'pre', properties: {}, children}]
      })
    })
  }
}

The code above is copied from the current project. Can this code be used in react-markdown?

<ReactMarkdown
        remarkPlugins={[remarkGfm]}
        rehypePlugins={[rehypeStarryNight]}
        skipHtml={true}
        components={{
          pre: Pre,
        }}
      >
        {markdown}
      </ReactMarkdown>

Why do I encounter this error after using it: runSync finished async. Use run instead

@wooorm
Copy link
Owner

wooorm commented Mar 26, 2024

Not yet, because React doesn’t have the good stable primitives for async work.
There is an idea that we think will work, but needs someone to write the code.
See remarkjs/react-markdown#680 (comment).

You don‘t have to use react-markdown. It’s a small wrapper with convenience features for beginners.
You can also use the underlying tools yourself: https://github.com/rehypejs/rehype-react.

@wooorm wooorm closed this as not planned Won't fix, can't repro, duplicate, stale Mar 26, 2024
@caihai123
Copy link
Author

Ok, thank you for your reply!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants