Skip to content

Commit

Permalink
fix: remove img regex
Browse files Browse the repository at this point in the history
  • Loading branch information
abernier committed Aug 28, 2024
1 parent a2ab5cc commit 5066a00
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 13 deletions.
2 changes: 1 addition & 1 deletion docs/getting-started/authoring.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ title: Authoring
<details>
<summary>Result (with double quotes)</summary>

<img src="./gutenberg.jpg" />
<img src="gutenberg.jpg" />

</details>

Expand Down
27 changes: 24 additions & 3 deletions src/components/mdx/Img/rehypeImg.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
import resolveMdxUrl from '@/utils/resolveMdxUrl'
import type { Root } from 'hast'
import { visit } from 'unist-util-visit'

import type { MdxJsxAttribute } from 'mdast-util-mdx-jsx'

// https://unifiedjs.com/learn/guide/create-a-rehype-plugin/
export function rehypeImg() {
return (tree: Root) => {
export function rehypeImg(
relFilePath: Parameters<typeof resolveMdxUrl>[1],
MDX_BASEURL: Parameters<typeof resolveMdxUrl>[2],
) {
return () => (tree: Root) => {
visit(tree, null, function (node) {
// console.log(node)
if (node.type === 'mdxJsxFlowElement' && node.name === 'img') node.name = 'Img' // map HTML <img> to <Img> React component
if (node.type === 'mdxJsxFlowElement' && node.name === 'img') {
node.name = 'Img' // map HTML <img> to <Img> React component

//
// Resolve relative URLs
//

const srcAttr = (
node.attributes.filter(({ type }) => type === 'mdxJsxAttribute') as MdxJsxAttribute[]
).find((attr) => attr.name === 'src')

if (srcAttr) {
const src = srcAttr.value
if (typeof src === 'string') srcAttr.value = resolveMdxUrl(src, relFilePath, MDX_BASEURL)
}
}
})
}
}
10 changes: 1 addition & 9 deletions src/utils/docs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,14 +142,6 @@ async function _getDocs(
// inline images
//

content = content.replace(
/(src="|\()(.+?\.(?:png|jpe?g|gif|webp|avif))("|\))/g, // https://regexper.com/#%2F%28src%3D%22%7C%5C%28%29%28.%2B%3F%5C.%28%3F%3Apng%7Cjpe%3Fg%7Cgif%7Cwebp%7Cavif%29%29%28%22%7C%5C%29%29%2Fg
(_input, prefix: string, src: string, suffix: string) => {
const url = resolveMdxUrl(src, relFilePath, MDX_BASEURL)
return `${prefix}${url}${suffix}`
},
)

const boxes: string[] = []
const tableOfContents: DocToC[] = []

Expand All @@ -159,7 +151,7 @@ async function _getDocs(
mdxOptions: {
remarkPlugins: [remarkGFM],
rehypePlugins: [
rehypeImg,
rehypeImg(relFilePath, MDX_BASEURL),
rehypeDetails,
rehypeSummary,
rehypeGha,
Expand Down

0 comments on commit 5066a00

Please sign in to comment.