From b5986e833a4524724b2901fd3c54e3fef6ceaa6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samy=20Pess=C3=A9?= Date: Wed, 24 Jan 2024 14:02:16 +0100 Subject: [PATCH] Fix optimized image size when using inline image (#116) --- src/components/DocumentView/InlineImage.tsx | 45 ++++++++++++++------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/src/components/DocumentView/InlineImage.tsx b/src/components/DocumentView/InlineImage.tsx index 8efef6013..2ad61437e 100644 --- a/src/components/DocumentView/InlineImage.tsx +++ b/src/components/DocumentView/InlineImage.tsx @@ -1,5 +1,8 @@ import { DocumentInlineImage } from '@gitbook/api'; +import { getImageSize } from '@/lib/images'; +import { ResolvedContentRef } from '@/lib/references'; + import { InlineProps } from './Inline'; import { Image } from '../utils'; @@ -18,20 +21,7 @@ export async function InlineImage(props: InlineProps) { return ( {inline.data.caption) { /> ); } + +async function getImageSizes(inline: DocumentInlineImage, src: ResolvedContentRef) { + if (inline.data.size === 'original') { + // The max-width is 300px + return [ + { + width: 300, + }, + ]; + } + + // We estimate that the maximum height of the line will be 40px + // and from the aspect-ratio, we can deduce the width + const lineHeight = 40; + const imageSize = + src.fileDimensions ?? + (await getImageSize(src.href, { + dpr: 3, + })); + const aspectRatio = imageSize ? imageSize.width / imageSize.height : 1; + + return [ + { + width: Math.floor(lineHeight * aspectRatio), + }, + ]; +}