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

fix: support multiple overridden syntax themes #1992

Merged
merged 16 commits into from
Aug 19, 2023
28 changes: 16 additions & 12 deletions packages/nextra/src/mdx-plugins/rehype.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import Slugger from 'github-slugger'
import { CODE_BLOCK_FILENAME_REGEX } from '../constants'
import { getFlattenedValue } from './remark-headings'

function visit(node, tagNames, handler) {
function visit(node, tagNames, handler, parent, idx) {
if (tagNames.includes(node.tagName)) {
handler(node)
handler(node, parent, idx)
return
}
node.children?.forEach(n => visit(n, tagNames, handler))
node.children?.forEach((n, i) => visit(n, tagNames, handler, node, i))
}

export const parseMeta =
Expand All @@ -34,20 +34,24 @@ export const attachMeta = () => tree => {

const headingsWithSlug = new Set(['h2', 'h3', 'h4', 'h5', 'h6'])

visit(tree, [...headingsWithSlug, 'div', 'pre'], node => {
visit(tree, [...headingsWithSlug, 'div', 'pre'], (node, parent, idx) => {
if (headingsWithSlug.has(node.tagName)) {
// Attach slug
node.properties.id ||= slugger.slug(getFlattenedValue(node))
return
}

if ('data-rehype-pretty-code-fragment' in node.properties) {
// remove <div data-rehype-pretty-code-fragment /> element that wraps <pre /> element
// because we'll wrap with our own <div />
Object.assign(node, node.children[0])
}

node.properties.filename = node.__nextra_filename
node.properties.hasCopyCode = node.__nextra_hasCopyCode
const children = "data-rehype-pretty-code-fragment" in node.properties
? node.children.map(child => ({ ...node, ...child }))
: [node];

children.forEach((node) => {
node.properties.filename = node.__nextra_filename;
node.properties.hasCopyCode = node.__nextra_hasCopyCode;
});
// if this is a <div data-rehype-pretty-code-fragment /> element,
// this flattens children that wraps <pre /> element(s) into sibling nodes
// because we'll wrap with our own <div />
parent.children.splice(idx, 1, ...children);
})
}