Skip to content

Commit

Permalink
fix(rehypeImg): differentiate md image from html ones
Browse files Browse the repository at this point in the history
  • Loading branch information
abernier committed Aug 28, 2024
1 parent df2b1a9 commit 87c19c3
Showing 1 changed file with 66 additions and 9 deletions.
75 changes: 66 additions & 9 deletions src/components/mdx/Img/rehypeImg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,45 @@ import resolveMdxUrl from '@/utils/resolveMdxUrl'
import type { Root } from 'hast'
import { visit } from 'unist-util-visit'

import type { MdxJsxAttribute } from 'mdast-util-mdx-jsx'
//
// MD image
//
// ![](basic-example.gif)
//
// {
// type: 'element',
// tagName: 'img',
// properties: { src: 'basic-example.gif', alt: '' },
// children: [],
// position: {
// start: { line: 1, column: 1, offset: 0 },
// end: { line: 1, column: 23, offset: 22 }
// }
// }

//
// HTML image
//
// <img src="basic-example.gif" />
//
// {
// type: 'mdxJsxFlowElement',
// name: 'img',
// attributes: [
// {
// type: 'mdxJsxAttribute',
// name: 'src',
// value: 'basic-example.gif',
// position: [Object]
// }
// ],
// position: {
// start: { line: 3, column: 1, offset: 2 },
// end: { line: 3, column: 32, offset: 33 }
// },
// data: { _mdxExplicitJsx: true },
// children: []
// }

// https://unifiedjs.com/learn/guide/create-a-rehype-plugin/
export function rehypeImg(
Expand All @@ -11,21 +49,40 @@ export function rehypeImg(
) {
return () => (tree: Root) => {
visit(tree, null, function (node) {
// console.log(node)
if (node.type === 'mdxJsxFlowElement' && node.name === 'img') {
node.name = 'Img' // map HTML <img> to <Img> React component
// console.log('node', node)

const isMDImage = 'tagName' in node && node.tagName === 'img'
const isHTMLImage = 'name' in node && node.name === 'img'

if (isMDImage) {
node.tagName = 'Img' // map to <Img> React component

//
// Resolve relative URLs
//

const oldSrc = node.properties.src
if (typeof oldSrc === 'string') {
node.properties.src = resolveMdxUrl(oldSrc, relFilePath, MDX_BASEURL)
}
}

if (isHTMLImage) {
node.name = 'Img' // map to <Img> React component

//
// Resolve relative URLs
//

const srcAttr = (
node.attributes.filter(({ type }) => type === 'mdxJsxAttribute') as MdxJsxAttribute[]
).find((attr) => attr.name === 'src')
const srcAttr = node.attributes
.filter((node) => 'name' in node)
.find((attr) => attr.name === 'src')

if (srcAttr) {
const src = srcAttr.value
if (typeof src === 'string') srcAttr.value = resolveMdxUrl(src, relFilePath, MDX_BASEURL)
const oldSrc = srcAttr?.value

if (typeof oldSrc === 'string')
srcAttr.value = resolveMdxUrl(oldSrc, relFilePath, MDX_BASEURL)
}
}
})
Expand Down

0 comments on commit 87c19c3

Please sign in to comment.