1
1
import { visit } from 'unist-util-visit' ;
2
2
import { Node , Paragraph , Parents } from 'mdast' ;
3
+ import { MdxJsxFlowElement } from 'mdast-util-mdx' ;
3
4
4
5
import { NodeTypes } from '../../enums' ;
5
6
import { ImageBlock } from '../../types' ;
7
+ import { getAttrs } from '../utils' ;
8
+ import { mdast } from '../../lib' ;
6
9
7
- const imageTransformer = ( ) => {
8
- return ( tree : Node ) => {
9
- visit ( tree , 'paragraph' , ( node : Paragraph , i : number , parent : Parents ) => {
10
- // check if inline or already transformed
11
- if ( parent . type !== 'root' || node . children ?. length > 1 || node . children [ 0 ] . type !== 'image' ) return ;
12
- const [ { alt, url, title } ] = node . children as any ;
13
-
14
- const newNode = {
15
- type : NodeTypes . imageBlock ,
16
- alt,
17
- title,
18
- url,
19
- data : {
20
- hName : 'img' ,
21
- hProperties : {
22
- ...( alt && { alt } ) ,
23
- src : url ,
24
- ...( title && { title } ) ,
25
- } ,
10
+ const imageTransformer = ( ) => ( tree : Node ) => {
11
+ visit ( tree , 'paragraph' , ( node : Paragraph , i : number , parent : Parents ) => {
12
+ // check if inline
13
+ if (
14
+ parent . type !== 'root' ||
15
+ node . children ?. length > 1 ||
16
+ node . children [ 0 ] . type !== 'image'
17
+ )
18
+ return ;
19
+
20
+ const [ { alt, url, title } ] = node . children as any ;
21
+
22
+ const newNode = {
23
+ type : NodeTypes . imageBlock ,
24
+ alt,
25
+ title,
26
+ url,
27
+ children : [ ] ,
28
+ data : {
29
+ hName : 'img' ,
30
+ hProperties : {
31
+ ...( alt && { alt } ) ,
32
+ src : url ,
33
+ ...( title && { title } ) ,
26
34
} ,
27
- position : node . position ,
28
- } as ImageBlock ;
35
+ } ,
36
+ position : node . position ,
37
+ } as ImageBlock ;
38
+
39
+ parent . children . splice ( i , 1 , newNode ) ;
40
+ } ) ;
41
+
42
+ const isImage = ( node : MdxJsxFlowElement ) => node . name === 'Image' ;
43
+
44
+ visit ( tree , isImage , ( node : MdxJsxFlowElement ) => {
45
+ const attrs = getAttrs < ImageBlock [ 'data' ] [ 'hProperties' ] > ( node ) ;
46
+
47
+ if ( attrs . caption ) {
48
+ node . children = mdast ( attrs . caption ) . children ;
49
+ }
50
+
51
+ } ) ;
29
52
30
- parent . children . splice ( i , 1 , newNode ) ;
31
- } ) ;
32
- } ;
53
+ return tree ;
33
54
} ;
34
55
35
56
export default imageTransformer ;
0 commit comments