From e9432c9486fb9d1de3cccedefab1570043379201 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samy=20Pess=C3=A9?= Date: Tue, 13 Feb 2024 21:08:11 +0100 Subject: [PATCH] Fix default size for inline images (#150) * Fix default size for inline images * Lint --- src/components/DocumentView/InlineImage.tsx | 63 ++++++++++++--------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/src/components/DocumentView/InlineImage.tsx b/src/components/DocumentView/InlineImage.tsx index 2ad61437e..9a7569316 100644 --- a/src/components/DocumentView/InlineImage.tsx +++ b/src/components/DocumentView/InlineImage.tsx @@ -1,4 +1,5 @@ import { DocumentInlineImage } from '@gitbook/api'; +import assertNever from 'assert-never'; import { getImageSize } from '@/lib/images'; import { ResolvedContentRef } from '@/lib/references'; @@ -8,6 +9,7 @@ import { Image } from '../utils'; export async function InlineImage(props: InlineProps) { const { inline, context } = props; + const { size = 'original' } = inline.data; const [src, darkSrc] = await Promise.all([ context.resolveContentRef(inline.data.ref), @@ -21,7 +23,7 @@ export async function InlineImage(props: InlineProps) { return ( {inline.data.caption) { priority="lazy" preload style={[ - inline.data.size === 'original' - ? ['max-w-[300px]', 'w-full'] - : ['max-h-[1lh]', 'h-[1lh]', 'w-auto'], + size === 'line' + ? ['max-h-[1lh]', 'h-[1lh]', 'w-auto'] + : ['max-w-[300px]', 'w-full'], ]} inline /> ); } -async function getImageSizes(inline: DocumentInlineImage, src: ResolvedContentRef) { - if (inline.data.size === 'original') { - // The max-width is 300px - return [ - { - width: 300, - }, - ]; +async function getImageSizes(size: 'original' | 'line', src: ResolvedContentRef) { + switch (size) { + case 'line': { + // 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), + }, + ]; + } + case 'original': { + // The max-width is 300px + return [ + { + width: 300, + }, + ]; + } + default: + assertNever(size); } - - // 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), - }, - ]; }