Skip to content

Commit 5066a00

Browse files
committed
fix: remove img regex
1 parent a2ab5cc commit 5066a00

File tree

3 files changed

+26
-13
lines changed

3 files changed

+26
-13
lines changed

docs/getting-started/authoring.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ title: Authoring
5656
<details>
5757
<summary>Result (with double quotes)</summary>
5858

59-
<img src="./gutenberg.jpg" />
59+
<img src="gutenberg.jpg" />
6060

6161
</details>
6262

src/components/mdx/Img/rehypeImg.ts

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,33 @@
1+
import resolveMdxUrl from '@/utils/resolveMdxUrl'
12
import type { Root } from 'hast'
23
import { visit } from 'unist-util-visit'
34

5+
import type { MdxJsxAttribute } from 'mdast-util-mdx-jsx'
6+
47
// https://unifiedjs.com/learn/guide/create-a-rehype-plugin/
5-
export function rehypeImg() {
6-
return (tree: Root) => {
8+
export function rehypeImg(
9+
relFilePath: Parameters<typeof resolveMdxUrl>[1],
10+
MDX_BASEURL: Parameters<typeof resolveMdxUrl>[2],
11+
) {
12+
return () => (tree: Root) => {
713
visit(tree, null, function (node) {
814
// console.log(node)
9-
if (node.type === 'mdxJsxFlowElement' && node.name === 'img') node.name = 'Img' // map HTML <img> to <Img> React component
15+
if (node.type === 'mdxJsxFlowElement' && node.name === 'img') {
16+
node.name = 'Img' // map HTML <img> to <Img> React component
17+
18+
//
19+
// Resolve relative URLs
20+
//
21+
22+
const srcAttr = (
23+
node.attributes.filter(({ type }) => type === 'mdxJsxAttribute') as MdxJsxAttribute[]
24+
).find((attr) => attr.name === 'src')
25+
26+
if (srcAttr) {
27+
const src = srcAttr.value
28+
if (typeof src === 'string') srcAttr.value = resolveMdxUrl(src, relFilePath, MDX_BASEURL)
29+
}
30+
}
1031
})
1132
}
1233
}

src/utils/docs.tsx

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,14 +142,6 @@ async function _getDocs(
142142
// inline images
143143
//
144144

145-
content = content.replace(
146-
/(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
147-
(_input, prefix: string, src: string, suffix: string) => {
148-
const url = resolveMdxUrl(src, relFilePath, MDX_BASEURL)
149-
return `${prefix}${url}${suffix}`
150-
},
151-
)
152-
153145
const boxes: string[] = []
154146
const tableOfContents: DocToC[] = []
155147

@@ -159,7 +151,7 @@ async function _getDocs(
159151
mdxOptions: {
160152
remarkPlugins: [remarkGFM],
161153
rehypePlugins: [
162-
rehypeImg,
154+
rehypeImg(relFilePath, MDX_BASEURL),
163155
rehypeDetails,
164156
rehypeSummary,
165157
rehypeGha,

0 commit comments

Comments
 (0)