Skip to content

Commit

Permalink
feat: allow 1 dim img
Browse files Browse the repository at this point in the history
  • Loading branch information
abernier committed Aug 29, 2024
1 parent 3ace2ca commit 5b629aa
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
13 changes: 13 additions & 0 deletions docs/getting-started/authoring.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
<img src="gutenberg.jpg" height="200" />
```

<details>
<summary>Result</summary>

<img src="gutenberg.jpg" height="200" />

</details>

> [!NOTE]
> See [`MDX_BASEURL`](introduction#configuration:~:text=MDX_BASEURL) to understand how it is converted to a full URL.
Expand Down
29 changes: 22 additions & 7 deletions src/components/mdx/Img/Img.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pick<ComponentProps<'img'>, '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 (
Expand Down

0 comments on commit 5b629aa

Please sign in to comment.