2022-10-07 13:55:39 +08:00
|
|
|
import { Parent, Node, Literal } from 'unist'
|
2022-07-17 21:40:41 +08:00
|
|
|
import { visit } from 'unist-util-visit'
|
|
|
|
import sizeOf from 'image-size'
|
|
|
|
import fs from 'fs'
|
|
|
|
|
2022-10-07 13:55:39 +08:00
|
|
|
type ImageNode = Parent & {
|
|
|
|
url: string
|
|
|
|
alt: string
|
|
|
|
name: string
|
|
|
|
attributes: (Literal & { name: string })[]
|
|
|
|
}
|
|
|
|
|
2022-07-17 21:40:41 +08:00
|
|
|
export default function remarkImgToJsx() {
|
2022-10-07 13:55:39 +08:00
|
|
|
return (tree: Node) => {
|
2022-07-17 21:40:41 +08:00
|
|
|
visit(
|
|
|
|
tree,
|
|
|
|
// only visit p tags that contain an img element
|
2022-10-07 13:55:39 +08:00
|
|
|
(node: Parent): node is Parent =>
|
|
|
|
node.type === 'paragraph' && node.children.some((n) => n.type === 'image'),
|
|
|
|
(node: Parent) => {
|
|
|
|
const imageNode = node.children.find((n) => n.type === 'image') as ImageNode
|
2022-07-17 21:40:41 +08:00
|
|
|
|
|
|
|
// only local files
|
|
|
|
if (fs.existsSync(`${process.cwd()}/public${imageNode.url}`)) {
|
|
|
|
const dimensions = sizeOf(`${process.cwd()}/public${imageNode.url}`)
|
|
|
|
|
|
|
|
// Convert original node to next/image
|
|
|
|
;(imageNode.type = 'mdxJsxFlowElement'),
|
|
|
|
(imageNode.name = 'Image'),
|
|
|
|
(imageNode.attributes = [
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'alt', value: imageNode.alt },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'src', value: imageNode.url },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'width', value: dimensions.width },
|
|
|
|
{ type: 'mdxJsxAttribute', name: 'height', value: dimensions.height },
|
|
|
|
])
|
|
|
|
|
|
|
|
// Change node type from p to div to avoid nesting error
|
|
|
|
node.type = 'div'
|
|
|
|
node.children = [imageNode]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|