diff --git a/next.config.ts b/next.config.ts index 875ffec912d81..e017e57faa955 100644 --- a/next.config.ts +++ b/next.config.ts @@ -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. diff --git a/src/components/docImage/index.tsx b/src/components/docImage/index.tsx index 674e1a8d55aac..3765ac398fb31 100644 --- a/src/components/docImage/index.tsx +++ b/src/components/docImage/index.tsx @@ -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 ( ); diff --git a/src/components/imageLightbox/index.tsx b/src/components/imageLightbox/index.tsx index 602f1d025e37e..763a823207c82 100644 --- a/src/components/imageLightbox/index.tsx +++ b/src/components/imageLightbox/index.tsx @@ -12,7 +12,6 @@ interface ImageLightboxProps extends Omit< alt: string; imgPath: string; src: string; - hasDimensionOverrides?: boolean; height?: number; width?: number; } @@ -53,7 +52,6 @@ export function ImageLightbox({ width, height, imgPath, - hasDimensionOverrides: hasDimensionOverrides = false, style, className, ...props @@ -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} + ? { + 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) { @@ -131,6 +125,8 @@ export function ImageLightbox({ /* eslint-disable-next-line @next/next/no-img-element */ {alt} /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) { @@ -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') diff --git a/src/remark-image-processing.spec.js b/src/remark-image-processing.spec.js index 8b9213fdda42a..c28316bf3a605 100644 --- a/src/remark-image-processing.spec.js +++ b/src/remark-image-processing.spec.js @@ -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({ @@ -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( @@ -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 => { @@ -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 + ); + } + ); + }); }); diff --git a/src/remark-image-resize.js b/src/remark-image-resize.js index d32f1d073b9f1..870b641ba29d2 100644 --- a/src/remark-image-resize.js +++ b/src/remark-image-resize.js @@ -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 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 produced by remark-mdx-images const altIndex = node.attributes.findIndex(a => a && a.name === 'alt'); @@ -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]} + ); + } }); + }; }