From 5b629aa9b04e4f5c04754eca9ce2495b95efbbfd Mon Sep 17 00:00:00 2001 From: Antoine BERNIER Date: Thu, 29 Aug 2024 10:19:31 +0200 Subject: [PATCH] feat: allow 1 dim img --- docs/getting-started/authoring.mdx | 13 +++++++++++++ src/components/mdx/Img/Img.tsx | 29 ++++++++++++++++++++++------- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/docs/getting-started/authoring.mdx b/docs/getting-started/authoring.mdx index 3a5a7f3f..d1404b18 100644 --- a/docs/getting-started/authoring.mdx +++ b/docs/getting-started/authoring.mdx @@ -60,6 +60,19 @@ title: Authoring > > For others, think about adding them to **prevent layout shift**. +It is also possible to specify only one dimension (other is inferred from instrisic ratio), eg: + +```md + +``` + +
+ Result + + + +
+ > [!NOTE] > See [`MDX_BASEURL`](introduction#configuration:~:text=MDX_BASEURL) to understand how it is converted to a full URL. diff --git a/src/components/mdx/Img/Img.tsx b/src/components/mdx/Img/Img.tsx index a467f130..e3c6e418 100644 --- a/src/components/mdx/Img/Img.tsx +++ b/src/components/mdx/Img/Img.tsx @@ -4,16 +4,31 @@ import { ComponentProps } from 'react' import sizeOf from 'image-size' import { resolve } from 'path' -export async function Img({ src, alt = '', className, ...props }: ComponentProps<'img'>) { - const dims: Partial, 'width' | 'height'>> = { - width: undefined, - height: undefined, +export async function Img({ + src, + width, + height, + alt = '', + className, + ...props +}: ComponentProps<'img'>) { + const dims = { + width, + height, } + + // + // If image is from MDX folder, we can determine its dimensions + // + if (process.env.MDX_BASEURL && src?.startsWith(process.env.MDX_BASEURL)) { const path = resolve(src.replace(process.env.MDX_BASEURL, process.env.MDX!)) - const { width, height } = sizeOf(path) - dims.width = width - dims.height = height + const { width: w, height: h } = sizeOf(path) + const ratio = w && h ? w / h : undefined + + // If only one dimension is provided, calculate the other based on the image's aspect ratio + dims.width ??= height && ratio ? Number(height) * ratio : w + dims.height ??= width && ratio ? Number(width) / ratio : h } return (