Fix default size for inline images (#150)

* Fix default size for inline images

* Lint
This commit is contained in:
Samy Pessé
2024-02-13 21:08:11 +01:00
committed by GitHub
parent c3d9e85823
commit e9432c9486
+35 -28
View File
@@ -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<DocumentInlineImage>) {
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<DocumentInlineImage>) {
return (
<Image
alt={inline.data.caption ?? ''}
sizes={await getImageSizes(inline, src)}
sizes={await getImageSizes(size, src)}
sources={{
light: {
src: src.href,
@@ -37,38 +39,43 @@ export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
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),
},
];
}