悬浮预览项目列表
五层嵌套 Portal 悬浮预览架构:移入与移出时沿正弦抛物弧线(±72px 横向偏转)从光标处以微弹弹簧(0.4s / bounce 0.24)甩出与收拢;移动时按光标移速自适应刚度(50→8)并以光标为支点做物理摆锤摆动;跨行切项采用 0.2s 零回弹弹簧在同栈内完成 0.5↔1.0 缩放交叠。
目录与索引8 项可调参数React + Tailwind
演示与调参
1:1 拆解还原的四个底层机制:① 五层职责解耦(anchor 负责双轴自适应追踪、layer 负责进出正弦弧线轨迹 sin(p·π)·(-72px)、swing 将 transform-origin 钉在实时鼠标坐标做二阶弹簧摆锤、stack 负责整体 0.1↔1 进出缩放、item 叠在同一 grid 单元各自带固定错落倾角);② 自适应移速跟随:慢移时刚度高达 50(零粘滞跟手),快速扫动时平滑降到 8 拉出柔和惯性并驱动 ±14° 钟摆旋转;③ 首次展开第一帧禁用子项动画(0ms 直出),展开后跨行切换改用 0.2s 无回弹弹簧做 scale(0.5↔1) + opacity 过渡;④ 预览内容采用预编码单层位图与 GPU drop-shadow,零 DOM 子树重排,满帧流畅。
Projects
FieldnotesA working library for those committed to designing with quiet care.FormaYour friendly neighborhood variable grotesk.Solstice LampA limited drop of one-of-one ceramic lamps, each sculpted by hand.DialpadA floating control panel for real-time parameter tweaking.Cobalt TypePreview every locally available font family directly in the browser.CadenceA tiny, fully-themeable, and dependency-free fluid stepper component.Night RadioA retro background ambiance synthesizer for late-night focus.
参数调节
布局结构
目录文案语言
预览框最大宽度300px
进出弧线偏移72px
动效反馈
进出弹簧时长0.40s
进出回弹弹性0.24
切项过渡时长0.20s
钟摆惯性幅度1.0
表面与质感
图片圆角半径8px
参考原站joshpuckett.me ↗
floating-preview-list复刻提示词
请用 React 实现极简编辑风「悬浮预览项目列表(Floating Preview List)」组件,严格采用 **5 层解耦 Fixed Portal 架构**,实现 120fps 零卡顿跟手追踪、正弦抛物弧线进出、鼠标支点钟摆旋转与无回弹跨行切图。
精确的五层 Portal DOM 结构(`createPortal(..., document.body)`,`position: fixed; top: 0; left: 0; pointer-events: none`):
1. `.anchor`(尺寸 300px × 200px):负责 `translate3d(x, y, 0)` 位移。当 `rowRect.top >= boxH + 38` 时置于上方(`clientY - rowHeight/2 - boxH - 14`),否则置于下方,距视口边缘留 24px 安全边距。
- **移速自适应刚度**:平滑统计目标移速 `pace`,按 `alpha = 1 - Math.exp(-(50 - 42 * Math.min(1, pace / 2000)) * dt)` 插值——慢速微移时刚度高达 50(极度跟手无拖泥带水),快速横扫时降至 8 拉出丝滑惯性。
2. `.layer`(`position: absolute; top: 50%; left: 50%`):负责进出正弦抛物弧线,使用弹簧(`visualDuration: 0.4s, bounce: 0.24`)。按鼠标位于行左/右半区取 `side = ±1`,收起态为光标相对中心偏移 `{ x: cursorRelX, y: cursorRelY, rotation: -8 * side }`,展开态为 `{ 0, 0, 0 }`;在进度 `p` 上叠加横向 `Math.sin(p * Math.PI) * (-72 * side)` 与纵向 `-Math.sin(p * Math.PI) * arcY` 弧线。
3. `.swing`(`translate: -50% -50%`):每帧将 `transformOrigin` 设为鼠标相对卡片左上角的精确像素坐标,用二阶扭转弹簧 `spin += (320 * (targetAngle - angle) - 16 * spin) * dt`(目标角 `clamp(-14, 14, hang * vx * 0.012 * 1)`)实现捏住照片般的钟摆惯性。
4. `.stack`(`display: grid; place-items: end center`):同步用 `visualDuration: 0.4s, bounce: 0.24` 弹簧驱动整体 `scale(0.1 ↔ 1)` 与 `opacity(0 ↔ 1)`。
5. `.item`(全部叠在 `grid-area: 1 / 1`,每项带固定静倾角 `[-5, 3.5, -2.5, 5.5, -6, 4, -3]deg`):首次展开首帧 0ms 直出当前项;展开状态下跨行切换时,用 `visualDuration: 0.2s, bounce: 0` 无回弹弹簧将旧项收至 `opacity: 0, scale: 0.5`、新项升至 `opacity: 1, scale: 1`。内部仅放单张圆角 8px 的 `<img>` 配 `drop-shadow`,避免复杂 DOM 子树导致掉帧。代码
FloatingPreviewList.tsxReact · Tailwind
"use client";
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
const listParams = {
"copyLang": "en",
"cardWidthPx": 300,
"enterDuration": 0.4,
"enterBounce": 0.24,
"swapDuration": 0.2,
"arcOffsetPx": 72,
"swingGain": 1,
"cardRadiusPx": 8
};
export interface FloatingPreviewListParams {
copyLang?: string;
cardWidthPx?: number;
enterDuration?: number;
enterBounce?: number;
swapDuration?: number;
arcOffsetPx?: number;
swingGain?: number;
cardRadiusPx?: number;
}
interface ProjectEntry {
key: string;
titleEn: string;
descEn: string;
titleZh: string;
descZh: string;
tilt: number;
image: {
src: string;
width: number;
height: number;
};
}
function svgDataUri(svg: string): string {
return `data:image/svg+xml;utf8,${encodeURIComponent(svg.trim())}`;
}
// Pre-encoded vector bitmap data-URIs (varied aspect ratios matching 300x200 max-fit box, zero DOM subtree cost)
const PROJECTS: ProjectEntry[] = [
{
key: "fieldnotes",
titleEn: "Fieldnotes",
descEn: "A working library for those committed to designing with quiet care.",
titleZh: "界面手记",
descZh: "记录交互手感、微动效与组件细节的设计工作库。",
tilt: -5,
image: {
width: 540,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="540" height="400" viewBox="0 0 540 400">
<rect width="540" height="400" fill="#F8F8F6"/>
<circle cx="36" cy="34" r="7" fill="#171717"/>
<rect x="444" y="28" width="64" height="12" rx="6" fill="#E4E4E7"/>
<rect x="24" y="64" width="492" height="176" rx="14" fill="#FFFFFF" stroke="#E4E4E7" stroke-width="1.5"/>
<text x="48" y="98" font-family="ui-monospace, monospace" font-size="16" fill="#71717A">01 · SPRING CURVE</text>
<path d="M 48 206 C 148 206, 178 108, 488 108" fill="none" stroke="#171717" stroke-width="4.5" stroke-linecap="round"/>
<circle cx="184" cy="126" r="7" fill="#2563EB"/>
<circle cx="488" cy="108" r="6" fill="#171717"/>
<rect x="24" y="256" width="238" height="120" rx="14" fill="#FFFFFF" stroke="#E4E4E7" stroke-width="1.5"/>
<rect x="44" y="276" width="32" height="32" rx="8" fill="#2563EB"/>
<rect x="44" y="344" width="148" height="10" rx="5" fill="#E4E4E7"/>
<rect x="278" y="256" width="238" height="120" rx="14" fill="#FFFFFF" stroke="#E4E4E7" stroke-width="1.5"/>
<circle cx="314" cy="292" r="15" fill="none" stroke="#171717" stroke-width="4"/>
<rect x="298" y="344" width="112" height="10" rx="5" fill="#E4E4E7"/>
</svg>
`),
},
},
{
key: "forma-sans",
titleEn: "Forma",
descEn: "Your friendly neighborhood variable grotesk.",
titleZh: "几何字型",
descZh: "一套温和友好的可变无衬线字体实验。",
tilt: 3.5,
image: {
width: 600,
height: 315,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="600" height="315" viewBox="0 0 600 315">
<rect width="600" height="315" fill="#FFFDF7"/>
<rect x="20" y="20" width="560" height="275" rx="12" fill="none" stroke="#E7E2D5" stroke-width="2"/>
<text x="48" y="198" font-family="system-ui, -apple-system, sans-serif" font-size="148" font-weight="700" letter-spacing="-6" fill="#171717">Ag</text>
<text x="274" y="132" font-family="system-ui, -apple-system, sans-serif" font-size="28" font-weight="500" fill="#171717">Forma Variable</text>
<text x="274" y="172" font-family="ui-monospace, monospace" font-size="18" fill="#78716C">wght 100 — 900 · opsz 14</text>
<rect x="274" y="204" width="256" height="8" rx="4" fill="#E7E2D5"/>
<rect x="274" y="204" width="168" height="8" rx="4" fill="#EA580C"/>
<circle cx="442" cy="208" r="10" fill="#171717"/>
</svg>
`),
},
},
{
key: "solstice-lamp",
titleEn: "Solstice Lamp",
descEn: "A limited drop of one-of-one ceramic lamps, each sculpted by hand.",
titleZh: "冬至台灯",
descZh: "手工塑形的限量陶瓷桌面灯具,每盏轮廓独一无二。",
tilt: -2.5,
image: {
width: 513,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="513" height="400" viewBox="0 0 513 400">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#E7AC74"/>
<stop offset="100%" stop-color="#C47641"/>
</linearGradient>
<radialGradient id="glow" cx="50%" cy="44%" r="46%">
<stop offset="0%" stop-color="#FFF9E6" stop-opacity="0.96"/>
<stop offset="55%" stop-color="#F6BE82" stop-opacity="0.45"/>
<stop offset="100%" stop-color="#C47641" stop-opacity="0"/>
</radialGradient>
</defs>
<rect width="513" height="400" fill="url(#bg)"/>
<circle cx="256" cy="182" r="170" fill="url(#glow)"/>
<ellipse cx="256" cy="316" rx="76" ry="12" fill="#46200C" opacity="0.22"/>
<path d="M 176 250 C 176 146, 216 102, 256 102 C 296 102, 336 146, 336 250 Z" fill="#FFF4DE"/>
<rect x="204" y="250" width="104" height="58" rx="22" fill="#B26535"/>
<text x="32" y="368" font-family="ui-monospace, monospace" font-size="16" fill="#FFF8EB" opacity="0.85">EDITION 04 / 24</text>
</svg>
`),
},
},
{
key: "dialpad",
titleEn: "Dialpad",
descEn: "A floating control panel for real-time parameter tweaking.",
titleZh: "阻尼旋钮",
descZh: "面向动效原型与弹簧参数实时微调的触感控制面板。",
tilt: 5.5,
image: {
width: 396,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="396" height="400" viewBox="0 0 396 400">
<rect width="396" height="400" fill="#151519"/>
<rect x="24" y="24" width="348" height="352" rx="20" fill="#1E1E24" stroke="#2E2E38" stroke-width="2"/>
<text x="48" y="64" font-family="ui-monospace, monospace" font-size="15" fill="#A1A1AA">SPRING TUNER</text>
<circle cx="336" cy="58" r="6" fill="#22C55E"/>
<circle cx="132" cy="176" r="56" fill="#121216" stroke="#32323D" stroke-width="3"/>
<line x1="132" y1="176" x2="100" y2="136" stroke="#F59E0B" stroke-width="6" stroke-linecap="round"/>
<text x="92" y="260" font-family="ui-monospace, monospace" font-size="14" fill="#D4D4D8">DAMP 0.76</text>
<circle cx="268" cy="176" r="56" fill="#121216" stroke="#32323D" stroke-width="3"/>
<line x1="268" y1="176" x2="298" y2="134" stroke="#38BDF8" stroke-width="6" stroke-linecap="round"/>
<text x="228" y="260" font-family="ui-monospace, monospace" font-size="14" fill="#D4D4D8">STIFF 171</text>
<rect x="48" y="308" width="300" height="12" rx="6" fill="#111114"/>
<rect x="48" y="308" width="196" height="12" rx="6" fill="#38BDF8"/>
</svg>
`),
},
},
{
key: "cobalt-type",
titleEn: "Cobalt Type",
descEn: "Preview every locally available font family directly in the browser.",
titleZh: "钴蓝字库",
descZh: "在浏览器中即时浏览并对比本地可用的全部字体家族。",
tilt: -6,
image: {
width: 522,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="522" height="400" viewBox="0 0 522 400">
<defs>
<linearGradient id="cb" x1="0" y1="0" x2="0.8" y2="1">
<stop offset="0%" stop-color="#1E3BFF"/>
<stop offset="100%" stop-color="#0D22D4"/>
</linearGradient>
</defs>
<rect width="522" height="400" fill="url(#cb)"/>
<rect x="20" y="16" width="482" height="24" rx="12" fill="#FFFFFF" fill-opacity="0.14"/>
<circle cx="36" cy="28" r="4" fill="#FFFFFF" fill-opacity="0.8"/>
<g fill="#FFFFFF" font-size="22" text-anchor="middle">
<rect x="20" y="54" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="76" y="108" font-family="Georgia, serif">Cobalt</text>
<rect x="143" y="54" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="199" y="108" font-family="system-ui, sans-serif" font-weight="700">Cobalt</text>
<rect x="266" y="54" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="322" y="108" font-family="Georgia, serif" font-style="italic">Cobalt</text>
<rect x="389" y="54" width="113" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="445" y="108" font-family="ui-monospace, monospace" font-size="19">Cobalt</text>
<rect x="20" y="156" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="76" y="210" font-family="system-ui, sans-serif" font-weight="300">Cobalt</text>
<rect x="143" y="156" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="199" y="210" font-family="Georgia, serif" font-weight="700">Cobalt</text>
<rect x="266" y="156" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="322" y="210" font-family="system-ui, sans-serif" font-style="italic">Cobalt</text>
<rect x="389" y="156" width="113" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="445" y="210" font-family="Georgia, serif">Cobalt</text>
<rect x="20" y="258" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="76" y="312" font-family="ui-monospace, monospace" font-weight="700" font-size="19">Cobalt</text>
<rect x="143" y="258" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="199" y="312" font-family="system-ui, sans-serif" font-weight="600">Cobalt</text>
<rect x="266" y="258" width="112" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="322" y="312" font-family="Georgia, serif" font-style="italic">Cobalt</text>
<rect x="389" y="258" width="113" height="92" rx="8" fill="#FFFFFF" fill-opacity="0.07" stroke="#FFFFFF" stroke-opacity="0.14"/>
<text x="445" y="312" font-family="system-ui, sans-serif">Cobalt</text>
</g>
<rect x="196" y="362" width="130" height="22" rx="11" fill="#FFFFFF" fill-opacity="0.24"/>
</svg>
`),
},
},
{
key: "cadence",
titleEn: "Cadence",
descEn: "A tiny, fully-themeable, and dependency-free fluid stepper component.",
titleZh: "韵律步进",
descZh: "轻量无依赖、支持主题定制的流畅弹性步进组件。",
tilt: 4,
image: {
width: 533,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="533" height="400" viewBox="0 0 533 400">
<rect width="533" height="400" fill="#EFF1F5"/>
<rect x="56" y="76" width="421" height="248" rx="24" fill="#FFFFFF" stroke="#E2E5EC" stroke-width="2"/>
<text x="96" y="134" font-family="system-ui, sans-serif" font-size="24" font-weight="600" fill="#171717">Checkout Flow</text>
<rect x="368" y="112" width="68" height="28" rx="14" fill="#F4F4F5"/>
<text x="402" y="131" text-anchor="middle" font-family="ui-monospace, monospace" font-size="13" fill="#52525B">02/04</text>
<rect x="96" y="168" width="340" height="12" rx="6" fill="#F4F4F5"/>
<rect x="96" y="196" width="236" height="12" rx="6" fill="#F4F4F5"/>
<circle cx="106" cy="268" r="7" fill="#71717A"/>
<rect x="126" y="261" width="56" height="14" rx="7" fill="#171717"/>
<circle cx="198" cy="268" r="7" fill="#D4D4D8"/>
<circle cx="224" cy="268" r="7" fill="#D4D4D8"/>
</svg>
`),
},
},
{
key: "night-radio",
titleEn: "Night Radio",
descEn: "A retro background ambiance synthesizer for late-night focus.",
titleZh: "深夜电台",
descZh: "为深夜专注打造的复古背景环境音合成器。",
tilt: -3,
image: {
width: 505,
height: 400,
src: svgDataUri(`
<svg xmlns="http://www.w3.org/2000/svg" width="505" height="400" viewBox="0 0 505 400">
<rect width="505" height="400" fill="#0E1714"/>
<circle cx="44" cy="46" r="7" fill="#34D399"/>
<text x="64" y="52" font-family="ui-monospace, monospace" font-size="16" fill="#A7F3D0" letter-spacing="2">98.4 MHZ · RAIN</text>
<g fill="#34D399">
<rect x="40" y="210" width="26" height="110" rx="5" opacity="0.55"/>
<rect x="78" y="156" width="26" height="164" rx="5" opacity="0.75"/>
<rect x="116" y="184" width="26" height="136" rx="5" opacity="0.65"/>
<rect x="154" y="112" width="26" height="208" rx="5" opacity="0.95"/>
<rect x="192" y="142" width="26" height="178" rx="5" opacity="0.8"/>
<rect x="230" y="94" width="26" height="226" rx="5"/>
<rect x="268" y="168" width="26" height="152" rx="5" opacity="0.75"/>
<rect x="306" y="128" width="26" height="192" rx="5" opacity="0.88"/>
<rect x="344" y="196" width="26" height="124" rx="5" opacity="0.6"/>
<rect x="382" y="152" width="26" height="168" rx="5" opacity="0.78"/>
<rect x="420" y="188" width="26" height="132" rx="5" opacity="0.55"/>
</g>
<rect x="40" y="352" width="406" height="4" rx="2" fill="#A7F3D0" opacity="0.22"/>
</svg>
`),
},
},
];
const SCOPED_CSS = `
.fpl-stage {
position: relative;
box-sizing: border-box;
width: 100%;
max-width: 640px;
margin: 0 auto;
border-radius: 16px;
background: #ffffff;
color: #171717;
padding: 32px 32px 24px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06);
font-family: "Inter", -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif;
}
.fpl-header {
margin: 0;
font-size: 22px;
line-height: 1.3;
font-weight: 600;
letter-spacing: -0.025em;
color: #171717;
}
.fpl-divider {
width: 48px;
height: 1px;
margin: 20px 0 16px;
border-radius: 1px;
background: #d4d4d4;
}
.fpl-list {
margin: 0 -16px;
}
.fpl-row {
position: relative;
display: block;
width: 100%;
border: 0;
border-radius: 12px;
padding: 12px 16px;
background: transparent;
text-align: left;
cursor: pointer;
text-decoration: none;
line-height: 1.625;
transition: background-color 150ms ease;
}
.fpl-row:hover {
background: #f5f5f5;
}
.fpl-row:focus-visible {
outline: 2px solid #171717;
outline-offset: -2px;
background: #f5f5f5;
}
.fpl-row-title {
display: block;
font-size: 15px;
font-weight: 500;
color: #171717;
}
.fpl-row-desc {
display: block;
font-size: 14px;
font-weight: 400;
color: #525252;
}
/* 5-layer portal architecture: anchor -> layer -> swing -> stack -> item -> picture */
.fpl-anchor {
z-index: 60;
pointer-events: none;
position: fixed;
top: 0;
left: 0;
will-change: transform;
}
.fpl-layer {
position: absolute;
top: 50%;
left: 50%;
will-change: transform;
}
.fpl-swing {
translate: -50% -50%;
will-change: rotate;
}
.fpl-stack {
display: grid;
place-items: end center;
will-change: transform, opacity;
}
.fpl-anchor[data-side="below"] .fpl-stack {
place-items: start center;
}
.fpl-item {
grid-area: 1 / 1;
will-change: transform, opacity;
}
.fpl-picture {
display: block;
max-width: none;
user-select: none;
-webkit-user-select: none;
filter: drop-shadow(0 12px 28px rgba(0, 0, 0, 0.16)) drop-shadow(0 2px 6px rgba(0, 0, 0, 0.1));
}
/* Static decorative preview shown only inside non-interactive gallery thumbnails */
.fpl-thumb-card {
pointer-events: none;
position: absolute;
top: 96px;
left: 44px;
z-index: 10;
transform: rotate(-6deg);
}
`;
const REST_POSE = { x: 0, y: 0, rotation: 0 };
// Exact Motion visualDuration + bounce -> (stiffness, damping) resolver
function resolveSpringParams(visualDuration: number, bounce: number) {
const omega = (2 * Math.PI) / (1.2 * Math.max(0.05, visualDuration));
const stiffness = omega * omega;
const zeta = Math.min(1, Math.max(0.05, 1 - bounce));
const damping = 2 * zeta * omega;
return { stiffness, damping };
}
interface Spring1D {
pos: number;
vel: number;
target: number;
}
function stepSpring1D(s: Spring1D, stiffness: number, damping: number, dt: number): boolean {
// Sub-step to <= 4ms for unconditional stability even at high stiffness (685)
const steps = Math.max(1, Math.ceil(dt / 0.004));
const h = dt / steps;
for (let i = 0; i < steps; i++) {
const force = stiffness * (s.target - s.pos) - damping * s.vel;
s.vel += force * h;
s.pos += s.vel * h;
}
if (Math.abs(s.target - s.pos) < 0.0008 && Math.abs(s.vel) < 0.005) {
s.pos = s.target;
s.vel = 0;
return true;
}
return false;
}
function FloatingPreviewList({
params,
}: {
params: Record<string, string | number | boolean>;
}) {
const copyLang = String(params.copyLang ?? "en") === "zh" ? "zh" : "en";
const boxW = Number(params.cardWidthPx ?? 300);
const boxH = Math.round((boxW * 2) / 3);
const enterDuration = Number(params.enterDuration ?? 0.4);
const enterBounce = Number(params.enterBounce ?? 0.24);
const swapDuration = Number(params.swapDuration ?? 0.2);
const arcOffsetPx = Number(params.arcOffsetPx ?? 72);
const swingGain = Number(params.swingGain ?? 1);
const cardRadiusPx = Number(params.cardRadiusPx ?? 8);
const stageRef = useRef<HTMLDivElement | null>(null);
const anchorRef = useRef<HTMLDivElement | null>(null);
const layerRef = useRef<HTMLDivElement | null>(null);
const swingRef = useRef<HTMLDivElement | null>(null);
const stackRef = useRef<HTMLDivElement | null>(null);
const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
const [mounted, setMounted] = useState(false);
const [isThumbnail, setIsThumbnail] = useState(false);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const [hasOpened, setHasOpened] = useState(false);
const [reducedMotion, setReducedMotion] = useState(false);
const cursorRelRef = useRef({ x: 0, y: 0 });
const followRef = useRef({
to: { x: 0, y: 0 },
from: { x: 0, y: 0 },
pace: 0,
x: 0,
y: 0,
angle: 0,
spin: 0,
hang: -1,
});
const followRafRef = useRef(0);
const arcPoseRef = useRef<{ x: number; y: number; rotation: number } | null>(null);
const sideSignRef = useRef<1 | -1>(1);
// Continuous spring states for stack (scale, opacity) and items (opacity, scale)
const stackScaleRef = useRef<Spring1D>({ pos: 0.1, vel: 0, target: 0.1 });
const stackOpacityRef = useRef<Spring1D>({ pos: 0, vel: 0, target: 0 });
const itemSpringsRef = useRef<{ opacity: Spring1D; scale: Spring1D }[]>(
PROJECTS.map((_, i) => ({
opacity: { pos: i === 0 ? 1 : 0, vel: 0, target: i === 0 ? 1 : 0 },
scale: { pos: i === 0 ? 1 : 0.5, vel: 0, target: i === 0 ? 1 : 0.5 },
}))
);
const springRafRef = useRef(0);
const cfgRef = useRef({
boxW,
boxH,
enterDuration,
enterBounce,
swapDuration,
arcOffsetPx,
swingGain,
reducedMotion,
});
useEffect(() => {
cfgRef.current = {
boxW,
boxH,
enterDuration,
enterBounce,
swapDuration,
arcOffsetPx,
swingGain,
reducedMotion,
};
}, [boxW, boxH, enterDuration, enterBounce, swapDuration, arcOffsetPx, swingGain, reducedMotion]);
useEffect(() => {
setMounted(true);
if (stageRef.current?.closest('[aria-hidden="true"]')) {
setIsThumbnail(true);
}
const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
const sync = () => setReducedMotion(mq.matches);
sync();
mq.addEventListener("change", sync);
return () => mq.removeEventListener("change", sync);
}, []);
const closePreview = () => {
setOpen(false);
setHasOpened(false);
};
const applyAnchorTransform = () => {
const f = followRef.current;
if (anchorRef.current) {
anchorRef.current.style.transform = `translate3d(${f.x}px, ${f.y}px, 0)`;
}
if (swingRef.current) {
swingRef.current.style.rotate = `${f.angle}deg`;
}
};
const startSpringsLoop = () => {
if (springRafRef.current) return;
let prev = performance.now();
const tick = (now: number) => {
const dt = Math.min(1 / 30, Math.max(0.001, (now - prev) / 1000));
prev = now;
const cfg = cfgRef.current;
const enterSp = resolveSpringParams(cfg.enterDuration, cfg.enterBounce);
const swapSp = resolveSpringParams(cfg.swapDuration, 0);
let allDone = true;
if (cfg.reducedMotion) {
stackScaleRef.current.pos = stackScaleRef.current.target;
stackOpacityRef.current.pos = stackOpacityRef.current.target;
} else {
const d1 = stepSpring1D(stackScaleRef.current, enterSp.stiffness, enterSp.damping, dt);
const d2 = stepSpring1D(stackOpacityRef.current, enterSp.stiffness, enterSp.damping, dt);
if (!d1 || !d2) allDone = false;
}
if (stackRef.current) {
const sc = Math.max(0.02, stackScaleRef.current.pos);
const op = Math.max(0, Math.min(1, stackOpacityRef.current.pos));
stackRef.current.style.transform = `scale(${sc.toFixed(4)})`;
stackRef.current.style.opacity = op.toFixed(4);
}
for (let i = 0; i < itemSpringsRef.current.length; i++) {
const sp = itemSpringsRef.current[i];
const el = itemRefs.current[i];
if (cfg.reducedMotion) {
sp.opacity.pos = sp.opacity.target;
sp.scale.pos = sp.scale.target;
} else {
const iDone1 = stepSpring1D(sp.opacity, swapSp.stiffness, swapSp.damping, dt);
const iDone2 = stepSpring1D(sp.scale, swapSp.stiffness, swapSp.damping, dt);
if (!iDone1 || !iDone2) allDone = false;
}
if (el) {
const op = Math.max(0, Math.min(1, sp.opacity.pos));
el.style.opacity = op.toFixed(4);
el.style.transform = `scale(${sp.scale.pos.toFixed(4)})`;
el.style.visibility = op < 0.002 && sp.opacity.target === 0 ? "hidden" : "visible";
}
}
springRafRef.current = allDone ? 0 : requestAnimationFrame(tick);
};
springRafRef.current = requestAnimationFrame(tick);
};
const trackPointer = (rowRect: DOMRect, clientX: number, clientY: number) => {
const anchorEl = anchorRef.current;
const swingEl = swingRef.current;
if (!anchorEl || !swingEl) return;
const { boxW: W, boxH: H, reducedMotion: rm } = cfgRef.current;
const above = rowRect.top >= H + 38;
const s = Math.max(24, Math.min(window.innerWidth - W - 24, clientX - W / 2));
const o = Math.max(
24,
Math.min(
window.innerHeight - H - 24,
above ? clientY - rowRect.height / 2 - H - 14 : clientY + rowRect.height / 2 + 14
)
);
anchorEl.dataset.side = above ? "above" : "below";
swingEl.style.transformOrigin = `${clientX - s}px ${clientY - o}px`;
cursorRelRef.current = { x: clientX - s - W / 2, y: clientY - o - H / 2 };
const state = followRef.current;
state.to = { x: s, y: o };
state.hang = above ? -1 : 1;
if (!arcPoseRef.current || rm) {
cancelAnimationFrame(followRafRef.current);
followRafRef.current = 0;
Object.assign(state, {
x: s,
y: o,
from: { ...state.to },
pace: 0,
angle: 0,
spin: 0,
});
applyAnchorTransform();
}
if (!rm && !followRafRef.current) {
let prevTime = performance.now();
const step = (now: number) => {
const f = followRef.current;
const dt = Math.min(1 / 30, Math.max(0.001, (now - prevTime) / 1000));
prevTime = now;
const speed = dt > 0 ? Math.hypot(f.to.x - f.from.x, f.to.y - f.from.y) / dt : 0;
f.from = { ...f.to };
f.pace += (speed - f.pace) * (1 - Math.exp(-12 * dt));
// Adaptive rate: 50 when moving slowly (zero lag), softening toward 8 during fast sweeps
const alpha = 1 - Math.exp(-(50 - 42 * Math.min(1, f.pace / 2000)) * dt);
const dx = (f.to.x - f.x) * alpha;
f.x += dx;
f.y += (f.to.y - f.y) * alpha;
const targetAngle = Math.max(
-14,
Math.min(14, f.hang * (dt > 0 ? dx / dt : 0) * 0.012 * cfgRef.current.swingGain)
);
f.spin += (320 * (targetAngle - f.angle) - 16 * f.spin) * dt;
f.angle += f.spin * dt;
const settled =
Math.abs(f.to.x - f.x) + Math.abs(f.to.y - f.y) < 0.1 &&
Math.abs(f.angle) + Math.abs(f.spin) < 0.01;
if (settled) {
Object.assign(f, { ...f.to, pace: 0, angle: 0, spin: 0 });
}
applyAnchorTransform();
followRafRef.current = settled ? 0 : requestAnimationFrame(step);
};
followRafRef.current = requestAnimationFrame(step);
}
};
const handlePointer = (e: React.PointerEvent<HTMLDivElement>) => {
if (e.pointerType === "touch") return;
const row = (e.target as HTMLElement).closest<HTMLElement>("[data-arc-index]");
if (!row) return;
const idx = Number(row.dataset.arcIndex);
const rect = row.getBoundingClientRect();
sideSignRef.current = e.clientX < rect.left + rect.width / 2 ? 1 : -1;
trackPointer(rect, e.clientX, e.clientY);
setActiveIndex((prev) => (prev === idx ? prev : idx));
setOpen((prev) => (prev ? prev : true));
};
// Parabolic arc swoop on layerRef + stack scale/opacity spring when `open` toggles
useLayoutEffect(() => {
const layerEl = layerRef.current;
if (!layerEl) return;
stackScaleRef.current.target = reducedMotion || open ? 1 : 0.1;
stackOpacityRef.current.target = open ? 1 : 0;
startSpringsLoop();
const applyLayer = (pose: { x: number; y: number; rotation: number }) => {
arcPoseRef.current = pose;
layerEl.style.transform = `translate3d(${pose.x.toFixed(2)}px, ${pose.y.toFixed(2)}px, 0) rotate(${pose.rotation.toFixed(2)}deg)`;
};
if (reducedMotion) {
applyLayer(REST_POSE);
return;
}
if (!open && !arcPoseRef.current) return;
const side = sideSignRef.current;
const closedPose = {
x: cursorRelRef.current.x,
y: cursorRelRef.current.y,
rotation: REST_POSE.rotation - 8 * side,
};
const fromPose = arcPoseRef.current ?? closedPose;
const toPose = open ? REST_POSE : closedPose;
const arcY = Math.min(32, Math.max(0, (anchorRef.current?.getBoundingClientRect().top ?? 0) - 12));
const arcX = -cfgRef.current.arcOffsetPx * side;
applyLayer(fromPose);
const sp = resolveSpringParams(cfgRef.current.enterDuration, cfgRef.current.enterBounce);
const prog: Spring1D = { pos: 0, vel: 0, target: 1 };
let rafId = 0;
let prev = performance.now();
const tickArc = (now: number) => {
const dt = Math.min(1 / 30, Math.max(0.001, (now - prev) / 1000));
prev = now;
const done = stepSpring1D(prog, sp.stiffness, sp.damping, dt);
const p = prog.pos;
applyLayer({
x: fromPose.x + (toPose.x - fromPose.x) * p + Math.sin(p * Math.PI) * arcX,
y: fromPose.y + (toPose.y - fromPose.y) * p - Math.sin(p * Math.PI) * arcY,
rotation: fromPose.rotation + (toPose.rotation - fromPose.rotation) * p,
});
if (done) {
if (!open) arcPoseRef.current = null;
rafId = 0;
} else {
rafId = requestAnimationFrame(tickArc);
}
};
rafId = requestAnimationFrame(tickArc);
return () => cancelAnimationFrame(rafId);
}, [open, reducedMotion]);
// Mark `hasOpened = true` one frame after opening so first reveal has 0ms item swap delay
useEffect(() => {
if (!open) return;
const id = requestAnimationFrame(() => setHasOpened(true));
return () => cancelAnimationFrame(id);
}, [open]);
// Update item targets when `activeIndex` changes (instant on first frame, 0.2s bounce-0 spring thereafter)
useLayoutEffect(() => {
const instant = !hasOpened || reducedMotion;
for (let i = 0; i < itemSpringsRef.current.length; i++) {
const isAct = i === activeIndex;
const sp = itemSpringsRef.current[i];
const targetOp = isAct ? 1 : 0;
const targetSc = isAct || reducedMotion ? 1 : 0.5;
sp.opacity.target = targetOp;
sp.scale.target = targetSc;
if (instant) {
sp.opacity.pos = targetOp;
sp.opacity.vel = 0;
sp.scale.pos = targetSc;
sp.scale.vel = 0;
const el = itemRefs.current[i];
if (el) {
el.style.opacity = String(targetOp);
el.style.transform = `scale(${targetSc})`;
el.style.visibility = isAct ? "visible" : "hidden";
}
}
}
if (!instant) startSpringsLoop();
}, [activeIndex, hasOpened, reducedMotion]);
// Close cleanly on scroll, resize, window blur, or Escape
useEffect(() => {
if (!open) return;
const onDismiss = () => {
setOpen(false);
setHasOpened(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onDismiss();
};
window.addEventListener("scroll", onDismiss, { capture: true, passive: true });
window.addEventListener("resize", onDismiss);
window.addEventListener("blur", onDismiss);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("scroll", onDismiss, true);
window.removeEventListener("resize", onDismiss);
window.removeEventListener("blur", onDismiss);
window.removeEventListener("keydown", onKey);
};
}, [open]);
useEffect(() => {
return () => {
cancelAnimationFrame(followRafRef.current);
cancelAnimationFrame(springRafRef.current);
};
}, []);
return (
<div ref={stageRef} className="fpl-stage">
<style>{SCOPED_CSS}</style>
<h3 className="fpl-header">{copyLang === "zh" ? "精选项目" : "Projects"}</h3>
<div className="fpl-divider" aria-hidden="true" />
<div
className="fpl-list"
onPointerEnter={handlePointer}
onPointerMove={handlePointer}
onPointerLeave={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
sideSignRef.current = e.clientX < rect.left + rect.width / 2 ? 1 : -1;
closePreview();
}}
onPointerCancel={closePreview}
>
{PROJECTS.map((item, idx) => (
<a
key={item.key}
href={`#${item.key}`}
onClick={(e) => e.preventDefault()}
data-arc-index={idx}
className="fpl-row"
style={isThumbnail && idx === 4 ? { background: "#f5f5f5" } : undefined}
onFocus={(e) => {
if (!e.currentTarget.matches(":focus-visible")) return;
const rect = e.currentTarget.getBoundingClientRect();
sideSignRef.current = 1;
trackPointer(rect, rect.left + rect.width / 2, rect.top + rect.height / 2);
setActiveIndex(idx);
setOpen(true);
}}
onBlur={closePreview}
>
<span className="fpl-row-title">
{copyLang === "zh" ? item.titleZh : item.titleEn}
</span>
<span className="fpl-row-desc">
{copyLang === "zh" ? item.descZh : item.descEn}
</span>
</a>
))}
</div>
{/* Static miniature card ONLY inside non-interactive /recipes gallery overview card */}
{isThumbnail && (
<div className="fpl-thumb-card" aria-hidden="true">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={PROJECTS[4].image.src}
alt=""
width={236}
height={180}
className="fpl-picture"
style={{ borderRadius: `${cardRadiusPx}px` }}
/>
</div>
)}
{mounted &&
!isThumbnail &&
createPortal(
<div
ref={anchorRef}
className="fpl-anchor"
style={{ width: boxW, height: boxH }}
aria-hidden="true"
>
<div ref={layerRef} className="fpl-layer">
<div ref={swingRef} className="fpl-swing">
<div
ref={stackRef}
className="fpl-stack"
style={{
width: boxW,
height: boxH,
opacity: 0,
transform: "scale(0.1)",
}}
>
{PROJECTS.map((item, idx) => {
const scaleFit = Math.min(boxW / item.image.width, boxH / item.image.height);
const w = Math.round(item.image.width * scaleFit);
const h = Math.round(item.image.height * scaleFit);
return (
<div
key={item.key}
ref={(node) => {
itemRefs.current[idx] = node;
}}
className="fpl-item"
style={{
rotate: `${item.tilt}deg`,
opacity: idx === 0 ? 1 : 0,
transform: idx === 0 ? "scale(1)" : "scale(0.5)",
visibility: idx === 0 ? "visible" : "hidden",
}}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
className="fpl-picture"
src={item.image.src}
alt=""
width={w}
height={h}
style={{ borderRadius: `${cardRadiusPx}px` }}
decoding="async"
draggable={false}
/>
</div>
);
})}
</div>
</div>
</div>
</div>,
document.body
)}
</div>
);
}
export default function PortfolioProjects() {
return <FloatingPreviewList params={listParams} />;
}
参数参考
| 属性 | 默认值 | 当前值 | 说明 |
|---|---|---|---|
copyLang 目录文案语言 | en | en | 在英文版与中文版脱敏个人作品目录之间切换。 |
cardWidthPx 预览框最大宽度 | 300 | 300 | 3:2 预览边界框的最大宽度(内部每件作品保持各自原始长宽比等比缩放)。 |
arcOffsetPx 进出弧线偏移 | 72 | 72 | 鼠标移入/移出左半区或右半区时,正弦抛物弧线的横向甩出幅度。 |
enterDuration 进出弹簧时长 | 0.4 | 0.4 | 移入与移出时整体缩放(0.1↔1)与抛物弧线的弹簧视觉时长。 |
enterBounce 进出回弹弹性 | 0.24 | 0.24 | 卡片甩出与收回时的弹簧回弹比例(默认 0.24)。 |
swapDuration 切项过渡时长 | 0.2 | 0.2 | 在相邻项目行之间滑过时,新旧图片 0.5↔1 缩放切换的无回弹弹簧时长。 |
swingGain 钟摆惯性幅度 | 1 | 1 | 以鼠标坐标为支点的横向钟摆旋转增益系数。 |
cardRadiusPx 图片圆角半径 | 8 | 8 | 每张作品预览图片的圆角半径(默认 8px)。 |