An open source design system that's fully customizable and agent ready
TypeScript
docs(site): blog images named @2x render at half their pixel width (#7385)
Cindy Zhangeaca8ebae6b8
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex 49523f8cc9..4b93e424c8 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -41,6 +41,7 @@ import docsiteConfig from '../astryx.config.mjs';import {integrationContentEnabled} from '../src/lib/integrationTargets.mjs';import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';import {projectThemingDoc} from './lib/theming-doc.mjs';+import {collectBlogImages} from './lib/blog-images.mjs';import {buildTypeDefinitionIndex,collectPropTypeRefs,@@ -2328,26 +2329,14 @@ async function generateBlogRegistry() {const types = collectTypes(posts);const tags = collectTags(posts);- // Definitive set of dark-mode image variants. We scan public/blog/** for- // files named "<name>.dark.<ext>" at build time so ThemedImage can decide,- // deterministically and with no runtime probe, whether a body image has a- // dark counterpart. Paths are stored as site-absolute URLs ("/blog/...").- const publicBlogDir = path.join(DOCSITE_ROOT, 'public', 'blog');- const darkImages = [];- const walkDark = dir => {- if (!fs.existsSync(dir)) return;- for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {- const full = path.join(dir, entry.name);- if (entry.isDirectory()) {- walkDark(full);- } else if (/\.dark\.[a-zA-Z0-9]+$/.test(entry.name)) {- const rel = path.relative(path.join(DOCSITE_ROOT, 'public'), full);- darkImages.push('/' + rel.split(path.sep).join('/'));- }- }- };- walkDark(publicBlogDir);- darkImages.sort();+ // Definitive facts about body images, scanned from public/blog/** at build+ // time so ThemedImage never probes at runtime: which images have a+ // "<name>.dark.<ext>" counterpart, and the natural size of every "@2x"+ // image, which renders at half its pixel width. Paths are site-absolute+ // URLs ("/blog/...").+ const {darkImages, imageSizes} = collectBlogImages(+ path.join(DOCSITE_ROOT, 'public'),+ );const content = `// Auto-generated by scripts/generate-data.mjs — do not editimport type {BlogPost, BlogPostType} from '../lib/blog/schema';@@ -2367,6 +2356,15 @@ export const blogPostCount = ${posts.length};* build-time list rather than a runtime existence probe.*/export const blogDarkImages: string[] = ${JSON.stringify(darkImages, null, 2)};++/**+ * Natural pixel size of every body image whose file name ends in "@2x"+ * (before the extension and the optional ".dark" marker). ThemedImage renders+ * such an image at half its pixel width, so a Retina screenshot shows the+ * component at the size it really is on screen.+ */+export const blogImageSizes: Record<string, {width: number; height: number}> =+ ${JSON.stringify(imageSizes, null, 2)};`;writeRegistry('blogRegistry.ts', content);return {blogPostCount: posts.length, blogTypeCount: types.length};diff --git a/apps/docsite/scripts/lib/blog-images.mjs b/apps/docsite/scripts/lib/blog-images.mjsnew file mode 100644index 0000000000..b994b12fb6--- /dev/null+++ b/apps/docsite/scripts/lib/blog-images.mjs@@ -0,0 +1,147 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file blog-images.mjs+ * Build-time facts about blog body images that the docsite needs without a+ * runtime probe: which images have a dark counterpart, and the natural size of+ * every image whose file name ends in `@2x` (before the extension and the+ * optional `.dark` marker), so a Retina screenshot renders at half its pixel+ * width — the size the component really is on screen.+ *+ * @input A `public/blog` directory tree.+ * @output `{darkImages, imageSizes}` with site-absolute paths.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++export const RETINA_IMAGE_RE = /@2x(\.dark)?\.[a-zA-Z0-9]+$/;++/**+ * Read a PNG's IHDR dimensions.+ * @param {Buffer} bytes+ * @returns {{width: number, height: number} | null}+ */+function pngSize(bytes) {+ if (+ bytes.length < 24 ||+ bytes.toString('latin1', 1, 4) !== 'PNG' ||+ bytes.toString('latin1', 12, 16) !== 'IHDR'+ ) {+ return null;+ }+ return {width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20)};+}++/**+ * Read a JPEG's SOF dimensions.+ * @param {Buffer} bytes+ * @returns {{width: number, height: number} | null}+ */+function jpegSize(bytes) {+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;+ let offset = 2;+ while (offset + 9 < bytes.length) {+ if (bytes[offset] !== 0xff) return null;+ const marker = bytes[offset + 1];+ const length = bytes.readUInt16BE(offset + 2);+ // SOF0..SOF15 except DHT (C4), JPG (C8) and DAC (CC) carry the frame size.+ if (+ marker >= 0xc0 &&+ marker <= 0xcf &&+ marker !== 0xc4 &&+ marker !== 0xc8 &&+ marker !== 0xcc+ ) {+ return {+ height: bytes.readUInt16BE(offset + 5),+ width: bytes.readUInt16BE(offset + 7),+ };+ }+ offset += 2 + length;+ }+ return null;+}++/**+ * Read a WebP's canvas size (VP8X extended header, VP8 lossy, or VP8L lossless).+ * @param {Buffer} bytes+ * @returns {{width: number, height: number} | null}+ */+function webpSize(bytes) {+ if (+ bytes.length < 30 ||+ bytes.toString('latin1', 0, 4) !== 'RIFF' ||+ bytes.toString('latin1', 8, 12) !== 'WEBP'+ ) {+ return null;+ }+ const chunk = bytes.toString('latin1', 12, 16);+ if (chunk === 'VP8X') {+ return {+ width: 1 + bytes.readUIntLE(24, 3),+ height: 1 + bytes.readUIntLE(27, 3),+ };+ }+ if (chunk === 'VP8 ') {+ return {+ width: bytes.readUInt16LE(26) & 0x3fff,+ height: bytes.readUInt16LE(28) & 0x3fff,+ };+ }+ if (chunk === 'VP8L') {+ const bits = bytes.readUInt32LE(21);+ return {width: 1 + (bits & 0x3fff), height: 1 + ((bits >> 14) & 0x3fff)};+ }+ return null;+}++/**+ * The natural pixel size of a PNG, JPEG, or WebP, or null for anything else.+ * @param {Buffer} bytes+ * @returns {{width: number, height: number} | null}+ */+export function imageSize(bytes) {+ return pngSize(bytes) ?? jpegSize(bytes) ?? webpSize(bytes);+}++/**+ * Walk `publicDir/blog` and collect the dark variants and the `@2x` sizes.+ * @param {string} publicDir The docsite's `public` directory.+ * @returns {{darkImages: string[], imageSizes: Record<string, {width: number, height: number}>}}+ */+export function collectBlogImages(publicDir) {+ const blogDir = path.join(publicDir, 'blog');+ /** @type {string[]} */+ const darkImages = [];+ /** @type {Record<string, {width: number, height: number}>} */+ const imageSizes = {};+ const siteUrl = (/** @type {string} */ full) =>+ '/' + path.relative(publicDir, full).split(path.sep).join('/');+ const walk = (/** @type {string} */ dir) => {+ if (!fs.existsSync(dir)) return;+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(full);+ continue;+ }+ if (/\.dark\.[a-zA-Z0-9]+$/.test(entry.name)) {+ darkImages.push(siteUrl(full));+ }+ if (RETINA_IMAGE_RE.test(entry.name)) {+ const size = imageSize(fs.readFileSync(full));+ if (size) imageSizes[siteUrl(full)] = size;+ }+ }+ };+ walk(blogDir);+ darkImages.sort();+ return {+ darkImages,+ imageSizes: Object.fromEntries(+ Object.entries(imageSizes).sort(([a], [b]) => a.localeCompare(b)),+ ),+ };+}diff --git a/apps/docsite/src/__tests__/blog-image-sizes.test.ts b/apps/docsite/src/__tests__/blog-image-sizes.test.tsnew file mode 100644index 0000000000..e1b84264ba--- /dev/null+++ b/apps/docsite/src/__tests__/blog-image-sizes.test.ts@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import zlib from 'node:zlib';+import {afterEach, describe, expect, it} from 'vitest';+import {collectBlogImages, imageSize} from '../../scripts/lib/blog-images.mjs';++/** A minimal valid PNG of the given size (one grey pixel row per line). */+function png(width: number, height: number): Buffer {+ const chunk = (type: string, data: Buffer) => {+ const length = Buffer.alloc(4);+ length.writeUInt32BE(data.length);+ const body = Buffer.concat([Buffer.from(type, 'latin1'), data]);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(zlib.crc32(body));+ return Buffer.concat([length, body, crc]);+ };+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr[8] = 8; // bit depth+ ihdr[9] = 0; // greyscale+ const raw = Buffer.alloc((width + 1) * height);+ return Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ chunk('IHDR', ihdr),+ chunk('IDAT', zlib.deflateSync(raw)),+ chunk('IEND', Buffer.alloc(0)),+ ]);+}++const tmpDirs: string[] = [];+afterEach(() => {+ for (const dir of tmpDirs.splice(0)) {+ fs.rmSync(dir, {recursive: true, force: true});+ }+});++describe('blog image facts', () => {+ it('reads a PNG natural size from its header and rejects other bytes', () => {+ expect(imageSize(png(780, 412))).toEqual({width: 780, height: 412});+ expect(imageSize(Buffer.from('not an image'))).toBeNull();+ });++ it('reads an extended WebP canvas size', () => {+ // RIFF header + VP8X chunk: flags, then canvas width-1 and height-1 as+ // 24-bit little-endian values.+ const header = Buffer.alloc(30);+ header.write('RIFF', 0, 'latin1');+ header.writeUInt32LE(22, 4);+ header.write('WEBP', 8, 'latin1');+ header.write('VP8X', 12, 'latin1');+ header.writeUInt32LE(10, 16);+ header.writeUIntLE(1278 - 1, 24, 3);+ header.writeUIntLE(570 - 1, 27, 3);+ expect(imageSize(header)).toEqual({width: 1278, height: 570});+ // The real asset agrees.+ const real = fs.readFileSync(+ path.resolve(+ __dirname,+ '../../public/blog/astryx-v0-6-0/adaptive-inputs.webp',+ ),+ );+ expect(imageSize(real)?.width).toBeGreaterThan(0);+ });++ it('records the natural size of @2x images only, light and dark alike', () => {+ const publicDir = fs.mkdtempSync(path.join(os.tmpdir(), 'blog-2x-'));+ tmpDirs.push(publicDir);+ const post = path.join(publicDir, 'blog', 'release');+ fs.mkdirSync(post, {recursive: true});+ fs.writeFileSync(path.join(post, '[email protected]'), png(780, 300));+ fs.writeFileSync(path.join(post, '[email protected]'), png(780, 300));+ fs.writeFileSync(path.join(post, 'cover.png'), png(1200, 600));+ fs.writeFileSync(path.join(post, 'cover.dark.png'), png(1200, 600));++ const {darkImages, imageSizes} = collectBlogImages(publicDir);+ expect(darkImages).toEqual([+ '/blog/release/cover.dark.png',+ '/blog/release/[email protected]',+ ]);+ expect(imageSizes).toEqual({+ '/blog/release/[email protected]': {width: 780, height: 300},+ '/blog/release/[email protected]': {width: 780, height: 300},+ });+ });+});diff --git a/apps/docsite/src/__tests__/themed-image-2x.test.tsx b/apps/docsite/src/__tests__/themed-image-2x.test.tsxnew file mode 100644index 0000000000..fd5e99d5f9--- /dev/null+++ b/apps/docsite/src/__tests__/themed-image-2x.test.tsx@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// @vitest-environment jsdom++import {render} from '@testing-library/react';+import {describe, expect, it, vi} from 'vitest';++vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+}));+vi.mock('../app/providers', () => ({+ useThemeMode: () => ({themeMode: 'system'}),+}));+vi.mock('../generated/blogRegistry', () => ({+ blogDarkImages: ['/blog/release/[email protected]'],+ blogImageSizes: {+ '/blog/release/[email protected]': {width: 780, height: 300},+ '/blog/release/[email protected]': {width: 780, height: 300},+ '/blog/release/[email protected]': {width: 639, height: 200},+ },+}));++import {MarkdownImage} from '../components/blog/ThemedImage';++// A screenshot taken on a 2x display is twice as many pixels as the component+// is wide on screen; an `@2x` file name says so, and the image renders at the+// component's real size instead of filling the column.+describe('@2x blog images render at half their pixel width', () => {+ it('gives a 780px @2x image a 390 CSS px width, on both theme variants', () => {+ const {container} = render(+ <MarkdownImage src="/blog/release/[email protected]" alt="Swipe actions" />,+ );+ const img = container.querySelector('img');+ expect(img?.getAttribute('width')).toBe('390');+ expect(container.querySelector('source')?.getAttribute('srcset')).toBe(+ '/blog/release/[email protected]',+ );+ });++ it('rounds an odd pixel width', () => {+ const {container} = render(+ <MarkdownImage src="/blog/release/[email protected]" alt="Menu" />,+ );+ expect(container.querySelector('img')?.getAttribute('width')).toBe('320');+ });++ it('leaves a non-@2x image, and an @2x image the build did not measure, unsized', () => {+ const {container, rerender} = render(+ <MarkdownImage src="/blog/release/cover.png" alt="Cover" />,+ );+ expect(container.querySelector('img')?.hasAttribute('width')).toBe(false);+ rerender(+ <MarkdownImage src="/blog/release/[email protected]" alt="Unknown" />,+ );+ expect(container.querySelector('img')?.hasAttribute('width')).toBe(false);+ });+});diff --git a/apps/docsite/src/components/blog/ThemedImage.tsx b/apps/docsite/src/components/blog/ThemedImage.tsxindex a4f19a37ae..a617b384c3 100644--- a/apps/docsite/src/components/blog/ThemedImage.tsx+++ b/apps/docsite/src/components/blog/ThemedImage.tsx@@ -22,7 +22,7 @@import {useState} from 'react';import * as stylex from '@stylexjs/stylex';import {useThemeMode} from '../../app/providers';-import {blogDarkImages} from '../../generated/blogRegistry';+import {blogDarkImages, blogImageSizes} from '../../generated/blogRegistry';const styles = stylex.create({image: {@@ -30,10 +30,14 @@ const styles = stylex.create({maxWidth: '100%',height: 'auto',borderRadius: 'var(--radius-md, 8px)',- // A subtle frame so a screenshot reads as intentional on either background.- borderWidth: 1,- borderStyle: 'solid',- borderColor: 'var(--color-border, rgba(0,0,0,0.12))',+ // A subtle frame so a screenshot reads as intentional on either+ // background. Drawn as an outline, not a border, so an `@2x` image's+ // `width` is exactly its painted width (the site's `box-sizing:+ // border-box` would otherwise take the frame out of it and resample).+ outlineWidth: 1,+ outlineStyle: 'solid',+ outlineColor: 'var(--color-border, rgba(0,0,0,0.12))',+ outlineOffset: 0,},});@@ -45,17 +49,37 @@ export interface ThemedImageProps {alt: string;}+/** `[email protected]`, `[email protected]`: a screenshot taken at 2× pixel density. */+const RETINA_SRC = /@2x(\.dark)?\.[a-zA-Z0-9]+$/;++/**+ * The CSS width a body image renders at, or undefined to let the image size+ * itself. An `@2x` image whose natural size the build recorded renders at half+ * its pixel width — the component's real on-screen size — and the dark+ * sibling takes the light one's width so the two never shift on toggle.+ */+export function displayWidthFor(src: string): number | undefined {+ if (!RETINA_SRC.test(src)) return undefined;+ const size = blogImageSizes[src];+ return size ? Math.round(size.width / 2) : undefined;+}+export function ThemedImage({lightSrc, darkSrc, alt}: ThemedImageProps) {const {themeMode} = useThemeMode();const [failed, setFailed] = useState<string | null>(null);const light = lightSrc ?? darkSrc;const dark = darkSrc ?? lightSrc;+ // `max-width: 100%` and `height: auto` stay in the style, so a wide+ // screenshot still fits the column and keeps its aspect ratio.+ const width = displayWidthFor(light ?? dark ?? '');// Only one variant available (or both point at the same asset): plain image.if (light == null || dark == null || light === dark) {const only = (light ?? dark) as string;- return <img src={only} alt={alt} {...stylex.props(styles.image)} />;+ return (+ <img src={only} alt={alt} width={width} {...stylex.props(styles.image)} />+ );}// Manual toggle resolved to a concrete mode — honor it directly.@@ -67,6 +91,7 @@ export function ThemedImage({lightSrc, darkSrc, alt}: ThemedImageProps) {<imgsrc={src}alt={alt}+ width={width}onError={() => setFailed(wanted)}{...stylex.props(styles.image)}/>@@ -77,7 +102,12 @@ export function ThemedImage({lightSrc, darkSrc, alt}: ThemedImageProps) {return (<picture><source srcSet={dark} media="(prefers-color-scheme: dark)" />- <img src={light} alt={alt} {...stylex.props(styles.image)} />+ <img+ src={light}+ alt={alt}+ width={width}+ {...stylex.props(styles.image)}+ /></picture>);}diff --git a/apps/docsite/src/content/blog/README.md b/apps/docsite/src/content/blog/README.mdindex 2509cdf819..fb24ad3229 100644--- a/apps/docsite/src/content/blog/README.md+++ b/apps/docsite/src/content/blog/README.md@@ -161,6 +161,29 @@ so the decision is made at build time — no runtime request, no flash. If nodark variant exists (the common case), the single image is used in both modes.The swap follows the site's theme toggle, not just the OS preference.+### Retina screenshots (`@2x`)++A screenshot taken on a 2× display has twice as many pixels as the component+is wide on screen, so by default it renders at double size, capped only by the+column. Name the file with an `@2x` suffix and it renders at half its pixel+width — the component's real size — with `height: auto` and still capped at+the column width:++```+public/blog/<slug>/[email protected] ← 780 px wide file → 390 CSS px+public/blog/<slug>/[email protected] ← dark variant, same width (optional)+```++```md++```++How it works: the same build-time scan records the natural size of every+`@2x` image (PNG, JPEG, or WebP — including an animated WebP's canvas) in a+`blogImageSizes` manifest, and the renderer sets the image's `width` to half+of it. The dark variant takes the light image's width, so the theme toggle+never shifts the layout. Images without the suffix are unchanged.+## 6. Preview locally```bash