forked from graphprotocol/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremarkReplaceImages.ts
33 lines (31 loc) · 1.11 KB
/
remarkReplaceImages.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { Root } from 'mdast'
import { Plugin } from 'unified'
import { visit } from 'unist-util-visit'
export const remarkReplaceImages: Plugin<[{ assetsBasePath: string }], Root> = ({ assetsBasePath }) => {
if (!assetsBasePath) throw new Error('remarkReplaceLinks: assetsBasePath is required')
return (tree, _file, done) => {
visit(
tree,
[
{ type: 'mdxJsxTextElement', name: 'img' },
{ type: 'mdxJsxFlowElement', name: 'img' },
],
(node: any) => {
const attrs = node.attributes as { name: string; value: string }[]
const srcAttr = attrs.find((attr) => attr.name === 'src')!
if (srcAttr.value.includes('.gitbook/assets/')) {
srcAttr.value = srcAttr.value.replace(
/.*\.gitbook\/assets\//,
`https://raw.githubusercontent.com/${assetsBasePath}.gitbook/assets/`,
)
}
},
)
visit(tree, 'image', (node) => {
if (node.url.includes('../assets/')) {
node.url = node.url.replace(/.*\.\.\/assets\//, `https://raw.githubusercontent.com/${assetsBasePath}assets/`)
}
})
done()
}
}