Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ const nextConfig = {
images: {
contentDispositionType: 'inline', // "open image in new tab" instead of downloading
remotePatterns: REMOTE_IMAGE_PATTERNS,
minimumCacheTTL: 86400, // 1 day
},
env: {
// Inline this per-deployment value into the edge middleware at build time.
Expand Down
22 changes: 7 additions & 15 deletions src/components/docImage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,20 +98,13 @@ export default function DocImage({
imgPath = finalSrc;
}

// Prefer explicit props (coming from MDX attributes) over hash-based dimensions.
// If either width or height prop is provided, treat as manual sizing.
const manualWidth = parseDimension(propsWidth);
const manualHeight = parseDimension(propsHeight);

// If either width or height is specified manually, ignore any hash dimensions entirely
const hasDimensionOverrides = manualWidth != null || manualHeight != null;
const hashDimensions = hasDimensionOverrides ? [] : parseDimensionsFromHash(src);

const inferredWidth = hashDimensions[0] > 0 ? hashDimensions[0] : undefined;
const width = hasDimensionOverrides ? manualWidth : inferredWidth;

const inferredHeight = hashDimensions[1] > 0 ? hashDimensions[1] : undefined;
const height = hasDimensionOverrides ? manualHeight : inferredHeight;
// JSX dimensions replace both hash dimensions, even for a single-axis override.
const parsedWidth = parseDimension(propsWidth);
const parsedHeight = parseDimension(propsHeight);
const [width, height] =
parsedWidth != null || parsedHeight != null
? [parsedWidth, parsedHeight]
: parseDimensionsFromHash(src);

return (
<ImageLightbox
Expand All @@ -120,7 +113,6 @@ export default function DocImage({
imgPath={imgPath}
width={width}
height={height}
hasDimensionOverrides={hasDimensionOverrides}
alt={props.alt ?? ''}
/>
);
Expand Down
24 changes: 10 additions & 14 deletions src/components/imageLightbox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ interface ImageLightboxProps extends Omit<
alt: string;
imgPath: string;
src: string;
hasDimensionOverrides?: boolean;
height?: number;
width?: number;
}
Expand Down Expand Up @@ -53,7 +52,6 @@ export function ImageLightbox({
width,
height,
imgPath,
hasDimensionOverrides: hasDimensionOverrides = false,
style,
className,
...props
Expand Down Expand Up @@ -98,19 +96,15 @@ export function ImageLightbox({
? className
: 'max-h-[90vh] max-w-[90vw] object-contain';

// Apply sizing:
// - If manual: set only provided dimension(s); missing one becomes 'auto'
// - Else: default responsive
// TODO: support other units for overrides
// Fit the resolved width to the container; height follows the aspect ratio.
// Height-only overrides retain their requested height.
const imageStyle = isInline
? hasDimensionOverrides
? {
width: width != null ? `${width}px` : 'auto',
height: height != null ? `${height}px` : 'auto',
maxWidth: 'min(100%, 1000px)',
...style,
}
: {width: 'auto', maxWidth: 'min(100%, 1000px)', height: 'auto', ...style}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lightbox now shows the capped, downscaled image

Medium Severity

The zoomed lightbox view now uses the same capped 900px size as the inline image, so it goes through next/image with width: auto instead of showing the original file. On 2x displays, a 1600px screenshot shows at about 800 CSS px, which is smaller than the 900px inline image. Zooming in now shrinks the image and lowers its resolution.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6744163. Configure here.

? {
width: width != null ? `min(100%, ${width}px)` : 'auto',
height: width == null && height != null ? `${height}px` : 'auto',
maxWidth: '100%',
...style,
}
: {width: 'auto', height: 'auto'};

if (shouldUseNextImage && dimensions) {
Expand All @@ -131,6 +125,8 @@ export function ImageLightbox({
/* eslint-disable-next-line @next/next/no-img-element */
<img
src={renderedSrc}
width={width}
height={height}
alt={alt}
loading={isInline ? 'lazy' : 'eager'}
decoding="async"
Expand Down
14 changes: 11 additions & 3 deletions src/remark-image-processing.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ import path from 'path';
import sharp from 'sharp';
import {visit} from 'unist-util-visit';

const MAX_IMAGE_WIDTH = 900;

/**
* Processes images in MDX content:
* 1. Appends image dimensions as a URL hash (for next/image sizing)
* 1. Appends image dimensions capped at 900px wide as a URL hash (for next/image sizing)
* 2. Appends content hash as query param (for Vercel CDN cache busting)
*
* e.g. /img.png -> /img.png?v=abc12345#100x100
*
* The size (#WxH) is consumed by docImage.tsx and passed down to next/image.
* For relative imports, remark-image-resize copies #WxH to JSX attributes before
* the bundler strips the hash. DocImage reads the hash for public asset URLs.
* The content hash (?v=xxx) ensures browsers/CDN fetch fresh images when content changes.
*/
export default function remarkImageProcessing(options) {
Expand All @@ -38,7 +41,12 @@ export default function remarkImageProcessing(options) {

// Read file buffer once for both operations to avoid redundant disk I/O
const imageBuffer = readFileSync(fullImagePath);
const {width, height} = await sharp(imageBuffer).metadata();
let {width, height} = await sharp(imageBuffer).metadata();
if (width > MAX_IMAGE_WIDTH) {
// cap new height proportionally to MAX_IMAGE_WIDTH
height = Math.max(1, Math.round((height * MAX_IMAGE_WIDTH) / width));
width = MAX_IMAGE_WIDTH;
}
const contentHash = createHash('md5')
.update(imageBuffer)
.digest('hex')
Expand Down
97 changes: 96 additions & 1 deletion src/remark-image-processing.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@ import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';
import {tmpdir} from 'node:os';
import path from 'node:path';

import {select} from 'hast-util-select';
import {bundleMDX} from 'mdx-bundler';
import {getMDXComponent} from 'mdx-bundler/client';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import rehypeParse from 'rehype-parse';
import remarkMdxImages from 'remark-mdx-images';
import sharp from 'sharp';
import {beforeAll, describe, expect, it} from 'vitest';
import {unified} from 'unified';
import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';

import DocImage from './components/docImage';
import remarkImageProcessing from './remark-image-processing';
import remarkImageResize from './remark-image-resize';

vi.mock('server-only', () => ({}));

vi.mock('sentry-docs/serverContext', () => ({
serverContext: () => ({path: []}),
}));

// Vitest uses the classic JSX transform for the application components.
vi.stubGlobal('React', React);
afterAll(() => vi.unstubAllGlobals());

const createImage = (width, height, format) => {
const image = sharp({
Expand Down Expand Up @@ -39,6 +59,10 @@ describe('remarkImageProcessing', () => {
[path.join(sourceFolder, 'relative.png'), await createImage(200, 150, 'png')],
[path.join(sourceFolder, 'photo.jpg'), await createImage(64, 48, 'jpeg')],
[path.join(sourceFolder, 'animation.gif'), await createImage(30, 20, 'gif')],
[path.join(sourceFolder, 'wide.png'), await createImage(2942, 1360, 'png')],
[path.join(sourceFolder, 'boundary.png'), await createImage(900, 600, 'png')],
[path.join(sourceFolder, 'thin.png'), await createImage(1801, 1, 'png')],
[path.join(sourceFolder, 'portrait.png'), await createImage(600, 1200, 'png')],
[
path.join(sourceFolder, 'icon.svg'),
Buffer.from(
Expand Down Expand Up @@ -76,6 +100,21 @@ describe('remarkImageProcessing', () => {
expect(node.url).toBe(`/img/public.png?v=${hashes['public.png']}#120x80`);
});

it.each([
['wide.png', '900x416'],
['boundary.png', '900x600'],
['thin.png', '900x1'],
['portrait.png', '600x1200'],
])(
'caps width without upscaling and preserves the content hash for %s',
async (fixture, size) => {
const node = imageNode(`./${fixture}`);
await transform(tree(node));

expect(node.url).toBe(`./${fixture}?v=${hashes[fixture]}#${size}`);
}
);

it.each(['https://example.com/img.png', 'http://example.com/img.png', '//cdn/img.png'])(
'leaves the external image %s untouched',
async url => {
Expand All @@ -99,4 +138,60 @@ describe('remarkImageProcessing', () => {
it('rejects when the image is missing', async () => {
await expect(transform(tree(imageNode('./nope.png')))).rejects.toThrow(/ENOENT/);
});

async function renderImage(suffix) {
const {code} = await bundleMDX({
source: `![Fixture${suffix}](./wide.png)`,
cwd: sourceFolder,
mdxOptions(options) {
options.remarkPlugins = [
...(options.remarkPlugins ?? []),
[remarkImageProcessing, {sourceFolder, publicFolder}],
remarkMdxImages,
remarkImageResize,
];
return options;
},
esbuildOptions(options) {
options.loader = {...options.loader, '.png': 'file'};
options.outdir = path.join(sourceFolder, 'output');
options.write = true;
return options;
},
});
const Content = getMDXComponent(code);
const html = renderToStaticMarkup(
React.createElement(Content, {components: {img: DocImage}})
);
return select('img', unified().use(rehypeParse, {fragment: true}).parse(html))
.properties;
}

describe('MDX image bundling and rendering', () => {
it.each`
sizing | suffix | width | height
${'inferred'} | ${''} | ${900} | ${416}
${'width only'} | ${' =300x'} | ${300} | ${undefined}
${'height only'} | ${' =x200'} | ${undefined} | ${200}
${'both axes'} | ${' =300x200'} | ${300} | ${200}
`(
'preserves $sizing sizing through bundling and rendering',
async ({suffix, width, height}) => {
const image = await renderImage(suffix);

expect(image.width).toBe(width);
expect(image.height).toBe(height);
expect(image.alt).toBe('Fixture');
expect(image.style).toContain(
`width:${width ? `min(100%, ${width}px)` : 'auto'};`
);
expect(image.style).toContain(
`height:${!width && height ? `${height}px` : 'auto'}`
);
expect(image.srcSet).toEqual(
width && height ? expect.stringContaining('/_next/image') : undefined
);
}
);
});
});
40 changes: 38 additions & 2 deletions src/remark-image-resize.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,29 @@ const SIZE_FROM_ALT_RE = /\s*=\s*(?:(\d+)\s*x\s*(\d+)|(\d+)\s*x|x\s*(\d+))\s*$/;
* Behavior:
* - Extracts the trailing "=WxH" (width-only/height-only also supported).
* - Cleans the ALT text by removing the size suffix.
* - Adds numeric `width`/`height` attributes to the <img> element.
* - Manual sizes replace inferred dimensions, including width-only/height-only sizes.
* - Copies inferred dimensions from imports to JSX before the bundler strips URL hashes.
*/
export default function remarkImageResize() {
return tree =>
return tree => {
// remember hash dimensions for each image import
const dimensionsByImport = new Map();
visit(tree, 'mdxjsEsm', node => {
for (const declaration of node.data?.estree?.body ?? []) {
if (declaration.type !== 'ImportDeclaration') continue;
const dimensions = declaration.source.value.match(/#(\d+)x(\d+)$/);
if (dimensions) {
for (const specifier of declaration.specifiers) {
dimensionsByImport.set(
specifier.local.name,
// take the captured groups from the regex match (ie width and height)
dimensions.slice(1)
);
}
}
}
});

visit(tree, {type: 'mdxJsxTextElement', name: 'img'}, node => {
// Handle MDX JSX <img> produced by remark-mdx-images
const altIndex = node.attributes.findIndex(a => a && a.name === 'alt');
Expand All @@ -44,7 +63,24 @@ export default function remarkImageResize() {
node.attributes.push({type: 'mdxJsxAttribute', name: 'width', value: wStr});
if (hStr)
node.attributes.push({type: 'mdxJsxAttribute', name: 'height', value: hStr});
return;
}
}

// inject inferred dimensions if not already manually overridden as width and height attributes
if (
node.attributes.some(attribute => ['width', 'height'].includes(attribute.name))
) {
return;
}
const src = node.attributes.find(attribute => attribute.name === 'src');
const dimensions = dimensionsByImport.get(src?.value?.value);
if (dimensions) {
node.attributes.push(
{type: 'mdxJsxAttribute', name: 'width', value: dimensions[0]},
{type: 'mdxJsxAttribute', name: 'height', value: dimensions[1]}
);
}
});
};
}
Loading