Shared Moment Gallery
The image keeps its place when the room changes.
Your preview settings
{
"layout": "editorial",
"captions": true
}These are the exact settings driving this demo, including sample content and simulated states. For the installable component’s public API, see Usage and Props below.
Open a study, use the arrow keys, then Escape. Focus should return to the card you opened.
A real browser viewport. Scroll within the preview when the sample needs more space. Configuration stays in sync between sizes.
01What it does
A grid-to-detail gallery with a measured shared-element flight. The selected study lifts from its thumbnail into the reading room, captions arrive in sequence, and closing returns the visual to its source card.
In this previewSix code-drawn field studies in an editorial grid. The detail view keeps the same visual, adds the caption and alt description, and supports next/previous. The grid rhythm and date captions are configurable.
Design decisions
A real element is measured on both sides of the transition: the source card and the detail media. The visual is not a screenshot clone, so it remains sharp and the same component content can be reused.
The return path measures the source card again at close. If the grid has not changed underneath the dialog, the visual lands exactly where the reader left it.
The panel chrome fades while the media travels, so closing reads as one object leaving rather than a whole modal shrinking into a card.
02Install
Registry install
Run this in a React project with components.json. The component and its stylesheet land in components/lab/shared-moment-gallery/.
npx shadcn@latest add https://lab.tanishk.me/r/shared-moment-gallery.jsonFiles included
2- components/lab/shared-moment-gallery/shared-moment-gallery.tsxcomponent
- components/lab/shared-moment-gallery/shared-moment-gallery.cssstyles
Manual install: copy each file into the same folder and preserve its relative imports. Open the source
03Usage
"use client";
import { SharedMomentGallery } from "@/components/lab/shared-moment-gallery/shared-moment-gallery";
export function Studies() {
return (
<SharedMomentGallery
items={studies.map((study) => ({
id: study.id,
title: study.title,
category: study.category,
date: study.date,
caption: study.caption,
alt: study.alt,
visual: <img src={study.image} alt="" />,
span: study.span,
}))}
/>
);
}04Props
| Prop | Type | Default | Notes |
|---|---|---|---|
items | { id: string; title: string; category: string; date: string; caption: string; visual: ReactNode; alt: string; span?: "standard" | "tall" | "wide" }[] | — | The studies, their visuals and their accessible descriptions. `span` controls the thumbnail ratio. |
label | string | "Gallery" | Accessible name for the collection. |
layout | "editorial" | "uniform" | "editorial" | Editorial masonry rhythm or an even grid. |
captions | boolean | true | Show dates beside categories in the grid. |
className | string | — | Forwarded to the root for local layout. |
05Accessibility
- Cards are real buttons labelled with title and category; the artwork itself is not the only accessible name.
- The detail view is a modal dialog with a title, caption description, containment for Tab and Shift+Tab, and focus returned to the source card.
- Escape closes; Left and Right move through the collection; the close and next/previous controls are labelled buttons.
- Body scroll is locked with scrollbar compensation while the reading room is open.
- The shared flight uses FLIP rather than the View Transitions API, so it has the same behaviour in every supported browser. Reduced motion replaces it with an immediate open and close.
- Each study exposes a written alt description in the detail view, not only the photograph.
06Source
2 files, 837 lines. The combined copy is a reference; save each file separately for use.
components/lab/shared-moment-gallery/shared-moment-gallery.tsx— press enter to show or hide the source
"use client";
import {
useCallback,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import "./shared-moment-gallery.css";
export type MomentItem = {
id: string;
title: string;
category: string;
date: string;
caption: string;
/** The image, illustration or composition shown in both sizes. */
visual: ReactNode;
/** A short description for people who cannot see the visual. */
alt: string;
/** Optional editorial emphasis for the thumbnail ratio. */
span?: "standard" | "tall" | "wide";
};
export type SharedMomentGalleryProps = {
items: MomentItem[];
label?: string;
layout?: "editorial" | "uniform";
captions?: boolean;
className?: string;
};
const FOCUSABLE =
'a[href],button:not([disabled]),textarea:not([disabled]),input:not([disabled]),select:not([disabled]),[tabindex]:not([tabindex="-1"])';
let locks = 0;
let release: (() => void) | null = null;
function lockPage() {
if (typeof document === "undefined") return () => {};
locks += 1;
if (locks === 1) {
const body = document.body;
const html = document.documentElement;
const gap = window.innerWidth - html.clientWidth;
const before = {
body: body.style.overflow,
padding: body.style.paddingRight,
html: html.style.overflow,
};
body.style.overflow = "hidden";
html.style.overflow = "hidden";
if (gap > 0) body.style.paddingRight = `${gap}px`;
release = () => {
body.style.overflow = before.body;
body.style.paddingRight = before.padding;
html.style.overflow = before.html;
release = null;
};
}
let done = false;
return () => {
if (done) return;
done = true;
locks = Math.max(0, locks - 1);
if (locks === 0) release?.();
};
}
function prefersReduced() {
return (
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches
);
}
const noopSubscribe = () => () => {};
function useClientReady() {
return useSyncExternalStore(
noopSubscribe,
() => true,
() => false,
);
}
/**
* SHARED MOMENT GALLERY
*
* Opening a card lifts its media from the thumbnail's exact rectangle
* into the detail panel with a FLIP measurement, while the caption
* arrives in a deliberate sequence. Closing runs the same path back to
* the source card. The detail view is a modal dialog with contained
* focus, Escape/arrow keys and a stable non-View-Transition fallback.
*/
export function SharedMomentGallery({
items,
label = "Gallery",
layout = "editorial",
captions = true,
className,
}: SharedMomentGalleryProps) {
const uid = useId();
const [selected, setSelected] = useState<number | null>(null);
const [closing, setClosing] = useState(false);
const ready = useClientReady();
const source = useRef<{ node: HTMLElement; rect: DOMRect } | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
const mediaRef = useRef<HTMLDivElement>(null);
const closeRef = useRef<HTMLButtonElement>(null);
const previousIndex = useRef<number | null>(null);
const dialogTitle = useRef<HTMLHeadingElement>(null);
const closeTimer = useRef<number | null>(null);
useEffect(() => () => {
if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
}, []);
useEffect(() => {
if (selected === null) return;
return lockPage();
}, [selected]);
useEffect(() => {
if (selected === null) return;
const timer = window.setTimeout(() => closeRef.current?.focus(), 40);
return () => window.clearTimeout(timer);
}, [selected]);
const open = (index: number, node: HTMLElement) => {
source.current = { node, rect: node.getBoundingClientRect() };
previousIndex.current = null;
setClosing(false);
setSelected(index);
};
const close = useCallback(() => {
if (selected === null || closing) return;
setClosing(true);
const node = source.current?.node;
const media = mediaRef.current;
const reduced = prefersReduced();
const duration = reduced ? 0 : 300;
const finish = () => {
setSelected(null);
setClosing(false);
const target = source.current?.node;
if (target?.isConnected) target.focus();
};
if (node && media && !reduced) {
const from = media.getBoundingClientRect();
const to = node.getBoundingClientRect();
const dx = to.left - from.left;
const dy = to.top - from.top;
const sx = to.width / Math.max(from.width, 1);
const sy = to.height / Math.max(from.height, 1);
media.animate(
[
{ transform: "none", opacity: 1 },
{
transform: `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`,
opacity: 0.65,
},
],
{ duration, easing: "cubic-bezier(0.4, 0, 0.2, 1)", fill: "forwards" },
);
}
closeTimer.current = window.setTimeout(finish, duration + 20);
}, [selected, closing]);
const go = (delta: number) => {
if (selected === null) return;
previousIndex.current = selected;
setSelected((current) =>
current === null
? null
: (current + delta + items.length) % items.length,
);
};
const onKeyDown = (event: {
key: string;
shiftKey: boolean;
preventDefault: () => void;
}) => {
if (event.key === "Escape") {
event.preventDefault();
close();
return;
}
if (event.key === "ArrowRight") {
event.preventDefault();
go(1);
return;
}
if (event.key === "ArrowLeft") {
event.preventDefault();
go(-1);
return;
}
if (event.key !== "Tab") return;
const panel = panelRef.current;
if (!panel) return;
const nodes = [...panel.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
(node) => node.getClientRects().length > 0,
);
if (!nodes.length) return;
const first = nodes[0];
const last = nodes[nodes.length - 1];
if (!panel.contains(document.activeElement)) {
event.preventDefault();
first.focus();
} else if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
useEffect(() => {
if (selected === null) return;
const handler = (event: globalThis.KeyboardEvent) => {
onKeyDown(event);
};
document.addEventListener("keydown", handler);
return () => document.removeEventListener("keydown", handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selected, closing, items.length]);
/* The media flight happens after the dialog has a real layout. */
useLayoutEffect(() => {
if (selected === null || closing) return;
const media = mediaRef.current;
if (!media) return;
const reduced = prefersReduced();
if (reduced) return;
if (previousIndex.current === null) {
const rect = source.current?.rect;
if (!rect) return;
const target = media.getBoundingClientRect();
const dx = rect.left - target.left;
const dy = rect.top - target.top;
const sx = rect.width / Math.max(target.width, 1);
const sy = rect.height / Math.max(target.height, 1);
media.animate(
[
{
transform: `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`,
borderRadius: "8px",
},
{ transform: "none", borderRadius: "3px" },
],
{
duration: 430,
easing: "cubic-bezier(0.16, 1, 0.3, 1)",
},
);
} else {
media.animate(
[
{ opacity: 0, transform: "scale(1.012)" },
{ opacity: 1, transform: "scale(1)" },
],
{ duration: 280, easing: "cubic-bezier(0.22, 1, 0.36, 1)" },
);
}
previousIndex.current = selected;
}, [selected, closing]);
const item = selected === null ? null : items[selected];
return (
<div
className={`smg-root${className ? ` ${className}` : ""}`}
data-layout={layout}
>
<ul className="smg-grid" aria-label={label}>
{items.map((entry, index) => (
<li
key={entry.id}
className="smg-cell"
data-span={entry.span ?? "standard"}
>
<button
type="button"
className="smg-card"
onClick={(event) => open(index, event.currentTarget)}
aria-label={`${entry.title}, ${entry.category}. Open study.`}
data-active={
selected === index && !closing ? "true" : "false"
}
>
<span className="smg-thumb" aria-hidden="true">
{entry.visual}
</span>
<span className="smg-card-meta">
<span className="smg-card-title">{entry.title}</span>
<span className="smg-card-line">
{entry.category}
{captions ? ` · ${entry.date}` : ""}
</span>
</span>
</button>
</li>
))}
</ul>
{ready && item && selected !== null
? createPortal(
<div
className="smg-overlay"
data-closing={closing ? "true" : "false"}
>
<div
className="smg-backdrop"
aria-hidden="true"
onClick={() => {
if (!closing) close();
}}
/>
<div
ref={panelRef}
className="smg-panel"
role="dialog"
aria-modal="true"
aria-labelledby={`${uid}-title`}
aria-describedby={`${uid}-caption`}
tabIndex={-1}
>
<div ref={mediaRef} className="smg-detail-media" aria-hidden="true">
{item.visual}
</div>
<div className="smg-detail">
<div className="smg-detail-top">
<span className="smg-counter">
{String(selected + 1).padStart(2, "0")} /{" "}
{String(items.length).padStart(2, "0")}
</span>
<button
ref={closeRef}
type="button"
className="smg-close"
onClick={close}
aria-label="Close study"
>
Close
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path
d="M4 4l8 8M12 4l-8 8"
fill="none"
stroke="currentColor"
strokeWidth="1.4"
strokeLinecap="round"
/>
</svg>
</button>
</div>
<div className="smg-detail-meta" key={item.id}>
<p className="smg-detail-category">{item.category}</p>
<h2 id={`${uid}-title`} ref={dialogTitle} tabIndex={-1}>
{item.title}
</h2>
<p className="smg-detail-date">{item.date}</p>
<p id={`${uid}-caption`} className="smg-caption">
{item.caption}
</p>
<p className="smg-alt">{item.alt}</p>
</div>
<div className="smg-nav">
<button type="button" onClick={() => go(-1)} aria-label="Previous study">
<span aria-hidden="true">←</span> Previous
</button>
<button type="button" onClick={() => go(1)} aria-label="Next study">
Next <span aria-hidden="true">→</span>
</button>
</div>
</div>
</div>
</div>,
document.body,
)
: null}
</div>
);
}components/lab/shared-moment-gallery/shared-moment-gallery.css— press enter to show or hide the source
.smg-root {
--smg-ink: #1b1b1d;
--smg-muted: #74716a;
--smg-line: rgba(27, 27, 29, 0.12);
--smg-paper: #f0ede5;
--smg-surface: #fbf9f4;
--smg-ease: cubic-bezier(0.22, 1, 0.36, 1);
min-width: 0;
color: var(--smg-ink);
font: inherit;
}
.smg-grid {
columns: 2;
column-gap: 16px;
margin: 0;
padding: 0;
list-style: none;
}
.smg-cell {
width: 100%;
margin: 0 0 16px;
break-inside: avoid;
min-width: 0;
}
.smg-root[data-layout="uniform"] .smg-grid {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 12px;
columns: auto;
column-gap: normal;
}
.smg-root[data-layout="uniform"] .smg-cell {
margin: 0;
grid-column: span 4;
}
.smg-root[data-layout="uniform"] .smg-cell[data-span="tall"] {
grid-column: span 4;
}
.smg-root[data-layout="uniform"] .smg-cell[data-span="wide"] {
grid-column: span 8;
}
.smg-card {
display: grid;
gap: 9px;
width: 100%;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
text-align: left;
cursor: zoom-in;
}
.smg-card:focus-visible {
outline: 2px solid var(--smg-ink);
outline-offset: 3px;
}
.smg-thumb {
display: block;
overflow: hidden;
border-radius: 4px;
background: #d8d3c8;
aspect-ratio: 4 / 5;
transition:
opacity 220ms ease,
transform 400ms var(--smg-ease);
}
.smg-cell[data-span="wide"] .smg-thumb {
aspect-ratio: 16 / 9;
}
.smg-cell[data-span="tall"] .smg-thumb {
aspect-ratio: 3 / 5;
}
.smg-thumb > * {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 700ms var(--smg-ease);
}
.smg-card:hover .smg-thumb > *,
.smg-card:focus-visible .smg-thumb > * {
transform: scale(1.025);
}
.smg-card[data-active="true"] .smg-thumb {
opacity: 0.38;
}
.smg-card-meta {
display: grid;
gap: 1px;
min-width: 0;
}
.smg-card-title {
font-size: 0.8125rem;
font-weight: 600;
letter-spacing: -0.005em;
line-height: 1.35;
overflow-wrap: anywhere;
}
.smg-card-line {
color: var(--smg-muted);
font-family: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace;
font-size: 0.5625rem;
letter-spacing: 0.08em;
text-transform: uppercase;
line-height: 1.4;
}
.smg-overlay {
--smg-ink: #f2eee4;
--smg-muted: rgba(242, 238, 228, 0.66);
--smg-line: rgba(242, 238, 228, 0.16);
--smg-paper: #131315;
--smg-surface: #19191c;
position: fixed;
inset: 0;
z-index: 90;
display: grid;
place-items: center;
padding: 28px;
color: var(--smg-ink);
font: inherit;
}
.smg-backdrop {
position: absolute;
inset: 0;
background: rgba(12, 12, 14, 0.76);
opacity: 1;
transition: opacity 260ms ease;
}
.smg-overlay[data-closing="true"] .smg-backdrop {
opacity: 0;
}
.smg-panel {
position: relative;
display: grid;
grid-template-columns: minmax(0, 1.25fr) minmax(300px, 0.75fr);
width: min(1080px, 100%);
max-height: min(86dvh, 760px);
overflow: hidden;
border: 1px solid rgba(242, 238, 228, 0.14);
border-radius: 6px;
background: var(--smg-surface);
box-shadow: 0 40px 120px -50px rgba(0, 0, 0, 0.8);
transition:
background-color 240ms ease,
border-color 240ms ease,
box-shadow 240ms ease;
}
.smg-overlay[data-closing="true"] .smg-panel {
background: transparent;
border-color: transparent;
box-shadow: none;
}
.smg-panel:focus {
outline: none;
}
.smg-detail-media {
position: relative;
z-index: 2;
min-height: 0;
overflow: hidden;
background: #24242a;
transform-origin: top left;
will-change: transform;
}
.smg-detail-media > * {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.smg-detail {
display: flex;
flex-direction: column;
min-height: 0;
overflow-y: auto;
padding: 20px 24px 20px;
border-left: 1px solid var(--smg-line);
background: var(--smg-surface);
scrollbar-width: thin;
}
.smg-overlay[data-closing="true"] .smg-detail {
opacity: 0;
transition: opacity 120ms ease;
}
.smg-detail-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.smg-counter {
font-family: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace;
font-size: 0.625rem;
letter-spacing: 0.12em;
color: var(--smg-muted);
}
.smg-close {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 32px;
padding: 4px 9px;
border: 1px solid var(--smg-line);
border-radius: 999px;
background: transparent;
color: var(--smg-ink);
font: inherit;
font-size: 0.6875rem;
font-weight: 600;
cursor: pointer;
transition:
background-color 150ms ease,
color 150ms ease;
}
.smg-close:hover {
background: var(--smg-ink);
color: var(--smg-paper);
}
.smg-close:focus-visible,
.smg-nav button:focus-visible {
outline: 2px solid var(--smg-ink);
outline-offset: 2px;
}
.smg-close svg {
width: 12px;
height: 12px;
}
.smg-detail-meta {
display: grid;
align-content: center;
flex: 1;
gap: 9px;
padding: 32px 0 24px;
}
.smg-detail-category {
margin: 0;
color: #d8c79d;
font-family: ui-monospace, "SF Mono", "Cascadia Mono", Consolas, monospace;
font-size: 0.625rem;
letter-spacing: 0.14em;
text-transform: uppercase;
animation: smg-enter 380ms var(--smg-ease) both;
}
.smg-detail-meta h2 {
margin: 0;
font-size: clamp(1.5rem, 3vw, 2.1rem);
font-weight: 550;
letter-spacing: -0.035em;
line-height: 1.08;
text-wrap: balance;
animation: smg-enter 420ms 60ms var(--smg-ease) both;
}
.smg-detail-meta h2:focus {
outline: none;
}
.smg-detail-date {
margin: 0;
color: var(--smg-muted);
font-size: 0.75rem;
animation: smg-enter 420ms 110ms var(--smg-ease) both;
}
.smg-caption {
margin: 12px 0 0;
color: var(--smg-muted);
font-size: 0.875rem;
line-height: 1.6;
text-wrap: pretty;
animation: smg-enter 440ms 170ms var(--smg-ease) both;
}
.smg-alt {
margin: 0;
padding-top: 12px;
border-top: 1px solid var(--smg-line);
color: var(--smg-muted);
font-size: 0.6875rem;
line-height: 1.55;
animation: smg-enter 440ms 220ms var(--smg-ease) both;
}
.smg-nav {
display: flex;
justify-content: space-between;
gap: 8px;
padding-top: 12px;
border-top: 1px solid var(--smg-line);
}
.smg-nav button {
display: inline-flex;
align-items: center;
gap: 7px;
min-height: 36px;
padding: 4px 2px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--smg-ink);
font: inherit;
font-size: 0.75rem;
font-weight: 550;
cursor: pointer;
}
.smg-nav button:hover {
color: #d8c79d;
}
@keyframes smg-enter {
from {
opacity: 0;
transform: translateY(9px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (max-width: 900px) {
.smg-panel {
grid-template-columns: minmax(0, 1fr) minmax(260px, 0.8fr);
}
.smg-root[data-layout="uniform"] .smg-cell,
.smg-root[data-layout="uniform"] .smg-cell[data-span="tall"] {
grid-column: span 6;
}
.smg-root[data-layout="uniform"] .smg-cell[data-span="wide"] {
grid-column: span 12;
}
}
@media (max-width: 720px) {
.smg-root[data-layout="editorial"] .smg-grid {
columns: 1;
}
.smg-overlay {
padding: 0;
align-items: stretch;
}
.smg-panel {
grid-template-columns: 1fr;
grid-template-rows: minmax(0, 52dvh) minmax(0, 1fr);
width: 100%;
max-height: none;
height: 100dvh;
border: 0;
border-radius: 0;
}
.smg-detail {
padding: 18px 20px calc(18px + env(safe-area-inset-bottom));
border-left: 0;
border-top: 1px solid var(--smg-line);
}
.smg-detail-meta {
padding: 22px 0 18px;
}
.smg-overlay[data-closing="true"] .smg-panel {
background: transparent;
}
.smg-overlay[data-closing="true"] .smg-detail {
opacity: 0;
}
}
@media (max-width: 520px) {
.smg-root[data-layout="uniform"] .smg-cell,
.smg-root[data-layout="uniform"] .smg-cell[data-span="tall"],
.smg-root[data-layout="uniform"] .smg-cell[data-span="wide"] {
grid-column: span 12;
}
}
@media (prefers-reduced-motion: reduce) {
.smg-backdrop,
.smg-panel,
.smg-detail,
.smg-thumb,
.smg-thumb > * {
transition-duration: 0.01ms;
}
.smg-detail-category,
.smg-detail-meta h2,
.smg-detail-date,
.smg-caption,
.smg-alt {
animation-duration: 0.01ms;
}
.smg-detail-media {
transform: none !important;
}
}