From 6ec9195d83a45e9c76b84fe3993a449f298e96a3 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Tue, 1 Feb 2022 00:17:08 +0530 Subject: [PATCH] fix: normalize img src --- src/node/markdown/markdown.ts | 2 ++ src/node/markdown/plugins/image.ts | 15 +++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 src/node/markdown/plugins/image.ts diff --git a/src/node/markdown/markdown.ts b/src/node/markdown/markdown.ts index 1fdb926814ae..4f3e0b7eca54 100644 --- a/src/node/markdown/markdown.ts +++ b/src/node/markdown/markdown.ts @@ -11,6 +11,7 @@ import { hoistPlugin } from './plugins/hoist' import { preWrapperPlugin } from './plugins/preWrapper' import { linkPlugin } from './plugins/link' import { headingPlugin } from './plugins/headings' +import { imagePlugin } from './plugins/image' import { Header } from '../shared' import anchor from 'markdown-it-anchor' import attrs from 'markdown-it-attrs' @@ -66,6 +67,7 @@ export const createMarkdownRenderer = ( .use(hoistPlugin) .use(containerPlugin) .use(headingPlugin) + .use(imagePlugin) .use(linkPlugin, { target: '_blank', rel: 'noopener noreferrer', diff --git a/src/node/markdown/plugins/image.ts b/src/node/markdown/plugins/image.ts new file mode 100644 index 000000000000..641a04c71c99 --- /dev/null +++ b/src/node/markdown/plugins/image.ts @@ -0,0 +1,15 @@ +// markdown-it plugin for normalizing image source + +import MarkdownIt from 'markdown-it' +import { EXTERNAL_URL_RE } from '../../shared' + +export const imagePlugin = (md: MarkdownIt) => { + md.renderer.rules.image = (tokens, idx, options, env, self) => { + const token = tokens[idx] + const url = token.attrGet('src') + if (url && !EXTERNAL_URL_RE.test(url) && !/^\.?\//.test(url)) { + token.attrSet('src', './' + url) + } + return self.renderToken(tokens, idx, options) + } +}