From 5066a00e72d71744427bca3e93004ec5d5f2b8b1 Mon Sep 17 00:00:00 2001 From: Antoine BERNIER Date: Wed, 28 Aug 2024 02:21:53 +0200 Subject: [PATCH] fix: remove img regex --- docs/getting-started/authoring.mdx | 2 +- src/components/mdx/Img/rehypeImg.ts | 27 ++++++++++++++++++++++++--- src/utils/docs.tsx | 10 +--------- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/docs/getting-started/authoring.mdx b/docs/getting-started/authoring.mdx index 8080e236..c7b9a84f 100644 --- a/docs/getting-started/authoring.mdx +++ b/docs/getting-started/authoring.mdx @@ -56,7 +56,7 @@ title: Authoring
Result (with double quotes) - +
diff --git a/src/components/mdx/Img/rehypeImg.ts b/src/components/mdx/Img/rehypeImg.ts index ebfb5a5e..f8e60fab 100644 --- a/src/components/mdx/Img/rehypeImg.ts +++ b/src/components/mdx/Img/rehypeImg.ts @@ -1,12 +1,33 @@ +import resolveMdxUrl from '@/utils/resolveMdxUrl' import type { Root } from 'hast' import { visit } from 'unist-util-visit' +import type { MdxJsxAttribute } from 'mdast-util-mdx-jsx' + // https://unifiedjs.com/learn/guide/create-a-rehype-plugin/ -export function rehypeImg() { - return (tree: Root) => { +export function rehypeImg( + relFilePath: Parameters[1], + MDX_BASEURL: Parameters[2], +) { + 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 + if (node.type === 'mdxJsxFlowElement' && node.name === 'img') { + node.name = 'Img' // map HTML to React component + + // + // Resolve relative URLs + // + + const srcAttr = ( + node.attributes.filter(({ type }) => type === 'mdxJsxAttribute') as MdxJsxAttribute[] + ).find((attr) => attr.name === 'src') + + if (srcAttr) { + const src = srcAttr.value + if (typeof src === 'string') srcAttr.value = resolveMdxUrl(src, relFilePath, MDX_BASEURL) + } + } }) } } diff --git a/src/utils/docs.tsx b/src/utils/docs.tsx index 3f4ac8ab..386a157d 100644 --- a/src/utils/docs.tsx +++ b/src/utils/docs.tsx @@ -142,14 +142,6 @@ async function _getDocs( // inline images // - content = content.replace( - /(src="|\()(.+?\.(?:png|jpe?g|gif|webp|avif))("|\))/g, // https://regexper.com/#%2F%28src%3D%22%7C%5C%28%29%28.%2B%3F%5C.%28%3F%3Apng%7Cjpe%3Fg%7Cgif%7Cwebp%7Cavif%29%29%28%22%7C%5C%29%29%2Fg - (_input, prefix: string, src: string, suffix: string) => { - const url = resolveMdxUrl(src, relFilePath, MDX_BASEURL) - return `${prefix}${url}${suffix}` - }, - ) - const boxes: string[] = [] const tableOfContents: DocToC[] = [] @@ -159,7 +151,7 @@ async function _getDocs( mdxOptions: { remarkPlugins: [remarkGFM], rehypePlugins: [ - rehypeImg, + rehypeImg(relFilePath, MDX_BASEURL), rehypeDetails, rehypeSummary, rehypeGha,