Files
personal/components/canvas/LoadingCurtain.tsx
T
virtheart 1cc36cb9f7 fix: 移动端菜单只见背景不见内容 — 幕布 z-[60] 回归原版 z-30
LoadingCurtain 容器 z-[60] 高于菜单(z-40)/Header(z-50),菜单展开
时整个被幕布盖住。原版该 Canvas 即 z-30(chunk 3c6cc5b2 提取证据),
压回 z-30 恢复原版层叠:内容(≤20) < 幕布(30) < 菜单/进度条(40) < Header(50)。
2026-09-02 23:17:55 +08:00

460 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useEffect, useMemo, useRef } from "react";
import { useLayoutEffect } from "react";
import { Canvas, useFrame, useThree } from "@react-three/fiber";
import { Color, MathUtils, UnsignedByteType } from "three";
import { Effect, BlendFunction } from "postprocessing";
import { EffectComposer } from "@react-three/postprocessing";
import { useResolvedTheme } from "@/lib/shellMedia";
import { customCubic } from "@/lib/customCubic";
/**
* Entry/route transition curtain — 1:1 port of the original fullscreen
* transition canvas (chunk 3c6cc5b2fcccdee5.js, module 34841):
*
* - `s`: a separate fixed fullscreen canvas (demand frameloop, alpha,
* premultiplied, no depth/stencil) holding only the mask material.
* - `p`: radial-hole mask mesh (renderOrder 2000, clip-space quad):
* alpha 0 inside the hole (content visible), 1 outside; the hole
* radius animates from the `max(aspect,1/aspect)` diagonal to 0
* (closed) or back up (open) with customCubic; the last 8% of progress
* fills the pinhole (fillMix).
* - `g`/`w`: MaskedDotsEffect post-processing (pixelSize 16 × dpr,
* radius 0.8 × mask alpha, BlendFunction.SRC) rasterizing the mask
* into the overlay-colored dot grid.
*
* Light theme overlay color (f): dark "#191b1b", light "#efede7".
*/
const CURTAIN_COLORS = ["#191b1b", "#efede7"] as const;
const MASK_VERT = `varying vec2 vUv;
void main() {
vUv = position.xy * 0.5 + 0.5;
gl_Position = vec4(position.xy, 0.0, 1.0);
}
`;
const MASK_FRAG = `precision highp float;
uniform vec3 uColor;
uniform float uFeather;
uniform float uAspect;
uniform float uHoleRadius;
uniform float uProgress;
varying vec2 vUv;
void main() {
vec2 p = vUv * 2.0 - 1.0;
if (uAspect > 1.0) {
p.x *= uAspect;
} else {
p.y /= max(uAspect, 0.0001);
}
float d = length(p);
float edge = max(uFeather, uHoleRadius * 0.12);
// 洞内为 0,洞外为 1。
float alphaHole = smoothstep(uHoleRadius, uHoleRadius + edge, d);
// 只在动画结束前一小段把“针孔”补满,让洞像是彻底消失。
float fillMix = smoothstep(0.92, 1.0, uProgress);
float alpha = mix(alphaHole, 1.0, fillMix);
// 预乘 alpha,避免透明像素携带 rgb 导致后期采样出现黑边/暗圈。
gl_FragColor = vec4(uColor * alpha, alpha);
#include <colorspace_fragment>
}
`;
const DOTS_FRAG = `uniform float pixelSize;
uniform float uFeather;
uniform float uAspect;
uniform float uHoleRadius;
uniform float uProgress;
uniform vec3 uOverlayColor;
void dotsMainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
vec2 normalizedPixelSize = pixelSize / resolution;
// 用传入的 inputColor.a 驱动圆点大小:越不透明圆点越大,越透明圆点越小。
float a = clamp(inputColor.a, 0.0, 1.0);
vec2 cellUV = fract(uv / normalizedPixelSize);
// 透明度 -> 圆点半径:a=1 时覆盖整个 cell,避免蒙版填充区漏出底图。
// sqrt(2)/2 是单位正方形中心到角的距离。
float radius = 0.8 * a;
vec2 circleCenter = vec2(0.5, 0.5);
float distanceFromCenter = distance(cellUV, circleCenter);
float aa = fwidth(distanceFromCenter) * 1.5;
float circleMask = smoothstep(radius, radius - aa, distanceFromCenter);
// 输出为 mask:rgb/alpha 都是 circleMask,供后期用来替换 opacity。
outputColor = vec4(vec3(circleMask), circleMask);
}
float radialMaskAlpha(vec2 uv) {
vec2 p = uv * 2.0 - 1.0;
if (uAspect > 1.0) {
p.x *= uAspect;
} else {
p.y /= max(uAspect, 0.0001);
}
float d = length(p);
float edge = max(uFeather, uHoleRadius * 0.12);
// 洞内为 0,洞外为 1。
float alphaHole = smoothstep(uHoleRadius, uHoleRadius + edge, d);
// 与 radial_mask.frag.glsl 保持一致:末段补满针孔。
float fillMix = smoothstep(0.92, 1.0, uProgress);
return mix(alphaHole, 1.0, fillMix);
}
void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) {
// 用蒙版 alpha 直接驱动点阵大小(0=最小,1=最大),不再只处理过渡带。
// 为了让点阵在一个 cell 内保持一致:用 cell 中心点的 alpha 驱动圆点大小。
vec2 normalizedPixelSize = pixelSize / resolution;
vec2 cellId = floor(uv / normalizedPixelSize);
vec2 uvCellCenter = (cellId + vec2(0.5)) * normalizedPixelSize;
float cellAlpha = clamp(radialMaskAlpha(uvCellCenter), 0.0, 1.0);
vec4 dotOut;
dotsMainImage(vec4(0.0, 0.0, 0.0, cellAlpha), uv, dotOut);
float dotMask = clamp(dotOut.a, 0.0, 1.0);
float finalAlpha = dotMask;
// 直接输出 overlay 颜色(预乘 alpha),避免颜色混合导致点边黑描边。
vec3 outRgb = uOverlayColor * finalAlpha;
outputColor = vec4(outRgb, finalAlpha);
}
`;
class MaskedDotsEffect extends Effect {
pixelSize: number;
feather: number;
aspect: number;
holeRadius: number;
progress: number;
overlayColor: Color;
private _uPixelSize: { value: number };
private _uFeather: { value: number };
private _uAspect: { value: number };
private _uHoleRadius: { value: number };
private _uProgress: { value: number };
private _uOverlayColor: { value: Color };
private _dirty = true;
constructor({
pixelSize = 32,
feather = 0.5,
aspect = 1,
holeRadius = 2,
progress = 0,
overlayColor = new Color(1, 1, 1),
} = {}) {
const uniforms = new Map<string, { value: any }>([
["pixelSize", { value: pixelSize }],
["uFeather", { value: feather }],
["uAspect", { value: aspect }],
["uHoleRadius", { value: holeRadius }],
["uProgress", { value: progress }],
["uOverlayColor", { value: overlayColor.clone() }],
]);
super("MaskedDotsEffect", DOTS_FRAG, {
uniforms: uniforms as unknown as Map<string, import("three").Uniform<any>>,
blendFunction: BlendFunction.SRC,
});
this.pixelSize = pixelSize;
this.feather = feather;
this.aspect = aspect;
this.holeRadius = holeRadius;
this.progress = progress;
this.overlayColor = overlayColor.clone();
this._uPixelSize = uniforms.get("pixelSize")!;
this._uFeather = uniforms.get("uFeather")!;
this._uAspect = uniforms.get("uAspect")!;
this._uHoleRadius = uniforms.get("uHoleRadius")!;
this._uProgress = uniforms.get("uProgress")!;
this._uOverlayColor = uniforms.get("uOverlayColor")!;
}
setParams(e: {
pixelSize?: number;
feather?: number;
aspect?: number;
holeRadius?: number;
progress?: number;
overlayColor?: Color;
}) {
let dirty = false;
if (typeof e.pixelSize === "number" && e.pixelSize !== this.pixelSize) {
this.pixelSize = e.pixelSize;
dirty = true;
}
if (typeof e.feather === "number" && e.feather !== this.feather) {
this.feather = e.feather;
dirty = true;
}
if (typeof e.aspect === "number" && e.aspect !== this.aspect) {
this.aspect = e.aspect;
dirty = true;
}
if (typeof e.holeRadius === "number" && e.holeRadius !== this.holeRadius) {
this.holeRadius = e.holeRadius;
dirty = true;
}
if (typeof e.progress === "number" && e.progress !== this.progress) {
this.progress = e.progress;
dirty = true;
}
if (e.overlayColor && !this.overlayColor.equals(e.overlayColor)) {
this.overlayColor.copy(e.overlayColor);
dirty = true;
}
if (dirty) this._dirty = true;
}
update() {
if (this._dirty) {
this._dirty = false;
this._uPixelSize.value = this.pixelSize;
this._uFeather.value = this.feather;
this._uAspect.value = this.aspect;
this._uHoleRadius.value = this.holeRadius;
this._uProgress.value = this.progress;
this._uOverlayColor.value.copy(this.overlayColor);
}
}
}
function RadialHoleMask({
open,
duration,
initialProgress,
resetKey,
onComplete,
materialRef,
}: {
open: boolean;
duration: number;
initialProgress?: number;
resetKey: string;
onComplete?: (open: boolean) => void;
materialRef: React.MutableRefObject<any>;
}) {
const { size } = useThree();
const invalidate = useThree((s) => s.invalidate);
// Original f(p): dark picks f[0] (#191b1b), light picks f[1] (#efede7).
const isDark = useResolvedTheme() === "dark";
const color = isDark ? CURTAIN_COLORS[0] : CURTAIN_COLORS[1];
const uniforms = useMemo(
() => ({
uColor: { value: new Color() },
uFeather: { value: 0.8 },
uAspect: { value: 1 },
uHoleRadius: { value: 2 },
uProgress: { value: 0 },
}),
[]
);
// b: sqrt(max(aspect, 1/aspect)^2 + 1) — the closed-hole diagonal norm.
const bMax = useMemo(() => {
const aspect = size.width / Math.max(1, size.height);
const t = Math.max(aspect, 1 / aspect);
return Math.sqrt(t * t + 1);
}, [size.width, size.height]);
useEffect(() => {
invalidate();
}, [color, invalidate]);
useEffect(() => {
if (materialRef.current) {
const aspect = size.width / Math.max(1, size.height);
materialRef.current.uniforms.uAspect.value = aspect;
}
}, [size.width, size.height, materialRef]);
const progressRef = useRef(0);
const startTimeRef = useRef<number | null>(null);
const fromRef = useRef(0);
const toRef = useRef(0);
const completedRef = useRef(false);
const initializedRef = useRef(false);
// initialProgress: cover fully closed on mount (entry:wait → 1).
useLayoutEffect(() => {
if (initializedRef.current || typeof initialProgress !== "number") return;
initializedRef.current = true;
const e = MathUtils.clamp(initialProgress, 0, 1);
progressRef.current = e;
fromRef.current = e;
const holeRadius = MathUtils.lerp(bMax, 0, e);
if (materialRef.current) {
materialRef.current.uniforms.uHoleRadius.value = holeRadius;
materialRef.current.uniforms.uProgress.value = e;
}
invalidate();
}, [initialProgress, bMax, materialRef, invalidate]);
// Reset the animation whenever open/resetKey changes.
useLayoutEffect(() => {
fromRef.current = progressRef.current;
toRef.current = +!!open;
startTimeRef.current = null;
completedRef.current = false;
invalidate();
}, [open, resetKey, invalidate]);
useFrame((state) => {
const elapsed = state.clock.getElapsedTime();
if (startTimeRef.current === null) startTimeRef.current = elapsed;
const l = elapsed - startTimeRef.current;
const t01 = MathUtils.clamp(l / Math.max(1e-6, duration), 0, 1);
const eased = customCubic(t01);
progressRef.current = MathUtils.lerp(fromRef.current, toRef.current, eased);
const holeRadius = MathUtils.lerp(bMax, 0, progressRef.current);
if (materialRef.current) {
materialRef.current.uniforms.uHoleRadius.value = holeRadius;
materialRef.current.uniforms.uProgress.value = progressRef.current;
materialRef.current.uniforms.uColor.value.set(color);
}
if (!completedRef.current && t01 >= 1 - 1e-6) {
completedRef.current = true;
onComplete?.(open);
}
if (!completedRef.current && t01 < 1 - 1e-6) state.invalidate();
});
return (
<mesh renderOrder={2000} frustumCulled={false}>
<planeGeometry args={[2, 2]} />
<shaderMaterial
ref={materialRef}
transparent
premultipliedAlpha
depthTest={false}
depthWrite={false}
toneMapped={false}
uniforms={uniforms}
vertexShader={MASK_VERT}
fragmentShader={MASK_FRAG}
/>
</mesh>
);
}
function DotsPost({ materialRef }: { materialRef: React.MutableRefObject<any> }) {
const effect = useMemo(
() =>
new MaskedDotsEffect({
pixelSize: 32,
feather: 0.5,
aspect: 1,
holeRadius: 2,
progress: 0,
overlayColor: new Color(1, 1, 1),
}),
[]
);
const dpr = useThree((s) => s.viewport.dpr);
useEffect(() => () => effect.dispose(), [effect]);
useFrame(() => {
const t = materialRef.current;
if (t) {
effect.setParams({
pixelSize: 16 * dpr,
feather: t.uniforms.uFeather.value,
aspect: t.uniforms.uAspect.value,
holeRadius: t.uniforms.uHoleRadius.value,
progress: t.uniforms.uProgress.value,
overlayColor: t.uniforms.uColor.value,
});
}
}, 1);
return (
<EffectComposer
multisampling={0}
autoClear
renderPriority={999}
frameBufferType={UnsignedByteType}
>
<primitive object={effect} />
</EffectComposer>
);
}
/**
* Fullscreen transition canvas — port of the original `s` wrapper:
* demand frameloop, alpha, premultiplied, depth/stencil off.
*/
export function LoadingCurtain({
open,
duration = 0.8,
initialProgress,
resetKey,
onComplete,
}: {
open: boolean;
duration?: number;
initialProgress?: number;
resetKey: string;
onComplete?: (open: boolean) => void;
}) {
const materialRef = useRef<any>(null);
// R3F's Canvas container carries inline `position: relative; width/height:
// 100%` which OVERRIDES any Tailwind `fixed inset-0` on the Canvas itself —
// the curtain then renders as an in-flow ~150px strip (invisible during
// transitions and, worse, pointer-events:auto so it eats card clicks). A
// dedicated fullscreen fixed wrapper gives the container a real viewport
// box; pointer-events:none inherits to the whole subtree.
return (
// 原版这块幕布 Canvas 是 "z-30 fixed inset-0 pointer-events-none":
// 盖住页面内容(≤z-20),但必须低于移动端全屏菜单(z-40)、
// 进度条(z-40)与 Header(z-50)——曾写成 z-[60] 会把菜单整个
// 压在幕布下面,移动端打开菜单只剩一片背景色。
<div className="fixed inset-0 z-30 pointer-events-none">
<Canvas
dpr={[1, 2]}
frameloop="demand"
style={{ pointerEvents: "none" }}
gl={{
alpha: true,
antialias: false,
premultipliedAlpha: true,
depth: false,
stencil: false,
powerPreference: "high-performance",
preserveDrawingBuffer: false,
}}
>
<RadialHoleMask
open={open}
duration={duration}
initialProgress={initialProgress}
resetKey={resetKey}
onComplete={onComplete}
materialRef={materialRef}
/>
<DotsPost materialRef={materialRef} />
</Canvas>
</div>
);
}
export default LoadingCurtain;