无界空间照片墙
源自 cuvii.dev/zh/photography 的无界二维空间摄影墙:不同长宽比照片等比居中嵌在纯白纸感环面网格中,支持惯性拖拽、滚轮平滑漫游与对数锚点缩放;点击任意照片不弹遮罩弹窗,而是原地放大并将四周邻居整列整行推开留出呼吸边缘,支持方向键、点击邻格与拖拽四角双线性滑移切图。
桌面与空间容器9 项可调参数React + Tailwind
演示与调参
1:1 还原原站 createWallEngine 的五个底层细节:① 300×300 均匀晶格内按 maxTile = 200 等比居中横竖构图,零圆角零阴影,加载前先铺照片主色再以 320ms 线性显影;② 无边界环面取模((-∞, +∞) 无限漫游),拖拽采用 0.4/0.6 EMA 速度滤波与 0.95^(dt/16.67) 惯性衰减(停顿 >80ms 抬手自动清零速度),滚轮与对数空间缩放共用 τ=70ms 指数阻尼并死锁鼠标屏幕锚点;③ 点击看图不盖黑底弹窗,而是用 0.28s / bounce 0.08 弹簧放大目标图,同时按 Math.sign(col - openCol) * pushX 整列整行对称推开四周缩略图;④ 展开态按方向键、点边缘露出的邻格或手势拖拽时,在连续网格坐标 (gx, gy) 上做四角双线性插值(stiffness 180 / damping 28);⑤ 底部日期与 Unsplash 虚线外链延迟 450ms 等画面落稳后再淡入,搭配 SVG feTurbulence 微噪点纸感肌理。
预设
布局结构
图注日期语言
单格照片占比0.67
画布缩放倍率0.70
展开推开间距48px
动效反馈
漫游阻尼时间常数70ms
展开弹簧时长0.28s
展开回弹系数0.08
表面与质感
画布纸张底色
spatial-photo-wall
复刻提示词
请用 React + 高分屏 HTML5 Canvas 完整复刻 cuvii.dev/zh/photography 的「无界空间照片墙(Spatial Photo Wall)」组件及其全部空间交互物理。
纯画布纸感肌理(无顶栏干扰、整区铺满):
- 整个容器 100% 铺满可交互空间画布,不加内嵌外框或顶部导航文字;底色采用纯净画廊白底(#FFFFFF,主字色 #0A0A0A),顶层覆盖 pointer-events: none 的 180×180 SVG feTurbulence 微噪点纸张肌理(baseFrequency 0.85,mix-blend-mode: overlay,不透明度 0.22)。
无界环面网格与漫游缩放物理:
- 世界空间采用 300×300 均匀方格,在 (-∞, +∞) 全方向做环面取模无限平铺,无硬边界。每张横构图或竖构图照片保持原始长宽比,居中放入 `maxTile = 300 × 0.67`(最长边 201 世界单位)的方格内,0 圆角、0 阴影、无悬停卡片。纹理未解码前先渲染照片主色调 `photo.color`,解码完成后用 320ms 线性显影过渡。
- 初始相机缩放设为 `0.7`(范围 0.22–3.0)。双指滚轮漫游与以光标为屏幕锚点的对数空间缩放(`Cmd/Ctrl + 滚轮`、双指捏合、`+`/`-` 键)统一使用时间常数 `τ = 70ms` 的指数阻尼 `u = 1 - Math.exp(-dt / 70)`。
- 指针拖拽时 1:1 紧跟手指,按 `0.4/0.6` 指数滑动平均采样速度;松手时若停顿超过 80ms 则清零惯性,否则以 `0.95^(dt / 16.67)` 阻尼滑行(累计位移 < 8px 判定为点击看图)。
无遮罩「推开邻居」看图与四角双线性滑移:
- 点击任意照片或按 Enter 打开中心照片时,绝不弹出黑底遮罩弹窗:用 `visualDuration: 0.28s, bounce: 0.08` 二阶弹簧将选中照片平滑放大至舞台中央,同时将其余列按 `Math.sign(col - openCol) * pushX`(水平安全间距 48px)、其余行按 `Math.sign(row - openRow) * pushY`(垂直安全间距 72px)对称向四周推开,让相邻照片继续在白纸边缘露头。
- 展开状态下支持 `ArrowLeft/Right/Up/Down` 四向切图、直接点击边缘露头的邻格缩略图切图,以及按住拖拽手势连续滑移:在二维浮点网格坐标 `(gx, gy)` 上对相邻四个格点的展开姿态做双线性插值,并由 `{ stiffness: 180, damping: 28 }` 弹簧平滑驱动。
- 大图正下方精确对齐渲染 `.photo-caption`:切图运动中立即隐藏,落稳延迟 450ms 后用 300ms 淡入(左侧 66% 墨色等宽拍摄年月,采用中文年月格式如 2025年1月,右侧 Unsplash 图标 + 1px 虚线悬停变实线外链 + 右上箭头);点击大图或空白处、按 Esc、滚轮滚动或捏合缩小即可丝滑归位。代码
SpatialPhotoWall.tsxReact · Tailwind
"use client";
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
const wallParams = {
"copyLang": "zh",
"tileFillRatio": 0.67,
"defaultZoom": 0.7,
"pushClearancePx": 48,
"panTauMs": 70,
"openDuration": 0.28,
"openBounce": 0.08,
"paperTheme": "paper",
"paperGrain": true
};
export interface SpatialPhotoWallParams {
copyLang?: string;
tileFillRatio?: number;
defaultZoom?: number;
pushClearancePx?: number;
panTauMs?: number;
openDuration?: number;
openBounce?: number;
paperTheme?: string;
paperGrain?: boolean;
}
interface PhotoItem {
id: string;
src: string;
alt: string;
width: number;
height: number;
color: string;
taken: string;
unsplashUrl: string;
}
// 30 curated Unsplash-licensed photographs matching the initial 6×5 center window of cuvii.dev/zh/photography
const PHOTOS: PhotoItem[] = [
{
id: "20250118-DSCF3063",
src: "/recipes/photo-wall/01.webp",
alt: "Hotel on a snowy hill with a monument",
width: 7728,
height: 5152,
color: "#a9aba9",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/hotel-on-a-snowy-hill-with-a-monument-bdG8_-fQ3lo?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240218-DSCF3547",
src: "/recipes/photo-wall/02.webp",
alt: "Busy city street with traffic and tall buildings",
width: 5152,
height: 7728,
color: "#545359",
taken: "2024-02",
unsplashUrl:
"https://unsplash.com/photos/busy-city-street-with-traffic-and-tall-buildings-lkeKcwBXGU4?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250118-DSCF3071",
src: "/recipes/photo-wall/03.webp",
alt: "Ferris wheel by the sea in winter landscape",
width: 7728,
height: 5152,
color: "#a5a8a3",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/ferris-wheel-by-the-sea-in-winter-landscape-1xQvwQfFfJ4?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240105-DSCF6991",
src: "/recipes/photo-wall/04.webp",
alt: "Giant gundam robot in a dark industrial setting",
width: 5152,
height: 7728,
color: "#232329",
taken: "2024-01",
unsplashUrl:
"https://unsplash.com/photos/giant-gundam-robot-in-a-dark-industrial-setting-eZKI6Lm-S-4?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250118-DSCF3044",
src: "/recipes/photo-wall/05.webp",
alt: "Lighthouse on snowy cliff overlooking the ocean",
width: 5152,
height: 7728,
color: "#aeb4b4",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/lighthouse-on-snowy-cliff-overlooking-the-ocean-B-tfBqFENUA?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250117-DSCF2568",
src: "/recipes/photo-wall/06.webp",
alt: "Tram arriving at station in snowy city street",
width: 7728,
height: 5152,
color: "#8a8b90",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/tram-arriving-at-station-in-snowy-city-street-DH5JKjqXvWI?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250111-DSCF1279",
src: "/recipes/photo-wall/07.webp",
alt: "Snowy bridge over a river with forest background",
width: 7728,
height: 5152,
color: "#73796e",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/snowy-bridge-over-a-river-with-forest-background-VVfBB63EIyQ?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240112-DSCF7797",
src: "/recipes/photo-wall/08.webp",
alt: "Majestic mountain peak bathed in golden sunset light",
width: 7728,
height: 4347,
color: "#2e2f2f",
taken: "2024-01",
unsplashUrl:
"https://unsplash.com/photos/majestic-mountain-peak-bathed-in-golden-sunset-light-92UMzEr2idk?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250118-DSCF3037",
src: "/recipes/photo-wall/09.webp",
alt: "Ferris wheel by the ocean in winter",
width: 5152,
height: 7728,
color: "#b2b4b1",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/ferris-wheel-by-the-ocean-in-winter-_KEWzlUflh8?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240918-DSCF8924",
src: "/recipes/photo-wall/10.webp",
alt: "Cows grazing in a green field under a blue sky",
width: 5152,
height: 7728,
color: "#7b796d",
taken: "2024-09",
unsplashUrl:
"https://unsplash.com/photos/cows-grazing-in-a-green-field-under-a-blue-sky-aoFRnZNZBJU?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240322-DSCF4465",
src: "/recipes/photo-wall/11.webp",
alt: "Rooftop basketball courts with blue markings and hoops",
width: 5152,
height: 7728,
color: "#729192",
taken: "2024-03",
unsplashUrl:
"https://unsplash.com/photos/rooftop-basketball-courts-with-blue-markings-and-hoops-sCBK_Hzy8SQ?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250117-DSCF2640",
src: "/recipes/photo-wall/12.webp",
alt: "Person wearing a snow covered hat and scarf in winter",
width: 7728,
height: 5152,
color: "#989696",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/person-wearing-a-snow-covered-hat-and-scarf-in-winter-3fvDE0bU9BE?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240804-DSCF7183",
src: "/recipes/photo-wall/13.webp",
alt: "Red sun setting behind a distant bridge",
width: 7728,
height: 5152,
color: "#27241d",
taken: "2024-08",
unsplashUrl:
"https://unsplash.com/photos/red-sun-setting-behind-a-distant-bridge-y0hS018kYP4?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240329-DSCF4712",
src: "/recipes/photo-wall/14.webp",
alt: "Modern city skyline with cars on the road",
width: 5152,
height: 7728,
color: "#676a67",
taken: "2024-03",
unsplashUrl:
"https://unsplash.com/photos/modern-city-skyline-with-cars-on-the-road-rPc_kgzqV7E?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240916-DSCF7972",
src: "/recipes/photo-wall/15.webp",
alt: "Golden hour light on rolling hills and a river",
width: 5152,
height: 7728,
color: "#686558",
taken: "2024-09",
unsplashUrl:
"https://unsplash.com/photos/golden-hour-light-on-rolling-hills-and-a-river-G1b0U14_ayc?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250117-DSCF2583",
src: "/recipes/photo-wall/16.webp",
alt: "View from train cabin during snowfall",
width: 7728,
height: 5152,
color: "#6d6c6c",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/view-from-train-cabin-during-snowfall-AfpqqAmG4pE?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240917-DSCF8483",
src: "/recipes/photo-wall/17.webp",
alt: "Industrial smokestacks emitting steam against a cloudy sky",
width: 5152,
height: 7728,
color: "#7c7a63",
taken: "2024-09",
unsplashUrl:
"https://unsplash.com/photos/industrial-smokestacks-emitting-steam-against-a-cloudy-sky-urcUlO1bju8?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250117-DSCF2703",
src: "/recipes/photo-wall/18.webp",
alt: "A postal worker rides a motorcycle in heavy snow",
width: 7728,
height: 5152,
color: "#9a959a",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/a-postal-worker-rides-a-motorcycle-in-heavy-snow-khzJq4VzCwQ?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240104-DSCF6647",
src: "/recipes/photo-wall/19.webp",
alt: "Tall tower against a clear blue sky",
width: 5152,
height: 7728,
color: "#7999b3",
taken: "2024-01",
unsplashUrl:
"https://unsplash.com/photos/tall-tower-against-a-clear-blue-sky-p-NbA5fiqi8?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20231229-DSCF5025",
src: "/recipes/photo-wall/20.webp",
alt: "Construction crane against a clear blue sky",
width: 5152,
height: 7728,
color: "#919daa",
taken: "2023-12",
unsplashUrl:
"https://unsplash.com/photos/construction-crane-against-a-clear-blue-sky-tlb6FP4bz8s?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240214-DSCF1135",
src: "/recipes/photo-wall/21.webp",
alt: "Row of orange torii gates in a forest",
width: 5152,
height: 7728,
color: "#13160b",
taken: "2024-02",
unsplashUrl:
"https://unsplash.com/photos/row-of-orange-torii-gates-in-a-forest-Kg4t4KqmXuU?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240707-DSCF6378",
src: "/recipes/photo-wall/22.webp",
alt: "Modern cityscape across a body of water",
width: 7728,
height: 5152,
color: "#6f8585",
taken: "2024-07",
unsplashUrl:
"https://unsplash.com/photos/modern-cityscape-across-a-body-of-water-2Axhu6DHuxI?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240610-DSCF5910",
src: "/recipes/photo-wall/23.webp",
alt: "Yellow construction crane against a blue sky",
width: 4933,
height: 7399,
color: "#6f8c86",
taken: "2024-06",
unsplashUrl:
"https://unsplash.com/photos/yellow-construction-crane-against-a-blue-sky-S-rx_ph_p80?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250118-DSCF2848",
src: "/recipes/photo-wall/24.webp",
alt: "Snow covered road leading to buildings on a clear day",
width: 7728,
height: 5152,
color: "#bdbdbd",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/snow-covered-road-leading-to-buildings-on-a-clear-day-EnMS553X-0g?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240108-DSCF7106",
src: "/recipes/photo-wall/25.webp",
alt: "Modern city skyline with tall buildings under a clear sky",
width: 7728,
height: 5152,
color: "#88a2af",
taken: "2024-01",
unsplashUrl:
"https://unsplash.com/photos/modern-city-skyline-with-tall-buildings-under-a-clear-sky-Boi4ZlocCgM?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240102-DSCF6478",
src: "/recipes/photo-wall/26.webp",
alt: "A modern church with a prominent cross against sky",
width: 7197,
height: 4798,
color: "#949da7",
taken: "2024-01",
unsplashUrl:
"https://unsplash.com/photos/a-modern-church-with-a-prominent-cross-against-sky-8hgrMFi4KbA?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240215-DSCF2012",
src: "/recipes/photo-wall/27.webp",
alt: "Two deer nuzzling each other closely",
width: 7728,
height: 5152,
color: "#94938b",
taken: "2024-02",
unsplashUrl:
"https://unsplash.com/photos/two-deer-nuzzling-each-other-closely-MajTrhEOWTE?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240713-DSCF6499",
src: "/recipes/photo-wall/28.webp",
alt: "Airplane flying through a cloudy blue sky",
width: 5152,
height: 7728,
color: "#c2d3d4",
taken: "2024-07",
unsplashUrl:
"https://unsplash.com/photos/airplane-flying-through-a-cloudy-blue-sky-iCDCAWA3y_s?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20240917-DSCF8134",
src: "/recipes/photo-wall/29.webp",
alt: "Tall concrete pillar stands in a dry grassy field",
width: 4829,
height: 7244,
color: "#9b9283",
taken: "2024-09",
unsplashUrl:
"https://unsplash.com/photos/tall-concrete-pillar-stands-in-a-dry-grassy-field-eD4VKd-7vaY?utm_source=cuvii.dev&utm_medium=referral",
},
{
id: "20250119-DSCF3640",
src: "/recipes/photo-wall/30.webp",
alt: "A boat sails on a misty lake seen through a window",
width: 7728,
height: 5152,
color: "#404547",
taken: "2025-01",
unsplashUrl:
"https://unsplash.com/photos/a-boat-sails-on-a-misty-lake-seen-through-a-window-89CporASv_s?utm_source=cuvii.dev&utm_medium=referral",
},
];
const CELL_SIZE = 300;
const BASE_COLS = 6;
const BASE_ROWS = 5;
const PAPER_GRAIN_SVG = `data:image/svg+xml;utf8,${encodeURIComponent(
`<svg xmlns="http://www.w3.org/2000/svg" width="180" height="180" viewBox="0 0 180 180"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="3" stitchTiles="stitch"/></filter><rect width="180" height="180" filter="url(#n)"/></svg>`
)}`;
const EN_MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
function formatTakenDate(taken: string, isZh: boolean): string {
const [yStr, mStr] = taken.split("-");
const year = Number(yStr);
const month = Number(mStr);
if (!year || !month || month < 1 || month > 12) return taken;
if (isZh) return `${year}年${month}月`;
return `${EN_MONTHS[month - 1]} ${year}`;
}
// Toroidal infinite tile lookup: exact 6×5 initial window for rows 0..4, cols 0..5,
// with a +2 column phase shift per vertical 5-row band so zooming far out avoids straight column seams.
function getTileIndex(col: number, row: number): number {
const bandRow = Math.floor(row / BASE_ROWS);
const localRow = ((row % BASE_ROWS) + BASE_ROWS) % BASE_ROWS;
const localCol = (((col + bandRow * 2) % BASE_COLS) + BASE_COLS) % BASE_COLS;
return localRow * BASE_COLS + localCol;
}
// Synthesize an atmospheric filmic plate if standalone code is pasted into a project without /recipes/photo-wall/*.webp
function createFallbackFilmPlate(photo: PhotoItem, idx: number): HTMLCanvasElement {
const aspect = photo.width / photo.height;
const w = aspect >= 1 ? 360 : Math.round(360 * aspect);
const h = aspect >= 1 ? Math.round(360 / aspect) : 360;
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const ctx = c.getContext("2d");
if (!ctx) return c;
const grad = ctx.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, photo.color);
grad.addColorStop(0.62, photo.color);
grad.addColorStop(1, "#16171a");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, w, h);
// Soft horizon glow & minimalist silhouette
const horizonY = h * (0.52 + ((idx * 17) % 18) * 0.01);
const sunX = w * (0.28 + ((idx * 29) % 44) * 0.01);
const rad = ctx.createRadialGradient(sunX, horizonY - h * 0.08, 4, sunX, horizonY, w * 0.65);
rad.addColorStop(0, "rgba(255, 248, 232, 0.34)");
rad.addColorStop(1, "rgba(255, 248, 232, 0)");
ctx.fillStyle = rad;
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "rgba(12, 13, 16, 0.42)";
ctx.beginPath();
ctx.moveTo(0, h);
ctx.lineTo(0, horizonY);
ctx.quadraticCurveTo(w * 0.38, horizonY - ((idx % 3) - 1) * 18, w, horizonY + 8);
ctx.lineTo(w, h);
ctx.closePath();
ctx.fill();
return c;
}
interface TileEntryCache {
source: CanvasImageSource | null;
loaded: boolean;
reveal: number; // 0 -> 1 over 320ms when loaded onto visible wall
}
interface CaptionDisplayState {
open: boolean;
settled: boolean;
photoIndex: number;
width: number;
x: number;
y: number;
}
interface CornerOpeningPose {
targetCx: number;
targetCy: number;
targetW: number;
targetH: number;
panX: number;
panY: number;
pushX: number;
pushY: number;
}
function SpatialPhotoWall({
params = {},
}: {
params?: SpatialPhotoWallParams;
}) {
const rawUid = useId();
const uid = rawUid.replace(/[^a-zA-Z0-9_-]/g, "");
const isZh = params.copyLang !== "en";
const tileFillRatio = Math.min(0.88, Math.max(0.45, Number(params.tileFillRatio ?? 0.67)));
const defaultZoom = Math.min(2.0, Math.max(0.3, Number(params.defaultZoom ?? 0.7)));
const pushClearancePx = Math.max(16, Number(params.pushClearancePx ?? 48));
const panTauMs = Math.max(20, Number(params.panTauMs ?? 70));
const openDuration = Math.max(0.12, Number(params.openDuration ?? 0.28));
const openBounce = Math.min(0.35, Math.max(0, Number(params.openBounce ?? 0.08)));
const paperTheme = String(params.paperTheme ?? "paper");
const paperGrain = Boolean(params.paperGrain ?? true);
const surfaceColors = useMemo(() => {
if (paperTheme === "darkroom") {
return {
bg: "#0D0D0F",
ink: "#F4F4F6",
isDark: true,
};
}
if (paperTheme === "warm") {
return {
bg: "#F6F4EF",
ink: "#0A0A0A",
isDark: false,
};
}
return {
bg: "#FFFFFF",
ink: "#0A0A0A",
isDark: false,
};
}, [paperTheme]);
const [cursorMode, setCursorMode] = useState<"grab" | "grabbing" | "pointer">("grab");
const cursorModeRef = useRef<"grab" | "grabbing" | "pointer">("grab");
const updateCursor = useCallback((next: "grab" | "grabbing" | "pointer") => {
if (cursorModeRef.current !== next) {
cursorModeRef.current = next;
setCursorMode(next);
}
}, []);
const [captionState, setCaptionState] = useState<CaptionDisplayState>({
open: false,
settled: false,
photoIndex: 14,
width: 240,
x: 0,
y: 0,
});
const captionRef = useRef<CaptionDisplayState>(captionState);
const hostRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
// Live mutable config ref read inside rAF loop without restarting loop or resetting camera
const cfgRef = useRef({
tileFillRatio,
defaultZoom,
pushClearancePx,
panTauMs,
openDuration,
openBounce,
bg: surfaceColors.bg,
});
cfgRef.current = {
tileFillRatio,
defaultZoom,
pushClearancePx,
panTauMs,
openDuration,
openBounce,
bg: surfaceColors.bg,
};
// Engine state preserved across re-renders
const engineRef = useRef({
// Initial camera centered on the 6×5 window (900, 750)
camX: (BASE_COLS * CELL_SIZE) / 2,
camY: (BASE_ROWS * CELL_SIZE) / 2,
targetX: (BASE_COLS * CELL_SIZE) / 2,
targetY: (BASE_ROWS * CELL_SIZE) / 2,
zoom: defaultZoom,
targetZoom: defaultZoom,
anchorX: 0,
anchorY: 0,
// EMA drag velocity & inertia (px / ms in logical stage coordinates)
velX: 0,
velY: 0,
inertiaActive: false,
// Pointer gesture tracking
pointers: new Map<number, { x: number; y: number }>(),
isDragging: false,
movedPx: 0,
downX: 0,
downY: 0,
lastMoveAt: 0,
pinchPrevDist: 0,
pinchPrevMidX: 0,
pinchPrevMidY: 0,
// Open / push-apart & 2D fractional glide state
isOpen: false,
openProgress: 0,
openVel: 0,
openTarget: 0, // 0 = closed, 1 = open
// Continuous 2D grid coordinates while open/closing (e.g. col=2, row=2)
glideX: 2,
glideY: 2,
glideVelX: 0,
glideVelY: 0,
targetGlideX: 2,
targetGlideY: 2,
draggingOpen: false,
openDragStepX: 180,
openDragStepY: 180,
// Interactive pinch/Ctrl+wheel zoom-out-to-close accumulator
zoomOutAccum: 0,
zoomOutSpan: 1,
zoomOutInteracting: false,
wheelEndTimer: 0,
// Stage logical size
viewW: 720,
viewH: 450,
dpr: 1,
});
// React smoothly when user drags the defaultZoom slider in RecipeWorkbench
const prevDefaultZoomRef = useRef(defaultZoom);
useEffect(() => {
if (prevDefaultZoomRef.current !== defaultZoom) {
prevDefaultZoomRef.current = defaultZoom;
const eng = engineRef.current;
eng.anchorX = 0;
eng.anchorY = 0;
eng.targetZoom = defaultZoom;
}
}, [defaultZoom]);
// Image texture & 320ms reveal cache
const imageCacheRef = useRef<TileEntryCache[]>([]);
useEffect(() => {
const cache: TileEntryCache[] = PHOTOS.map(() => ({
source: null,
loaded: false,
reveal: 0,
}));
imageCacheRef.current = cache;
let cancelled = false;
PHOTOS.forEach((photo, idx) => {
const img = new Image();
img.decoding = "async";
img.onload = () => {
if (cancelled) return;
cache[idx].source = img;
cache[idx].loaded = true;
};
img.onerror = () => {
if (cancelled) return;
cache[idx].source = createFallbackFilmPlate(photo, idx);
cache[idx].loaded = true;
};
img.src = photo.src;
});
return () => {
cancelled = true;
};
}, []);
// Helper: compute stage responsive scale so 720px stage matches cuvii.dev 1160px desktop 6×5 density
const getStageScale = useCallback((viewW: number) => {
return viewW < 480 ? viewW / 540 : viewW / 1160;
}, []);
// Helper: compute tile geometry inside its 300×300 world cell
const getTileCellBox = useCallback((photo: PhotoItem, fillRatio: number) => {
const maxTile = CELL_SIZE * fillRatio;
const scale = maxTile / Math.max(photo.width, photo.height);
const w = photo.width * scale;
const h = photo.height * scale;
const x = (CELL_SIZE - w) / 2;
const y = (CELL_SIZE - h) / 2;
return { x, y, w, h, maxTile };
}, []);
// Helper: compute target expanded frame & neighbor push offsets for an integer (col, row)
const computeCornerPose = useCallback(
(
col: number,
row: number,
viewW: number,
viewH: number,
camX: number,
camY: number,
effZoom: number,
fillRatio: number,
clearanceBasePx: number
): CornerOpeningPose => {
const idx = getTileIndex(col, row);
const photo = PHOTOS[idx];
const box = getTileCellBox(photo, fillRatio);
// Origin center relative to viewport center (0, 0)
const originCx = (CELL_SIZE * col + box.x + box.w / 2 - camX) * effZoom;
const originCy = (CELL_SIZE * row + box.y + box.h / 2 - camY) * effZoom;
const stageScale = getStageScale(viewW);
const sideMargin = viewW < 520 ? 16 : 0.14 * viewW;
const topReserve = Math.max(32, Math.round(52 * stageScale));
const bottomReserve = Math.max(48, Math.round(84 * stageScale));
const aspect = photo.width / photo.height;
const maxW = Math.max(80, viewW - 2 * sideMargin);
const maxH = Math.max(80, viewH - topReserve - bottomReserve);
const targetW = Math.min(maxW, maxH * aspect);
const targetH = targetW / aspect;
const targetCx = 0;
const targetCy = -8; // 8px above vertical center so caption clears bottom peeking row
const cellPx = CELL_SIZE * effZoom;
const maxHalfTilePx = (box.maxTile * effZoom) / 2;
const clearX = clearanceBasePx * stageScale;
const clearY = clearanceBasePx * 1.5 * stageScale;
const pushX = Math.max(0, targetW / 2 + clearX - cellPx + maxHalfTilePx);
const pushY = Math.max(0, targetH / 2 + clearY - cellPx + maxHalfTilePx);
return {
targetCx,
targetCy,
targetW,
targetH,
panX: targetCx - originCx,
panY: targetCy - originCy,
pushX,
pushY,
};
},
[getStageScale, getTileCellBox]
);
// Open a specific (col, row) tile
const openTileAt = useCallback(
(col: number, row: number) => {
const eng = engineRef.current;
const reduced =
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
eng.inertiaActive = false;
eng.velX = 0;
eng.velY = 0;
if (!eng.isOpen && eng.openProgress < 0.02) {
eng.glideX = col;
eng.glideY = row;
eng.glideVelX = 0;
eng.glideVelY = 0;
}
eng.targetGlideX = col;
eng.targetGlideY = row;
eng.isOpen = true;
eng.openTarget = 1;
eng.zoomOutInteracting = false;
eng.zoomOutAccum = 0;
if (reduced) {
eng.openProgress = 1;
eng.openVel = 0;
eng.glideX = col;
eng.glideY = row;
}
updateCursor("pointer");
},
[updateCursor]
);
// Close the currently opened tile cleanly back into its settled (col, row) slot
const closeOpenTile = useCallback(
(seedVelocity = 0) => {
const eng = engineRef.current;
if (!eng.isOpen && eng.openTarget === 0) return;
const reduced =
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// Recenter camera onto settled glide target when closing from fully open
const settledCol = Math.round(eng.targetGlideX);
const settledRow = Math.round(eng.targetGlideY);
if (eng.openProgress > 0.98) {
const photo = PHOTOS[getTileIndex(settledCol, settledRow)];
const box = getTileCellBox(photo, cfgRef.current.tileFillRatio);
const tileWorldCx = CELL_SIZE * settledCol + box.x + box.w / 2;
const tileWorldCy = CELL_SIZE * settledRow + box.y + box.h / 2;
const stageScale = getStageScale(eng.viewW);
const effZoom = eng.zoom * stageScale;
const screenDx = (tileWorldCx - eng.camX) * effZoom;
const screenDy = (tileWorldCy - eng.camY) * effZoom;
if (
Math.abs(screenDx) > eng.viewW * 0.32 ||
Math.abs(screenDy) > eng.viewH * 0.32
) {
eng.camX = tileWorldCx;
eng.camY = tileWorldCy;
eng.targetX = tileWorldCx;
eng.targetY = tileWorldCy;
}
}
eng.targetGlideX = settledCol;
eng.targetGlideY = settledRow;
eng.isOpen = false;
eng.openTarget = 0;
eng.zoomOutInteracting = false;
eng.zoomOutAccum = 0;
if (seedVelocity !== 0) {
eng.openVel = seedVelocity;
}
if (reduced) {
eng.openProgress = 0;
eng.openVel = 0;
}
updateCursor("grab");
},
[getStageScale, getTileCellBox, updateCursor]
);
// Step to adjacent photo while open (Arrow keys / discrete wheel)
const stepOpenNeighbor = useCallback((dCol: number, dRow: number) => {
const eng = engineRef.current;
if (!eng.isOpen) return;
const reduced =
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const nextCol = Math.round(eng.targetGlideX) + dCol;
const nextRow = Math.round(eng.targetGlideY) + dRow;
eng.targetGlideX = nextCol;
eng.targetGlideY = nextRow;
if (reduced) {
eng.glideX = nextCol;
eng.glideY = nextRow;
eng.glideVelX = 0;
eng.glideVelY = 0;
}
}, []);
// Main ResizeObserver + 120fps Canvas rAF Loop
useEffect(() => {
const host = hostRef.current;
const canvas = canvasRef.current;
if (!host || !canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const syncSize = () => {
const w = Math.max(240, host.clientWidth);
const h = Math.max(180, host.clientHeight);
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const eng = engineRef.current;
eng.viewW = w;
eng.viewH = h;
eng.dpr = dpr;
const targetPxW = Math.round(w * dpr);
const targetPxH = Math.round(h * dpr);
if (canvas.width !== targetPxW || canvas.height !== targetPxH) {
canvas.width = targetPxW;
canvas.height = targetPxH;
}
};
syncSize();
const ro = new ResizeObserver(syncSize);
ro.observe(host);
let rafId = 0;
let lastTime = performance.now();
const renderFrame = (now: number) => {
const dtMs = Math.min(Math.max(now - lastTime, 0.5), 64);
lastTime = now;
const eng = engineRef.current;
const cfg = cfgRef.current;
const viewW = eng.viewW;
const viewH = eng.viewH;
const dpr = eng.dpr;
const stageScale = getStageScale(viewW);
// 1. Inertia coasting when wall is closed and pointer released
if (eng.inertiaActive && !eng.isDragging && !eng.isOpen) {
const effZoom = eng.zoom * stageScale;
eng.targetX -= (eng.velX * dtMs) / effZoom;
eng.targetY -= (eng.velY * dtMs) / effZoom;
eng.camX = eng.targetX;
eng.camY = eng.targetY;
const decay = Math.pow(0.95, dtMs / (1000 / 60));
eng.velX *= decay;
eng.velY *= decay;
if (Math.hypot(eng.velX, eng.velY) < 0.005) {
eng.velX = 0;
eng.velY = 0;
eng.inertiaActive = false;
}
}
// 2. Exponential camera damping u = 1 - exp(-dt / tau)
const u = 1 - Math.exp(-dtMs / cfg.panTauMs);
if (!eng.isDragging) {
eng.camX += (eng.targetX - eng.camX) * u;
eng.camY += (eng.targetY - eng.camY) * u;
if (
Math.hypot(eng.targetX - eng.camX, eng.targetY - eng.camY) *
eng.zoom *
stageScale <
0.05
) {
eng.camX = eng.targetX;
eng.camY = eng.targetY;
}
}
// 3. Log-space anchor-preserving zoom interpolation
const minZoom = 0.22;
const maxZoom = 3.0;
eng.targetZoom = Math.min(maxZoom, Math.max(minZoom, eng.targetZoom));
if (Math.abs(eng.targetZoom - eng.zoom) > 1e-4) {
const nextZoom = Math.exp(
Math.log(eng.zoom) + (Math.log(eng.targetZoom) - Math.log(eng.zoom)) * u
);
const snappedZoom =
Math.abs(nextZoom - eng.targetZoom) < 1e-4 ? eng.targetZoom : nextZoom;
const dInv = 1 / (eng.zoom * stageScale) - 1 / (snappedZoom * stageScale);
eng.camX += eng.anchorX * dInv;
eng.targetX += eng.anchorX * dInv;
eng.camY += eng.anchorY * dInv;
eng.targetY += eng.anchorY * dInv;
eng.zoom = snappedZoom;
}
// 4. Integrate open/close spring (visualDuration = 0.28s, bounce = 0.08)
// Sub-step at <= 8ms for unconditionally stable second-order integration
const subSteps = Math.max(1, Math.ceil(dtMs / 8));
const dtSec = dtMs / 1000 / subSteps;
const omega = (2 * Math.PI) / Math.max(0.12, cfg.openDuration);
const zeta = Math.max(0.15, 1 - cfg.openBounce);
const openStiff = omega * omega;
const openDamp = 2 * zeta * omega;
// Adjacent glide spring (stiffness: 180, damping: 28 from cuvii.dev createWallEngine)
const glideStiff = 180;
const glideDamp = 28;
for (let s = 0; s < subSteps; s++) {
if (!eng.zoomOutInteracting) {
const disp = eng.openProgress - eng.openTarget;
const acc = -openStiff * disp - openDamp * eng.openVel;
eng.openVel += acc * dtSec;
eng.openProgress += eng.openVel * dtSec;
if (
Math.abs(eng.openTarget - eng.openProgress) < 0.0008 &&
Math.abs(eng.openVel) < 0.008
) {
eng.openProgress = eng.openTarget;
eng.openVel = 0;
}
}
if (!eng.draggingOpen) {
const dxG = eng.glideX - eng.targetGlideX;
const dyG = eng.glideY - eng.targetGlideY;
eng.glideVelX += (-glideStiff * dxG - glideDamp * eng.glideVelX) * dtSec;
eng.glideVelY += (-glideStiff * dyG - glideDamp * eng.glideVelY) * dtSec;
eng.glideX += eng.glideVelX * dtSec;
eng.glideY += eng.glideVelY * dtSec;
if (
Math.hypot(eng.targetGlideX - eng.glideX, eng.targetGlideY - eng.glideY) <
0.0005 &&
Math.hypot(eng.glideVelX, eng.glideVelY) < 0.01
) {
eng.glideX = eng.targetGlideX;
eng.glideY = eng.targetGlideY;
eng.glideVelX = 0;
eng.glideVelY = 0;
}
}
}
const openP = Math.max(0, Math.min(1.12, eng.openProgress));
// When fully settled open (openP === 1), camX/camY algebraically cancel out of screen poses,
// so we keep camX/camY tracking glideX/glideY so visible tile culling never runs out on long glides.
if (eng.isOpen && Math.abs(eng.openProgress - 1) < 0.0015 && eng.openVel === 0) {
const trackCol = Math.round(eng.glideX);
const trackRow = Math.round(eng.glideY);
const trackBox = getTileCellBox(
PHOTOS[getTileIndex(trackCol, trackRow)],
cfg.tileFillRatio
);
const wx = CELL_SIZE * trackCol + trackBox.x + trackBox.w / 2;
const wy = CELL_SIZE * trackRow + trackBox.y + trackBox.h / 2;
if (
Math.abs(wx - eng.camX) > CELL_SIZE * 1.5 ||
Math.abs(wy - eng.camY) > CELL_SIZE * 1.5
) {
eng.camX = wx;
eng.camY = wy;
eng.targetX = wx;
eng.targetY = wy;
}
}
const effZoom = eng.zoom * stageScale;
const cellPx = CELL_SIZE * effZoom;
// 5. Determine visible column/row range with generous buffer for push-apart transition
const padWorld = CELL_SIZE * 2;
const halfWorldW = viewW / (2 * effZoom) + padWorld;
const halfWorldH = viewH / (2 * effZoom) + padWorld;
const minCol = Math.floor((eng.camX - halfWorldW) / CELL_SIZE);
const maxCol = Math.ceil((eng.camX + halfWorldW) / CELL_SIZE);
const minRow = Math.floor((eng.camY - halfWorldH) / CELL_SIZE);
const maxRow = Math.ceil((eng.camY + halfWorldH) / CELL_SIZE);
// Precompute 4-corner bilinear opening poses when openP > 0
const hasOpenEffect = openP > 0.0005;
let c0 = 0;
let r0 = 0;
let w00 = 1;
let w10 = 0;
let w01 = 0;
let w11 = 0;
let pose00: CornerOpeningPose | null = null;
let pose10: CornerOpeningPose | null = null;
let pose01: CornerOpeningPose | null = null;
let pose11: CornerOpeningPose | null = null;
if (hasOpenEffect) {
c0 = Math.floor(eng.glideX);
r0 = Math.floor(eng.glideY);
const fx = eng.glideX - c0;
const fy = eng.glideY - r0;
w00 = (1 - fx) * (1 - fy);
w10 = fx * (1 - fy);
w01 = (1 - fx) * fy;
w11 = fx * fy;
pose00 = computeCornerPose(
c0,
r0,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
);
pose10 =
w10 > 0.0001
? computeCornerPose(
c0 + 1,
r0,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
)
: pose00;
pose01 =
w01 > 0.0001
? computeCornerPose(
c0,
r0 + 1,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
)
: pose00;
pose11 =
w11 > 0.0001
? computeCornerPose(
c0 + 1,
r0 + 1,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
)
: pose00;
// Update drag sensitivity step (1/3 of pushed neighbor distance = 1 grid unit)
eng.openDragStepX = Math.max(48, (cellPx + pose00.pushX) / 2.6);
eng.openDragStepY = Math.max(48, (cellPx + pose00.pushY) / 2.6);
}
// 6. Clear & draw orthographic photo planes onto high-DPI canvas
ctx.save();
ctx.scale(dpr, dpr);
ctx.fillStyle = cfg.bg;
ctx.fillRect(0, 0, viewW, viewH);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
const cache = imageCacheRef.current;
// Advance 320ms linear texture reveal for loaded photos
for (let i = 0; i < cache.length; i++) {
if (cache[i].loaded && cache[i].reveal < 1) {
cache[i].reveal = Math.min(1, cache[i].reveal + dtMs / 320);
}
}
const activeNearestCol = Math.round(eng.glideX);
const activeNearestRow = Math.round(eng.glideY);
const evaluateTileScreenRect = (col: number, row: number) => {
const idx = getTileIndex(col, row);
const photo = PHOTOS[idx];
const box = getTileCellBox(photo, cfg.tileFillRatio);
const baseCx = (CELL_SIZE * col + box.x + box.w / 2 - eng.camX) * effZoom;
const baseCy = (CELL_SIZE * row + box.y + box.h / 2 - eng.camY) * effZoom;
const baseW = box.w * effZoom;
const baseH = box.h * effZoom;
if (!hasOpenEffect || !pose00 || !pose10 || !pose01 || !pose11) {
return {
idx,
photo,
cx: viewW / 2 + baseCx,
cy: viewH / 2 + baseCy,
w: baseW,
h: baseH,
};
}
const evalUnderCorner = (ck: number, rk: number, p: CornerOpeningPose) => {
if (col === ck && row === rk) {
return { cx: p.targetCx, cy: p.targetCy, w: p.targetW, h: p.targetH };
}
return {
cx: baseCx + p.panX + Math.sign(col - ck) * p.pushX,
cy: baseCy + p.panY + Math.sign(row - rk) * p.pushY,
w: baseW,
h: baseH,
};
};
const r00 = evalUnderCorner(c0, r0, pose00);
const r10 = w10 > 0.0001 ? evalUnderCorner(c0 + 1, r0, pose10) : r00;
const r01 = w01 > 0.0001 ? evalUnderCorner(c0, r0 + 1, pose01) : r00;
const r11 = w11 > 0.0001 ? evalUnderCorner(c0 + 1, r0 + 1, pose11) : r00;
const openCx = w00 * r00.cx + w10 * r10.cx + w01 * r01.cx + w11 * r11.cx;
const openCy = w00 * r00.cy + w10 * r10.cy + w01 * r01.cy + w11 * r11.cy;
const openW = w00 * r00.w + w10 * r10.w + w01 * r01.w + w11 * r11.w;
const openH = w00 * r00.h + w10 * r10.h + w01 * r01.h + w11 * r11.h;
return {
idx,
photo,
cx: viewW / 2 + baseCx + (openCx - baseCx) * openP,
cy: viewH / 2 + baseCy + (openCy - baseCy) * openP,
w: baseW + (openW - baseW) * openP,
h: baseH + (openH - baseH) * openP,
};
};
const drawSingleTile = (
idx: number,
photo: PhotoItem,
cx: number,
cy: number,
w: number,
h: number
) => {
const x = cx - w / 2;
const y = cy - h / 2;
if (x + w < -2 || x > viewW + 2 || y + h < -2 || y > viewH + 2) return;
const entry = cache[idx];
const reveal = entry?.reveal ?? 0;
if (reveal < 1) {
ctx.fillStyle = photo.color;
ctx.fillRect(x, y, w, h);
}
if (entry?.source && reveal > 0) {
if (reveal < 1) {
ctx.save();
ctx.globalAlpha = reveal;
ctx.drawImage(entry.source, x, y, w, h);
ctx.restore();
} else {
ctx.drawImage(entry.source, x, y, w, h);
}
}
};
let deferredActive: {
idx: number;
photo: PhotoItem;
cx: number;
cy: number;
w: number;
h: number;
} | null = null;
for (let r = minRow; r <= maxRow; r++) {
for (let c = minCol; c <= maxCol; c++) {
const rect = evaluateTileScreenRect(c, r);
if (hasOpenEffect && c === activeNearestCol && r === activeNearestRow) {
deferredActive = rect;
} else {
drawSingleTile(rect.idx, rect.photo, rect.cx, rect.cy, rect.w, rect.h);
}
}
}
// Active / transitioning tile renders last (renderOrder = 1)
if (deferredActive) {
drawSingleTile(
deferredActive.idx,
deferredActive.photo,
deferredActive.cx,
deferredActive.cy,
deferredActive.w,
deferredActive.h
);
}
ctx.restore();
// 7. Sync HTML .photo-caption overlay position & settled state without redundant re-renders
const glideSettled =
!eng.draggingOpen &&
!eng.zoomOutInteracting &&
Math.hypot(eng.targetGlideX - eng.glideX, eng.targetGlideY - eng.glideY) < 0.04;
const shouldShowCaption = eng.isOpen && eng.openTarget === 1 && glideSettled;
if (eng.isOpen && pose00) {
const settledCol = Math.round(eng.targetGlideX);
const settledRow = Math.round(eng.targetGlideY);
const settledPose = computeCornerPose(
settledCol,
settledRow,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
);
const capW = Math.round(settledPose.targetW);
const capX = Math.round(viewW / 2 + settledPose.targetCx - settledPose.targetW / 2);
const capY = Math.round(
viewH / 2 + settledPose.targetCy + settledPose.targetH / 2 + 12
);
const pIdx = getTileIndex(settledCol, settledRow);
const prev = captionRef.current;
if (
!prev.open ||
prev.settled !== shouldShowCaption ||
prev.photoIndex !== pIdx ||
prev.width !== capW ||
prev.x !== capX ||
prev.y !== capY
) {
const nextCap: CaptionDisplayState = {
open: true,
settled: shouldShowCaption,
photoIndex: pIdx,
width: capW,
x: capX,
y: capY,
};
captionRef.current = nextCap;
setCaptionState(nextCap);
}
} else if (captionRef.current.open) {
const closedCap: CaptionDisplayState = {
...captionRef.current,
open: false,
settled: false,
};
captionRef.current = closedCap;
setCaptionState(closedCap);
}
rafId = window.requestAnimationFrame(renderFrame);
};
rafId = window.requestAnimationFrame(renderFrame);
return () => {
ro.disconnect();
window.cancelAnimationFrame(rafId);
};
}, [computeCornerPose, getStageScale, getTileCellBox]);
// Convert client pointer coordinates to logical stage coordinates (handles ScaledStagePreview CSS scale)
const clientToStage = useCallback((clientX: number, clientY: number) => {
const host = hostRef.current;
if (!host) return { x: 0, y: 0 };
const rect = host.getBoundingClientRect();
const scaleX = rect.width > 0 ? host.clientWidth / rect.width : 1;
const scaleY = rect.height > 0 ? host.clientHeight / rect.height : 1;
return {
x: (clientX - rect.left) * scaleX,
y: (clientY - rect.top) * scaleY,
};
}, []);
// Hit-test stage (x, y) against visible tiles (in current open or closed state)
const hitTestTile = useCallback(
(stageX: number, stageY: number): { col: number; row: number; isCenterOpen: boolean } | null => {
const eng = engineRef.current;
const cfg = cfgRef.current;
const viewW = eng.viewW;
const viewH = eng.viewH;
const stageScale = getStageScale(viewW);
const effZoom = eng.zoom * stageScale;
const padWorld = CELL_SIZE * 2;
const halfWorldW = viewW / (2 * effZoom) + padWorld;
const halfWorldH = viewH / (2 * effZoom) + padWorld;
const minCol = Math.floor((eng.camX - halfWorldW) / CELL_SIZE);
const maxCol = Math.ceil((eng.camX + halfWorldW) / CELL_SIZE);
const minRow = Math.floor((eng.camY - halfWorldH) / CELL_SIZE);
const maxRow = Math.ceil((eng.camY + halfWorldH) / CELL_SIZE);
const openP = Math.max(0, Math.min(1, eng.openProgress));
const activeCol = Math.round(eng.targetGlideX);
const activeRow = Math.round(eng.targetGlideY);
const pose =
openP > 0.01
? computeCornerPose(
activeCol,
activeRow,
viewW,
viewH,
eng.camX,
eng.camY,
effZoom,
cfg.tileFillRatio,
cfg.pushClearancePx
)
: null;
// Test active center tile first if open
if (pose && openP > 0.5) {
const cx = viewW / 2 + pose.targetCx;
const cy = viewH / 2 + pose.targetCy;
if (
Math.abs(stageX - cx) <= pose.targetW / 2 &&
Math.abs(stageY - cy) <= pose.targetH / 2
) {
return { col: activeCol, row: activeRow, isCenterOpen: true };
}
}
for (let r = minRow; r <= maxRow; r++) {
for (let c = minCol; c <= maxCol; c++) {
if (pose && c === activeCol && r === activeRow) continue;
const idx = getTileIndex(c, r);
const box = getTileCellBox(PHOTOS[idx], cfg.tileFillRatio);
let cx = (CELL_SIZE * c + box.x + box.w / 2 - eng.camX) * effZoom;
let cy = (CELL_SIZE * r + box.y + box.h / 2 - eng.camY) * effZoom;
const w = box.w * effZoom;
const h = box.h * effZoom;
if (pose) {
const pushedCx = cx + pose.panX + Math.sign(c - activeCol) * pose.pushX;
const pushedCy = cy + pose.panY + Math.sign(r - activeRow) * pose.pushY;
cx += (pushedCx - cx) * openP;
cy += (pushedCy - cy) * openP;
}
const screenCx = viewW / 2 + cx;
const screenCy = viewH / 2 + cy;
if (Math.abs(stageX - screenCx) <= w / 2 && Math.abs(stageY - screenCy) <= h / 2) {
return { col: c, row: r, isCenterOpen: false };
}
}
}
return null;
},
[computeCornerPose, getStageScale, getTileCellBox]
);
// Non-passive wheel listener for smooth 2D pan, Ctrl/Cmd anchor zoom, and open-photo navigation
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const handleWheel = (e: WheelEvent) => {
e.preventDefault();
const eng = engineRef.current;
const modeMul = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? eng.viewH : 1;
const dx = e.deltaX * modeMul;
const dy = e.deltaY * modeMul;
const pt = clientToStage(e.clientX, e.clientY);
if (e.ctrlKey || e.metaKey) {
// Pinch / Cmd+Wheel zoom
if (eng.isOpen) {
// Interactive zoom-out-to-close (cuvii.dev spring g)
if (dy > 0) {
const activeCol = Math.round(eng.targetGlideX);
const activeRow = Math.round(eng.targetGlideY);
const idx = getTileIndex(activeCol, activeRow);
const box = getTileCellBox(PHOTOS[idx], cfgRef.current.tileFillRatio);
const effZoom = eng.zoom * getStageScale(eng.viewW);
const originW = Math.max(8, box.w * effZoom);
const span = Math.log(Math.max(1.05, captionRef.current.width / originW));
eng.zoomOutInteracting = true;
eng.zoomOutSpan = span;
eng.zoomOutAccum = Math.min(span, eng.zoomOutAccum + dy * 0.008);
const closedRatio =
(1 - Math.exp(-eng.zoomOutAccum)) / (1 - Math.exp(-span));
eng.openProgress = Math.max(0, 1 - closedRatio);
window.clearTimeout(eng.wheelEndTimer);
eng.wheelEndTimer = window.setTimeout(() => {
eng.zoomOutInteracting = false;
if (eng.openProgress < 0.5) {
closeOpenTile(-1.6);
} else {
eng.openTarget = 1;
}
}, 120);
}
return;
}
eng.inertiaActive = false;
eng.anchorX = pt.x - eng.viewW / 2;
eng.anchorY = pt.y - eng.viewH / 2;
eng.targetZoom = Math.min(
3.0,
Math.max(0.22, eng.targetZoom * Math.exp(-dy * 0.01))
);
return;
}
if (eng.isOpen) {
// Discrete wheel or trackpad swipe while open: close back to wall cleanly on scroll
// (matching live cuvii.dev wheel-to-dismiss feel) unless horizontal swipe dominates
if (Math.abs(dx) > Math.abs(dy) * 1.25 && Math.abs(dx) > 18) {
window.clearTimeout(eng.wheelEndTimer);
eng.wheelEndTimer = window.setTimeout(() => {
stepOpenNeighbor(dx > 0 ? 1 : -1, 0);
}, 40);
} else if (Math.abs(dy) > 12) {
closeOpenTile();
}
return;
}
// Closed wall 2D pan
eng.inertiaActive = false;
eng.velX = 0;
eng.velY = 0;
const effZoom = eng.zoom * getStageScale(eng.viewW);
eng.targetX += dx / effZoom;
eng.targetY += dy / effZoom;
};
host.addEventListener("wheel", handleWheel, { passive: false });
return () => {
host.removeEventListener("wheel", handleWheel);
};
}, [clientToStage, closeOpenTile, getStageScale, getTileCellBox, stepOpenNeighbor]);
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (e.button !== 0 && e.pointerType === "mouse") return;
hostRef.current?.focus({ preventScroll: true });
e.currentTarget.setPointerCapture(e.pointerId);
const pt = clientToStage(e.clientX, e.clientY);
const eng = engineRef.current;
eng.pointers.set(e.pointerId, pt);
if (eng.pointers.size === 2) {
const pts = Array.from(eng.pointers.values());
eng.pinchPrevDist = Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y);
eng.pinchPrevMidX = (pts[0].x + pts[1].x) / 2;
eng.pinchPrevMidY = (pts[0].y + pts[1].y) / 2;
eng.isDragging = false;
eng.draggingOpen = false;
return;
}
eng.downX = pt.x;
eng.downY = pt.y;
eng.movedPx = 0;
eng.velX = 0;
eng.velY = 0;
eng.inertiaActive = false;
eng.lastMoveAt = performance.now();
if (eng.isOpen) {
eng.draggingOpen = true;
eng.glideVelX = 0;
eng.glideVelY = 0;
} else {
eng.isDragging = true;
updateCursor("grabbing");
}
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const eng = engineRef.current;
if (!eng.pointers.has(e.pointerId)) return;
const prevPt = eng.pointers.get(e.pointerId)!;
const pt = clientToStage(e.clientX, e.clientY);
eng.pointers.set(e.pointerId, pt);
// Two-finger touch pinch & pan
if (eng.pointers.size === 2) {
const pts = Array.from(eng.pointers.values());
const dist = Math.max(8, Math.hypot(pts[1].x - pts[0].x, pts[1].y - pts[0].y));
const midX = (pts[0].x + pts[1].x) / 2;
const midY = (pts[0].y + pts[1].y) / 2;
if (eng.isOpen) {
if (dist < eng.pinchPrevDist * 0.78) {
closeOpenTile();
}
return;
}
const stageScale = getStageScale(eng.viewW);
const effZoom = eng.zoom * stageScale;
const dMidX = midX - eng.pinchPrevMidX;
const dMidY = midY - eng.pinchPrevMidY;
eng.camX -= dMidX / effZoom;
eng.camY -= dMidY / effZoom;
eng.targetX = eng.camX;
eng.targetY = eng.camY;
if (eng.pinchPrevDist > 0) {
eng.anchorX = midX - eng.viewW / 2;
eng.anchorY = midY - eng.viewH / 2;
const nextZ = Math.min(3.0, Math.max(0.22, eng.zoom * (dist / eng.pinchPrevDist)));
eng.zoom = nextZ;
eng.targetZoom = nextZ;
}
eng.pinchPrevDist = dist;
eng.pinchPrevMidX = midX;
eng.pinchPrevMidY = midY;
return;
}
const dx = pt.x - prevPt.x;
const dy = pt.y - prevPt.y;
const now = performance.now();
const dt = Math.max(1, now - eng.lastMoveAt);
eng.lastMoveAt = now;
eng.movedPx += Math.hypot(dx, dy);
// EMA velocity (0.4 old + 0.6 instant)
eng.velX = 0.4 * eng.velX + 0.6 * (dx / dt);
eng.velY = 0.4 * eng.velY + 0.6 * (dy / dt);
if (eng.draggingOpen && eng.isOpen) {
if (eng.movedPx >= 8) {
eng.glideX -= dx / eng.openDragStepX;
eng.glideY -= dy / eng.openDragStepY;
}
return;
}
if (eng.isDragging && !eng.isOpen) {
const effZoom = eng.zoom * getStageScale(eng.viewW);
eng.camX -= dx / effZoom;
eng.camY -= dy / effZoom;
eng.targetX = eng.camX;
eng.targetY = eng.camY;
}
};
const handlePointerUpOrCancel = (e: React.PointerEvent<HTMLDivElement>) => {
const eng = engineRef.current;
if (!eng.pointers.has(e.pointerId)) return;
const pt = clientToStage(e.clientX, e.clientY);
eng.pointers.delete(e.pointerId);
if (eng.pointers.size > 0) return;
const idleMs = performance.now() - eng.lastMoveAt;
const wasClick = eng.movedPx < 8 && e.type !== "pointercancel";
if (eng.draggingOpen) {
eng.draggingOpen = false;
if (wasClick) {
const hit = hitTestTile(pt.x, pt.y);
if (hit && !hit.isCenterOpen) {
// Clicking an adjacent peeking thumbnail glides directly to that neighbor!
eng.targetGlideX = hit.col;
eng.targetGlideY = hit.row;
} else {
// Clicking the opened photo or empty whitespace closes back to wall
closeOpenTile();
}
return;
}
// Snap continuous fractional glide with velocity projection
const projVx = idleMs > 80 ? 0 : (-eng.velX * 1000) / eng.openDragStepX;
const projVy = idleMs > 80 ? 0 : (-eng.velY * 1000) / eng.openDragStepY;
const snapCol = Math.round(eng.glideX + 0.08 * projVx);
const snapRow = Math.round(eng.glideY + 0.08 * projVy);
eng.targetGlideX = snapCol;
eng.targetGlideY = snapRow;
return;
}
if (eng.isDragging) {
eng.isDragging = false;
if (wasClick) {
const hit = hitTestTile(pt.x, pt.y);
if (hit) {
openTileAt(hit.col, hit.row);
} else {
updateCursor("grab");
}
return;
}
updateCursor("grab");
if (idleMs > 80) {
eng.velX = 0;
eng.velY = 0;
eng.inertiaActive = false;
} else {
eng.inertiaActive = true;
}
}
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
const eng = engineRef.current;
const stageScale = getStageScale(eng.viewW);
const effZoom = eng.zoom * stageScale;
if (e.key === "Escape" && eng.isOpen) {
e.preventDefault();
closeOpenTile();
return;
}
if (e.key === "Enter" && !eng.isOpen) {
e.preventDefault();
// Open the photo closest to viewport center
const centerCol = Math.round(eng.camX / CELL_SIZE - 0.5);
const centerRow = Math.round(eng.camY / CELL_SIZE - 0.5);
openTileAt(centerCol, centerRow);
return;
}
if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
const dirX = e.key === "ArrowLeft" ? -1 : e.key === "ArrowRight" ? 1 : 0;
const dirY = e.key === "ArrowUp" ? -1 : e.key === "ArrowDown" ? 1 : 0;
if (eng.isOpen) {
stepOpenNeighbor(dirX, dirY);
} else {
eng.inertiaActive = false;
eng.targetX += (200 * stageScale * dirX) / effZoom;
eng.targetY += (200 * stageScale * dirY) / effZoom;
}
return;
}
if ((e.key === "+" || e.key === "=" || e.key === "-" || e.key === "_") && !eng.isOpen) {
e.preventDefault();
eng.inertiaActive = false;
eng.anchorX = 0;
eng.anchorY = 0;
const factor = e.key === "-" || e.key === "_" ? 0.8 : 1.25;
eng.targetZoom = Math.min(3.0, Math.max(0.22, eng.targetZoom * factor));
}
};
const activePhoto = PHOTOS[captionState.photoIndex] ?? PHOTOS[14];
return (
<div
lang={isZh ? "zh-CN" : "en"}
data-paper="/photography"
style={
{
"--space-bg": surfaceColors.bg,
"--space-ink": surfaceColors.ink,
backgroundColor: surfaceColors.bg,
color: surfaceColors.ink,
} as React.CSSProperties
}
className={`spw-${uid} relative h-full w-full overflow-hidden select-none`}
>
<style>{`
.spw-${uid} {
--font-sans: "Inter", -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;
font-family: var(--font-sans);
}
.spw-${uid} .spw-host[data-cursor="grab"] {
cursor: grab;
}
.spw-${uid} .spw-host[data-cursor="grabbing"] {
cursor: grabbing;
}
.spw-${uid} .spw-host[data-cursor="pointer"] {
cursor: pointer;
}
.spw-${uid} .spw-caption {
opacity: 0;
pointer-events: none;
transition: opacity 300ms ease 0ms;
}
.spw-${uid} .spw-caption[data-open="true"] {
opacity: 1;
transition: opacity 300ms ease 450ms;
}
.spw-${uid} .spw-out-link {
pointer-events: auto;
display: inline-flex;
align-items: baseline;
gap: 2px;
color: var(--space-ink);
text-decoration: none;
}
.spw-${uid} .spw-out-link-label {
display: inline-flex;
align-items: center;
border-bottom: 1px dotted color-mix(in srgb, currentColor 40%, transparent);
transition: border-color 180ms ease;
}
.spw-${uid} .spw-out-link:hover .spw-out-link-label,
.spw-${uid} .spw-out-link:focus-visible .spw-out-link-label {
border-bottom-style: solid;
border-bottom-color: currentColor;
}
.spw-${uid} .spw-out-arrow {
opacity: 0.5;
transition: opacity 180ms ease, transform 180ms ease;
}
.spw-${uid} .spw-out-link:hover .spw-out-arrow,
.spw-${uid} .spw-out-link:focus-visible .spw-out-arrow {
opacity: 1;
transform: translate(1px, -1px);
}
@media (prefers-reduced-motion: reduce) {
.spw-${uid} .spw-caption,
.spw-${uid} .spw-caption[data-open="true"] {
transition-duration: 0.01ms !important;
transition-delay: 0ms !important;
}
}
`}</style>
<main className="relative h-full w-full">
{/* Interactive Spatial Host (.space-host) */}
<div
ref={hostRef}
role="application"
tabIndex={0}
data-cursor={cursorMode}
aria-label={
isZh
? "照片墙。拖动、滚动或用方向键移动,双指捏合、按住 ⌘ 或 Ctrl 滚动,或按 + 和 − 缩放;点击照片,或按 Enter 打开中间那张,按 Esc 放回去。"
: "Photo wall. Drag, scroll, or use arrow keys to pan; pinch, hold Cmd/Ctrl + scroll, or press + and − to zoom; click a photo or press Enter to open, press Esc to put it back."
}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUpOrCancel}
onPointerCancel={handlePointerUpOrCancel}
onKeyDown={handleKeyDown}
style={{ touchAction: "none" }}
className="spw-host relative h-full w-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-black/25"
>
<canvas
ref={canvasRef}
className="block h-full w-full"
/>
</div>
{/* Positioned Caption & Unsplash Attribution (.photo-caption) */}
{captionState.open && (
<p
aria-live="polite"
data-open={captionState.settled ? "true" : "false"}
style={{
width: `${captionState.width}px`,
transform: `translate3d(${captionState.x}px, ${captionState.y}px, 0px)`,
}}
className="spw-caption absolute top-0 left-0 z-20 m-0 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 text-[12px] leading-[1.3] sm:text-[13px]"
>
<span
style={{
color: "color-mix(in srgb, var(--space-ink) 66%, transparent)",
}}
className="tabular-nums"
>
{formatTakenDate(activePhoto.taken, isZh)}
</span>
<a
href={activePhoto.unsplashUrl}
target="_blank"
rel="noreferrer"
onClick={(e) => e.stopPropagation()}
className="spw-out-link"
>
<span className="spw-out-link-label">
<svg
viewBox="0 0 24 24"
fill="currentColor"
aria-hidden="true"
className="mr-1 h-[0.75em] w-[0.75em] shrink-0"
>
<path d="M7.5 6.75V0h9v6.75h-9zm9 3.75H24V24H0V10.5h7.5v6.75h9V10.5z" />
</svg>
<span>Unsplash</span>
</span>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
className="spw-out-arrow ml-0.5 h-[0.85em] w-[0.85em] shrink-0 self-center"
>
<path d="M7 7h10v10" />
<path d="M7 17 17 7" />
</svg>
</a>
</p>
)}
</main>
{/* Subtle Paper Grain Overlay (.space::before feTurbulence) */}
{paperGrain && (
<div
aria-hidden="true"
style={{
backgroundImage: `url("${PAPER_GRAIN_SVG}")`,
backgroundSize: "180px 180px",
mixBlendMode: "overlay",
opacity: surfaceColors.isDark ? 0.12 : 0.22,
}}
className="pointer-events-none absolute inset-0 z-10"
/>
)}
</div>
);
}
export default function PhotographyWallPage() {
return <SpatialPhotoWall params={wallParams} />;
}
参数参考
| 属性 | 默认值 | 当前值 | 说明 |
|---|---|---|---|
copyLang 图注日期语言 | zh | zh | 切换展开大图下方拍摄年月的本地化格式(如 2025年1月 / January 2025)。 |
tileFillRatio 单格照片占比 | 0.67 | 0.67 | 照片最长边占 300×300 均匀方格的比例(原站为 200/300 ≈ 0.67,控制四周留白呼吸感)。 |
defaultZoom 画布缩放倍率 | 0.7 | 0.7 | 空间相机缩放倍率(原站默认 0.70,桌面视口恰好露出 6×5 张缩略图)。 |
pushClearancePx 展开推开间距 | 48 | 48 | 点开大图时将左右/上下相邻行列向外推开的最小呼吸安全间距(原站水平 48px / 垂直 72px)。 |
panTauMs 漫游阻尼时间常数 | 70 | 70 | 滚轮漫游与对数缩放的指数平滑时间常数 τ(原站为 70ms,越小越紧致跟手,越大越丝滑绵长)。 |
openDuration 展开弹簧时长 | 0.28 | 0.28 | 点开或收起照片并同步推开四周邻居行列的弹簧视觉时长(原站为 0.28s)。 |
openBounce 展开回弹系数 | 0.08 | 0.08 | 照片放大推开邻居时的微回弹系数(原站为克制的 0.08)。 |
paperTheme 画布纸张底色 | paper | paper | 在原站纯白纸底(#FFFFFF)、暖调银盐相纸(#F6F4EF)与暗房黑底(#0D0D0F)间切换。 |
paperGrain 纸张噪点肌理 | true | true | 叠加原站 180×180 SVG feTurbulence 微噪点纸感肌理层(mix-blend-mode: overlay,0.22 透明度)。 |