diff --git a/lib/replaceMdImages.ts b/lib/replaceMdImages.ts new file mode 100644 index 000000000..412a27fed --- /dev/null +++ b/lib/replaceMdImages.ts @@ -0,0 +1,44 @@ +export function replaceMdImages(content: string): string { + let newContent = content; + + newContent = replaceNormalImages(newContent); + newContent = replaceObsidianImages(newContent); + + return newContent; +} + +const normalImgRegex = /!\[(.*?)\]\((.*?)\)/g; +function replaceNormalImages(content: string): string { + const newContent = content.replace(normalImgRegex, (_, altText: string, imageUrl: string) => { + const [alt, size] = altText.split('|'); + + if (!size) return `${alt}`; + + const { width, height } = getImageSize(size); + return `${alt}`; + }); + + return newContent; +} + +const obsidianImgRegex = /!\[\[([^\]]*?)\]\]/g; +function replaceObsidianImages(content: string): string { + const newContent = content.replace(obsidianImgRegex, (match, imageUrl) => { + const [url, size] = imageUrl.split('|'); + + if (!size) return `image`; + + const { width, height } = getImageSize(size); + return `image`; + }); + + return newContent; +} + +function getImageSize(size: string): { width: string; height: string } { + let [width, height] = size.split('x'); + + if (!height) height = width; + + return { width, height }; +} diff --git a/pages/[[...slug]].tsx b/pages/[[...slug]].tsx index 1d893bdf5..9f1a1a1ea 100644 --- a/pages/[[...slug]].tsx +++ b/pages/[[...slug]].tsx @@ -9,6 +9,7 @@ import computeFields from "@/lib/computeFields"; import parse from "@/lib/markdown"; import siteConfig from "@/config/siteConfig"; import type { CustomAppProps } from "./_app"; +import { replaceMdImages } from "@/lib/replaceMdImages"; interface SlugPageProps extends CustomAppProps { source: any; @@ -62,7 +63,8 @@ export const getStaticProps: GetStaticProps = async ({ const frontMatter = dbFile!.metadata ?? {}; const source = fs.readFileSync(filePath, { encoding: "utf-8" }); - const { mdxSource } = await parse(source, "mdx", {}); + const newSource = replaceMdImages(source); + const { mdxSource } = await parse(newSource, "mdx", {}); // TODO temporary replacement for contentlayer's computedFields const frontMatterWithComputedFields = await computeFields({