@@ -2,7 +2,45 @@ import resolveMdxUrl from '@/utils/resolveMdxUrl'
2
2
import type { Root } from 'hast'
3
3
import { visit } from 'unist-util-visit'
4
4
5
- import type { MdxJsxAttribute } from 'mdast-util-mdx-jsx'
5
+ //
6
+ // MD image
7
+ //
8
+ // 
9
+ //
10
+ // {
11
+ // type: 'element',
12
+ // tagName: 'img',
13
+ // properties: { src: 'basic-example.gif', alt: '' },
14
+ // children: [],
15
+ // position: {
16
+ // start: { line: 1, column: 1, offset: 0 },
17
+ // end: { line: 1, column: 23, offset: 22 }
18
+ // }
19
+ // }
20
+
21
+ //
22
+ // HTML image
23
+ //
24
+ // <img src="basic-example.gif" />
25
+ //
26
+ // {
27
+ // type: 'mdxJsxFlowElement',
28
+ // name: 'img',
29
+ // attributes: [
30
+ // {
31
+ // type: 'mdxJsxAttribute',
32
+ // name: 'src',
33
+ // value: 'basic-example.gif',
34
+ // position: [Object]
35
+ // }
36
+ // ],
37
+ // position: {
38
+ // start: { line: 3, column: 1, offset: 2 },
39
+ // end: { line: 3, column: 32, offset: 33 }
40
+ // },
41
+ // data: { _mdxExplicitJsx: true },
42
+ // children: []
43
+ // }
6
44
7
45
// https://unifiedjs.com/learn/guide/create-a-rehype-plugin/
8
46
export function rehypeImg (
@@ -11,21 +49,40 @@ export function rehypeImg(
11
49
) {
12
50
return ( ) => ( tree : Root ) => {
13
51
visit ( tree , null , function ( node ) {
14
- // console.log(node)
15
- if ( node . type === 'mdxJsxFlowElement' && node . name === 'img' ) {
16
- node . name = 'Img' // map HTML <img> to <Img> React component
52
+ // console.log('node', node)
53
+
54
+ const isMDImage = 'tagName' in node && node . tagName === 'img'
55
+ const isHTMLImage = 'name' in node && node . name === 'img'
56
+
57
+ if ( isMDImage ) {
58
+ node . tagName = 'Img' // map to <Img> React component
59
+
60
+ //
61
+ // Resolve relative URLs
62
+ //
63
+
64
+ const oldSrc = node . properties . src
65
+ if ( typeof oldSrc === 'string' ) {
66
+ node . properties . src = resolveMdxUrl ( oldSrc , relFilePath , MDX_BASEURL )
67
+ }
68
+ }
69
+
70
+ if ( isHTMLImage ) {
71
+ node . name = 'Img' // map to <Img> React component
17
72
18
73
//
19
74
// Resolve relative URLs
20
75
//
21
76
22
- const srcAttr = (
23
- node . attributes . filter ( ( { type } ) => type === 'mdxJsxAttribute' ) as MdxJsxAttribute [ ]
24
- ) . find ( ( attr ) => attr . name === 'src' )
77
+ const srcAttr = node . attributes
78
+ . filter ( ( node ) => 'name' in node )
79
+ . find ( ( attr ) => attr . name === 'src' )
25
80
26
81
if ( srcAttr ) {
27
- const src = srcAttr . value
28
- if ( typeof src === 'string' ) srcAttr . value = resolveMdxUrl ( src , relFilePath , MDX_BASEURL )
82
+ const oldSrc = srcAttr ?. value
83
+
84
+ if ( typeof oldSrc === 'string' )
85
+ srcAttr . value = resolveMdxUrl ( oldSrc , relFilePath , MDX_BASEURL )
29
86
}
30
87
}
31
88
} )
0 commit comments