Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(docsite): theme-aware (light/dark) images in blog post bodies (#4770)

nynexman44645b87d6d14089
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index 3579f952f4..a46251a1ac 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -1555,6 +1555,27 @@ 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();
+
const content = `// Auto-generated by scripts/generate-data.mjs — do not edit
import type {BlogPost, BlogPostType} from '../lib/blog/schema';
@@ -1565,6 +1586,14 @@ export const blogTypes: BlogPostType[] = ${JSON.stringify(types)};
export const blogTags: string[] = ${JSON.stringify(tags)};
export const blogPostCount = ${posts.length};
+
+/**
+ * Site-absolute paths of every dark-mode image variant found under
+ * public/blog (files named "<name>.dark.<ext>"). ThemedImage consults this to
+ * decide whether a body image has a dark counterpart — a definitive,
+ * build-time list rather than a runtime existence probe.
+ */
+export const blogDarkImages: string[] = ${JSON.stringify(darkImages, null, 2)};
`;
writeRegistry('blogRegistry.ts', content);
return {blogPostCount: posts.length, blogTypeCount: types.length};
diff --git a/apps/docsite/src/components/blog/BlogArticle.tsx b/apps/docsite/src/components/blog/BlogArticle.tsx
index 01ec8b9174..22cd078694 100644
--- a/apps/docsite/src/components/blog/BlogArticle.tsx
+++ b/apps/docsite/src/components/blog/BlogArticle.tsx
@@ -23,6 +23,7 @@ import {POST_TYPE_LABELS} from '../../lib/blog/schema';
import {MarkdownText} from '../MarkdownText';
import {AuthorByline} from './AuthorByline';
import {ReleaseCoverArt} from './ReleaseCoverArt';
+import {MarkdownImage} from './ThemedImage';
import {parseReleaseVersion} from '../../lib/blog/release';
import {layout} from '../../layout.stylex';
@@ -107,7 +108,10 @@ export function BlogArticle({post}: BlogArticleProps) {
</AspectRatio>
) : null}
- <Markdown headingLevelStart={2} contentWidth="100%">
+ <Markdown
+ headingLevelStart={2}
+ contentWidth="100%"
+ components={{image: MarkdownImage}}>
{post.body}
</Markdown>
diff --git a/apps/docsite/src/components/blog/ThemedImage.tsx b/apps/docsite/src/components/blog/ThemedImage.tsx
new file mode 100644
index 0000000000..a4f19a37ae
--- /dev/null
+++ b/apps/docsite/src/components/blog/ThemedImage.tsx
@@ -0,0 +1,105 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ThemedImage.tsx
+ * Theme-aware image. Give it a `lightSrc` and/or a `darkSrc`; it shows the one
+ * matching the docsite's resolved color mode. If only one is provided, that
+ * one is always used.
+ *
+ * Honors the MANUAL theme toggle, not just the OS preference:
+ * - Before mount / while mode is 'system': renders a <picture> whose
+ * `prefers-color-scheme: dark` <source> lets the browser pick from the OS
+ * scheme with no flash and no JS.
+ * - After the user toggles (themeMode resolves to a concrete 'light'|'dark'):
+ * renders a single <img> for that mode so the toggle beats the media query.
+ *
+ * When both variants exist but the dark asset happens to be missing at runtime,
+ * an onError handler falls back to the light asset (and vice-versa).
+ */
+
+'use client';
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {useThemeMode} from '../../app/providers';
+import {blogDarkImages} from '../../generated/blogRegistry';
+
+const styles = stylex.create({
+ image: {
+ display: 'block',
+ 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))',
+ },
+});
+
+export interface ThemedImageProps {
+ /** Image shown in light mode. Falls back to darkSrc if omitted. */
+ lightSrc?: string;
+ /** Image shown in dark mode. Falls back to lightSrc if omitted. */
+ darkSrc?: string;
+ alt: string;
+}
+
+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;
+
+ // 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)} />;
+ }
+
+ // Manual toggle resolved to a concrete mode — honor it directly.
+ if (themeMode === 'light' || themeMode === 'dark') {
+ const wanted = themeMode === 'dark' ? dark : light;
+ const other = themeMode === 'dark' ? light : dark;
+ const src = failed === wanted ? other : wanted;
+ return (
+ <img
+ src={src}
+ alt={alt}
+ onError={() => setFailed(wanted)}
+ {...stylex.props(styles.image)}
+ />
+ );
+ }
+
+ // First paint / 'system': let the browser choose from the OS scheme.
+ return (
+ <picture>
+ <source srcSet={dark} media="(prefers-color-scheme: dark)" />
+ <img src={light} alt={alt} {...stylex.props(styles.image)} />
+ </picture>
+ );
+}
+
+/**
+ * Markdown image override for post bodies. Markdown carries a single `src`, so
+ * we derive a candidate dark-mode variant by convention (`foo.png` ->
+ * `foo.dark.png`) and use it only if that asset is in the build-time
+ * `blogDarkImages` manifest (scanned from public/blog by generate-data.mjs).
+ * This keeps ThemedImage's API explicit (lightSrc/darkSrc) while letting
+ * plain-markdown posts opt into a dark variant just by dropping a `*.dark.*`
+ * file next to the image — no runtime existence probe, no broken-image flash.
+ * Posts with no dark variant (the common case) render a single framed image.
+ */
+export function MarkdownImage({src, alt}: {src: string; alt: string}) {
+ const m = /^(.*)\.([a-zA-Z0-9]+)$/.exec(src);
+ const candidate =
+ m && !m[1].endsWith('.dark') ? `${m[1]}.dark.${m[2]}` : undefined;
+ const darkSrc =
+ candidate != null && blogDarkImages.includes(candidate)
+ ? candidate
+ : undefined;
+
+ return <ThemedImage lightSrc={src} darkSrc={darkSrc} alt={alt} />;
+}
diff --git a/apps/docsite/src/content/blog/README.md b/apps/docsite/src/content/blog/README.md
index 695f784216..8c013aaaba 100644
--- a/apps/docsite/src/content/blog/README.md
+++ b/apps/docsite/src/content/blog/README.md
@@ -127,7 +127,41 @@ Astryx-blue field with the Astryx mark as the separator between segments and
the package name beneath. Set `releasePackage` to change the package label
(defaults to `@astryxdesign/core`); set an explicit `coverImage` to opt out.
-## 5. Preview locally
+## 5. Images in the post body
+
+Reference images in the body with normal Markdown, from `public/blog/<slug>/`:
+
+```md
+![Descriptive alt text](/blog/<slug>/my-screenshot.png)
+```
+
+Always write meaningful alt text — it's read by screen readers and shown if the
+image fails to load. Body images are rendered with a subtle frame so screenshots
+read intentionally on either background.
+
+### Light / dark variants
+
+A body image can automatically swap in dark mode. Drop a second file next to it
+named `<name>.dark.<ext>` and it's used when the site is in dark mode — no
+frontmatter, no markup change. You still reference only the light file:
+
+```
+public/blog/<slug>/pipeline.png ← shown in light mode
+public/blog/<slug>/pipeline.dark.png ← shown in dark mode (optional)
+```
+
+```md
+![The build pipeline](/blog/<slug>/pipeline.png)
+```
+
+How it works: `scripts/generate-data.mjs` scans `public/blog/**` at build time
+and records every `*.dark.*` file in a `blogDarkImages` manifest. The blog
+renderer checks that manifest for a `<name>.dark.<ext>` sibling of each image,
+so the decision is made at build time — no runtime request, no flash. If no
+dark 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.
+
+## 6. Preview locally
```bash
cd apps/docsite
@@ -137,7 +171,7 @@ pnpm dev # runs `pnpm generate` first, then starts Next.js
Visit `/blog` and `/blog/<slug>`. Drafts (`draft: true`) render in dev but are
excluded from production builds.
-## 6. Validate before you push
+## 7. Validate before you push
```bash
pnpm generate # discovers + validates posts into src/generated/blogRegistry.ts