From 87c19c3878ce9b50fe4282f7282a0445154e309a Mon Sep 17 00:00:00 2001 From: Antoine BERNIER Date: Wed, 28 Aug 2024 10:59:18 +0200 Subject: [PATCH] fix(rehypeImg): differentiate md image from html ones --- src/components/mdx/Img/rehypeImg.ts | 75 +++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/src/components/mdx/Img/rehypeImg.ts b/src/components/mdx/Img/rehypeImg.ts index f8e60fab..5753637c 100644 --- a/src/components/mdx/Img/rehypeImg.ts +++ b/src/components/mdx/Img/rehypeImg.ts @@ -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 +// +// +// +// { +// 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( @@ -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 to 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 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 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) } } })