Skip to content

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

TypeScript

docs(useImageMode): add a photo caption example block (#9893)

Parman Mohammadalizadehc03a87c51d17
diff --git a/.changeset/use-image-mode-photo-caption-example.md b/.changeset/use-image-mode-photo-caption-example.md
new file mode 100644
index 0000000000..874f20dedb
--- /dev/null
+++ b/.changeset/use-image-mode-photo-caption-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useImageMode — Photo Caption` example block shows a caption over a photo's sky. `useImageMode` samples only the strip under the caption, and `MediaTheme` gives the caption light or dark text from the result. A Beach photo switch swaps a night photo for a bright beach photo, and the caption keeps the dark fallback while the new photo loads. Copy it with `astryx template useImageModeHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index c0fcdf2226..c700f1bcdf 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -792,6 +792,7 @@
"/templates/useFocusTrapHookUsage/",
"/templates/useGridFocusHookUsage/",
"/templates/useHotkeysHookUsage/",
+ "/templates/useImageModeHookUsage/",
"/templates/useInputStatusIconHookUsage/",
"/templates/useKeyboardHintHookUsage/",
"/templates/useListFocusHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 91fafc7483..d13f8d63dd 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3701,6 +3701,11 @@
"path": "examples/use-hover-card/profile-preview",
"aliases": []
},
+ {
+ "name": "example-use-image-mode-photo-caption",
+ "path": "examples/use-image-mode/photo-caption",
+ "aliases": []
+ },
{
"name": "example-use-input-status-icon-coupon-code-status",
"path": "examples/use-input-status-icon/coupon-code-status",
diff --git a/packages/cli/api/template/use-image-mode-hook-usage.test.tsx b/packages/cli/api/template/use-image-mode-hook-usage.test.tsx
new file mode 100644
index 0000000000..f16e37e8f1
--- /dev/null
+++ b/packages/cli/api/template/use-image-mode-hook-usage.test.tsx
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useImageMode example is a photo caption that reads light or dark text
+ * from the strip of sky under it, and keeps the dark fallback while a new
+ * photo loads.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseImageModeHookUsage from '../../assets/templates/blocks/components/Hooks/useImageModeHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const PHOTO_HEIGHT = 600;
+
+// Average color of each photo's top 30% (the caption strip) and of the whole
+// photo. The beach sky is pale, but the photo as a whole is dark.
+const PIXELS: Record<string, {strip: number[]; whole: number[]}> = {
+ 'moody-scene-horizontal-1.png': {strip: [40, 70, 80], whole: [20, 35, 40]},
+ 'light-scene-horizontal-1.png': {
+ strip: [190, 200, 210],
+ whole: [90, 100, 110],
+ },
+};
+
+type Bitmap = {name: string; width: number; height: number};
+
+let root: Root | null = null;
+let container: HTMLElement;
+let pending: Map<string, () => void>;
+let drawn: Array<{name: string; sy: number; sh: number}>;
+
+function photoName(url: string): string {
+ return url.split('/').pop() ?? url;
+}
+
+function caption(): HTMLElement {
+ const element = container.querySelector<HTMLElement>('[data-astryx-media]');
+ if (element == null) {
+ throw new Error('no MediaTheme caption rendered');
+ }
+ return element;
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 5; i++) {
+ await act(() => Promise.resolve());
+ }
+}
+
+async function finishLoading(name: string): Promise<void> {
+ pending.get(name)?.();
+ await settle();
+}
+
+beforeEach(() => {
+ pending = new Map();
+ drawn = [];
+ vi.stubGlobal('fetch', async (url: string) => ({
+ blob: async () => ({name: photoName(url)}),
+ }));
+ vi.stubGlobal(
+ 'createImageBitmap',
+ (blob: {name: string}) =>
+ new Promise<Bitmap>(resolve => {
+ pending.set(blob.name, () =>
+ resolve({name: blob.name, width: 900, height: PHOTO_HEIGHT}),
+ );
+ }),
+ );
+ vi.stubGlobal(
+ 'OffscreenCanvas',
+ class {
+ getContext() {
+ let color = [0, 0, 0];
+ return {
+ drawImage(
+ bitmap: Bitmap,
+ _sx: number,
+ sy: number,
+ _sw: number,
+ sh: number,
+ ) {
+ drawn.push({name: bitmap.name, sy, sh});
+ const pixels = PIXELS[bitmap.name];
+ color = sh < bitmap.height ? pixels.strip : pixels.whole;
+ },
+ getImageData(_x: number, _y: number, width: number, height: number) {
+ const data = new Uint8ClampedArray(width * height * 4);
+ for (let i = 0; i < data.length; i += 4) {
+ data.set([...color, 255], i);
+ }
+ return {data};
+ },
+ };
+ }
+ },
+ );
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseImageModeHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+describe('useImageMode example', () => {
+ it('samples only the strip under the caption', async () => {
+ await finishLoading('moody-scene-horizontal-1.png');
+ expect(drawn).toEqual([
+ {name: 'moody-scene-horizontal-1.png', sy: 0, sh: 0.3 * PHOTO_HEIGHT},
+ ]);
+ expect(caption().getAttribute('data-astryx-media')).toBe('dark');
+ expect(caption().textContent).toContain('Sky behind the caption: dark');
+ });
+
+ it('switches the caption to dark text over the beach sky, after the fallback while it loads', async () => {
+ await finishLoading('moody-scene-horizontal-1.png');
+ act(() => container.querySelector<HTMLInputElement>('input')?.click());
+ await settle();
+
+ expect(caption().textContent).toContain('Afternoon at the beach');
+ expect(caption().getAttribute('data-astryx-media')).toBe('dark');
+
+ await finishLoading('light-scene-horizontal-1.png');
+ expect(caption().getAttribute('data-astryx-media')).toBe('light');
+ expect(caption().textContent).toContain('Sky behind the caption: light');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.doc.mjs
new file mode 100644
index 0000000000..1303a3b75b
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useImageMode',
+ name: 'useImageMode — Photo Caption',
+ displayName: 'useImageMode — Photo Caption',
+ description:
+ 'A photo banner with a caption over the sky. useImageMode samples only the strip under the caption and MediaTheme switches the caption between light and dark text from the result. A Beach photo switch swaps a night photo for a bright beach photo, and while the new photo loads the caption keeps the dark fallback.',
+ isReady: true,
+ aspectRatio: 3 / 2,
+ componentsUsed: ['AspectRatio', 'MediaTheme', 'Switch', 'Text', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.tsx
new file mode 100644
index 0000000000..f0c62baac7
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useImageModeHookUsage.tsx
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {AspectRatio} from '@astryxdesign/core/AspectRatio';
+import {useImageMode} from '@astryxdesign/core/hooks';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Switch} from '@astryxdesign/core/Switch';
+import {Text} from '@astryxdesign/core/Text';
+import {MediaTheme} from '@astryxdesign/core/theme';
+
+const NIGHT_PHOTO = '/template-assets/moody-scene-horizontal-1.png';
+const BEACH_PHOTO = '/template-assets/light-scene-horizontal-1.png';
+
+const CAPTION_REGION = {x: 0, y: 0, width: 1, height: 0.3};
+
+export default function UseImageModeHookUsage() {
+ const [isBeach, setIsBeach] = useState(false);
+ const src = isBeach ? BEACH_PHOTO : NIGHT_PHOTO;
+ const mode = useImageMode(src, {
+ region: CAPTION_REGION,
+ threshold: 0.4,
+ fallback: 'dark',
+ });
+
+ return (
+ <VStack gap={3}>
+ <AspectRatio
+ ratio={3 / 2}
+ style={{
+ width: 360,
+ maxWidth: '100%',
+ borderRadius: 'var(--radius-container)',
+ }}>
+ <img
+ src={src}
+ alt={isBeach ? 'A beach under a pale sky' : 'Snowy peaks at night'}
+ style={{width: '100%', height: '100%', objectFit: 'cover'}}
+ />
+ <div style={{position: 'absolute', inset: '0 0 auto', padding: 16}}>
+ <MediaTheme mode={mode ?? 'off'}>
+ <VStack gap={1}>
+ <Text type="body" weight="bold">
+ {isBeach ? 'Afternoon at the beach' : 'Night in the mountains'}
+ </Text>
+ <Text type="supporting">Sky behind the caption: {mode}</Text>
+ </VStack>
+ </MediaTheme>
+ </div>
+ </AspectRatio>
+ <Switch label="Beach photo" value={isBeach} onChange={setIsBeach} />
+ </VStack>
+ );
+}