Fluid Glass

Refractive glass lens, cube or bar that follows the pointer over a scrolling WebGL scene; the glb model is passed as a URL prop.

pnpm dlx shadcn@latest add @leo/fluid-glass

Props

NameTypeDefaultDescription
backgroundColorstring | undefined#120F17
barPropsModeProps | undefined{}
classNamestring | undefined-
cubePropsModeProps | undefined{}
dracoDecoderPathstring | undefined-Self-hosted Draco decoder folder. Without it a Draco-compressed model (lens.glb is one) makes drei fetch the decoder from a CDN (gstatic).
imagesstring[] | undefined[ makePanel("#4f46e5", "#0ea5e9", "#f0abfc"), makePanel("#be123c", "#f97316", "#fde68a"), makePanel("#0f766e", "#22c55e", "#a7f3d0"), makePanel("#7c3aed", "#ec4899", "#fbcfe8"), makePanel("#1d4ed8", "#06b6d4", "#bae6fd"), ]Up to five image URLs for the scrolling panels; defaults to generated gradients.
lensPropsModeProps | undefined{}
modeundefined | "lens" | "bar" | "cube"lens
modelUrl*string-URL of the glb matching `mode`: lens.glb, cube.glb or bar.glb from react-bits.
textColorstring | undefined#ffffff
titlestring | undefinedReact BitsHeadline drawn in the scene.

Dependencies

  • @react-three/drei@^10.7.4
  • @react-three/fiber@^9.3.0
  • maath@^0.10.8
  • three@^0.180.0

Source

"use client";

import {
  Image,
  MeshTransmissionMaterial,
  Preload,
  Scroll,
  ScrollControls,
  useFBO,
  useGLTF,
  useScroll,
} from "@react-three/drei";
import { Canvas, createPortal, type ThreeElements, useFrame, useThree } from "@react-three/fiber";
import { easing } from "maath";
import { memo, type ReactNode, useEffect, useMemo, useRef, useState } from "react";
/* eslint-disable react/no-unknown-property */
import * as THREE from "three";
import { cn } from "@/lib/utils";

// Generated gradient panels with a few shapes, so refraction has something to bend and nothing
// is fetched from the network.
function makePanel(from: string, to: string, accent: string): string {
  const svg =
    `<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900" viewBox="0 0 900 900">` +
    `<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">` +
    `<stop offset="0" stop-color="${from}"/><stop offset="1" stop-color="${to}"/>` +
    `</linearGradient></defs><rect width="900" height="900" fill="url(#g)"/>` +
    `<circle cx="640" cy="260" r="190" fill="${accent}" fill-opacity="0.55"/>` +
    `<circle cx="250" cy="650" r="140" fill="${accent}" fill-opacity="0.35"/>` +
    `<rect x="120" y="120" width="260" height="30" rx="15" fill="#fff" fill-opacity="0.5"/>` +
    `<rect x="120" y="170" width="170" height="30" rx="15" fill="#fff" fill-opacity="0.3"/>` +
    `</svg>`;
  return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}

const DEFAULT_IMAGES = [
  makePanel("#4f46e5", "#0ea5e9", "#f0abfc"),
  makePanel("#be123c", "#f97316", "#fde68a"),
  makePanel("#0f766e", "#22c55e", "#a7f3d0"),
  makePanel("#7c3aed", "#ec4899", "#fbcfe8"),
  makePanel("#1d4ed8", "#06b6d4", "#bae6fd"),
];

const DEFAULT_NAV_ITEMS: NavItem[] = [
  { label: "Home", link: "" },
  { label: "About", link: "" },
  { label: "Contact", link: "" },
];

const EMPTY_MODE_PROPS: ModeProps = {};

type Mode = "lens" | "bar" | "cube";

interface NavItem {
  label: string;
  link: string;
}

type ModeProps = Record<string, unknown>;

// react-use-measure (inside <Canvas>) feeds its ResizeObserver through the scroll debounce, a 50 ms
// timer; with no debounce the canvas gets its size on the first observation.
const CANVAS_RESIZE = { debounce: 0 };

// r3f 9 rethrows a failed renderer creation while rendering <Canvas>, which would unmount the whole app.
// Starts false so the server render and the first client render match.
function useWebGLSupported() {
  const [supported, setSupported] = useState(false);
  useEffect(() => {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl");
    gl?.getExtension("WEBGL_lose_context")?.loseContext();
    setSupported(gl !== null);
  }, []);
  return supported;
}

export interface FluidGlassProps {
  /** URL of the glb matching `mode`: lens.glb, cube.glb or bar.glb from react-bits. */
  modelUrl: string;
  mode?: Mode;
  lensProps?: ModeProps;
  barProps?: ModeProps;
  cubeProps?: ModeProps;
  backgroundColor?: string;
  textColor?: string;
  /** Headline drawn in the scene. */
  title?: string;
  /** Up to five image URLs for the scrolling panels; defaults to generated gradients. */
  images?: string[];
  /**
   * Self-hosted Draco decoder folder. Without it a Draco-compressed model (lens.glb is one) makes drei
   * fetch the decoder from a CDN (gstatic).
   */
  dracoDecoderPath?: string;
  className?: string;
}

export function FluidGlass({
  modelUrl,
  mode = "lens",
  lensProps = EMPTY_MODE_PROPS,
  barProps = EMPTY_MODE_PROPS,
  cubeProps = EMPTY_MODE_PROPS,
  backgroundColor = "#120F17",
  textColor = "#ffffff",
  title = "React Bits",
  images = DEFAULT_IMAGES,
  dracoDecoderPath,
  className,
}: FluidGlassProps) {
  const webgl = useWebGLSupported();
  const Wrapper = mode === "bar" ? Bar : mode === "cube" ? Cube : Lens;
  const rawOverrides = mode === "bar" ? barProps : mode === "cube" ? cubeProps : lensProps;

  const { navItems = DEFAULT_NAV_ITEMS, ...modeProps } = rawOverrides;

  return (
    <div className={cn("relative h-full w-full", className)}>
      {webgl && (
        <Canvas
          resize={CANVAS_RESIZE}
          camera={{ position: [0, 0, 20], fov: 15 }}
          gl={{ alpha: true, toneMapping: THREE.NoToneMapping }}
          style={{ backgroundColor }}
        >
          <ScrollControls damping={0.2} pages={3} distance={0.4}>
            {mode === "bar" && <NavItems items={navItems as NavItem[]} textColor={textColor} />}
            <Wrapper
              glb={modelUrl}
              dracoDecoderPath={dracoDecoderPath}
              modeProps={modeProps}
              backgroundColor={backgroundColor}
            >
              <Scroll>
                <Typography textColor={textColor} title={title} />
                <Images urls={images.length > 0 ? images : DEFAULT_IMAGES} />
              </Scroll>
              <Scroll html />
              <Preload />
            </Wrapper>
          </ScrollControls>
        </Canvas>
      )}
    </div>
  );
}

type MeshProps = ThreeElements["mesh"];

interface ModeWrapperProps extends MeshProps {
  children?: ReactNode;
  glb: string;
  dracoDecoderPath?: string;
  geometryKey: string;
  lockToBottom?: boolean;
  followPointer?: boolean;
  modeProps?: ModeProps;
  backgroundColor?: string;
}

type ModeComponentProps = Omit<ModeWrapperProps, "geometryKey">;

interface ZoomMaterial extends THREE.Material {
  zoom: number;
}

interface ZoomMesh extends THREE.Mesh<THREE.BufferGeometry, ZoomMaterial> {}

type ZoomGroup = THREE.Group & { children: ZoomMesh[] };

const ModeWrapper = memo(function ModeWrapper({
  children,
  glb,
  dracoDecoderPath,
  geometryKey,
  lockToBottom = false,
  followPointer = true,
  modeProps = {},
  backgroundColor = "#120F17",
  ...props
}: ModeWrapperProps) {
  const ref = useRef<THREE.Mesh>(null!);
  const { nodes } = useGLTF(glb, dracoDecoderPath ?? true);
  const buffer = useFBO();
  const { viewport: vp } = useThree();
  const [scene] = useState<THREE.Scene>(() => new THREE.Scene());
  const geoWidthRef = useRef<number>(1);

  useEffect(() => {
    const geo = (nodes[geometryKey] as THREE.Mesh)?.geometry;
    if (!geo) return;
    geo.computeBoundingBox();
    geoWidthRef.current = geo.boundingBox!.max.x - geo.boundingBox!.min.x || 1;
  }, [nodes, geometryKey]);

  useFrame((state, delta) => {
    const { gl, viewport, pointer, camera } = state;
    const v = viewport.getCurrentViewport(camera, [0, 0, 15]);

    const destX = followPointer ? (pointer.x * v.width) / 2 : 0;
    const destY = lockToBottom
      ? -v.height / 2 + 0.2
      : followPointer
        ? (pointer.y * v.height) / 2
        : 0;
    easing.damp3(ref.current.position, [destX, destY, 15], 0.15, delta);

    if ((modeProps as { scale?: number }).scale == null) {
      const maxWorld = v.width * 0.9;
      const desired = maxWorld / geoWidthRef.current;
      ref.current.scale.setScalar(Math.min(0.15, desired));
    }

    gl.setClearColor(0x000000, 0);
    gl.setRenderTarget(buffer);
    gl.render(scene, camera);
    gl.setRenderTarget(null);
    gl.setClearColor(0x000000, 0);
  });

  const { scale, ior, thickness, anisotropy, chromaticAberration, ...extraMat } = modeProps as {
    scale?: number;
    ior?: number;
    thickness?: number;
    anisotropy?: number;
    chromaticAberration?: number;
    [key: string]: unknown;
  };

  return (
    <>
      {createPortal(
        <>
          <mesh position={[0, 0, -5]} scale={[vp.width * 2, vp.height * 2, 1]}>
            <planeGeometry />
            <meshBasicMaterial color={backgroundColor} toneMapped={false} />
          </mesh>
          {children}
        </>,
        scene,
      )}
      <mesh scale={[vp.width, vp.height, 1]}>
        <planeGeometry />
        <meshBasicMaterial map={buffer.texture} transparent toneMapped={false} />
      </mesh>
      <mesh
        ref={ref}
        scale={scale ?? 0.15}
        rotation-x={Math.PI / 2}
        geometry={(nodes[geometryKey] as THREE.Mesh)?.geometry}
        {...props}
      >
        <MeshTransmissionMaterial
          buffer={buffer.texture}
          ior={ior ?? 1.15}
          thickness={thickness ?? 5}
          anisotropy={anisotropy ?? 0.01}
          chromaticAberration={chromaticAberration ?? 0.1}
          {...(typeof extraMat === "object" && extraMat !== null ? extraMat : {})}
        />
      </mesh>
    </>
  );
});

function Lens({ modeProps, ...p }: ModeComponentProps) {
  return <ModeWrapper geometryKey="Cylinder" followPointer modeProps={modeProps} {...p} />;
}

function Cube({ modeProps, ...p }: ModeComponentProps) {
  return <ModeWrapper geometryKey="Cube" followPointer modeProps={modeProps} {...p} />;
}

function Bar({ modeProps = {}, ...p }: ModeComponentProps) {
  const defaultMat = {
    transmission: 1,
    roughness: 0,
    thickness: 10,
    ior: 1.15,
    color: "#ffffff",
    attenuationColor: "#ffffff",
    attenuationDistance: 0.25,
  };

  return (
    <ModeWrapper
      geometryKey="Cube"
      lockToBottom
      followPointer={false}
      modeProps={{ ...defaultMat, ...modeProps }}
      {...p}
    />
  );
}

const NAV_DEVICE = {
  mobile: { spacing: 0.2, fontSize: 0.035 },
  tablet: { spacing: 0.24, fontSize: 0.045 },
  desktop: { spacing: 0.3, fontSize: 0.045 },
};
const TITLE_DEVICE = {
  mobile: { fontSize: 0.2 },
  tablet: { fontSize: 0.4 },
  desktop: { fontSize: 0.6 },
};

type DeviceName = "mobile" | "tablet" | "desktop";

function getDevice(): DeviceName {
  const w = window.innerWidth;
  return w <= 639 ? "mobile" : w <= 1023 ? "tablet" : "desktop";
}

function useDevice(): DeviceName {
  const [device, setDevice] = useState<DeviceName>(getDevice);

  useEffect(() => {
    const onResize = () => setDevice(getDevice());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return device;
}

const FONT_STACK =
  'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
const PX_PER_EM = 128;

interface CanvasTextProps extends Omit<ThreeElements["mesh"], "children"> {
  text: string;
  fontSize: number;
  color: string;
  letterSpacing?: number;
}

// Text is rasterised with the system font instead of drei's <Text>, whose default font is fetched
// from a CDN at runtime.
function CanvasText({ text, fontSize, color, letterSpacing = 0, ...props }: CanvasTextProps) {
  const { texture, size } = useMemo(() => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const font = `600 ${PX_PER_EM}px ${FONT_STACK}`;
    const spacing = `${letterSpacing * PX_PER_EM}px`;
    let width = PX_PER_EM;
    if (ctx) {
      ctx.font = font;
      ctx.letterSpacing = spacing;
      width = Math.ceil(ctx.measureText(text).width + PX_PER_EM * 0.4);
    }
    const height = Math.ceil(PX_PER_EM * 1.6);
    canvas.width = width;
    canvas.height = height;
    if (ctx) {
      ctx.font = font;
      ctx.letterSpacing = spacing;
      ctx.fillStyle = color;
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(text, width / 2, height / 2);
    }
    const tex = new THREE.CanvasTexture(canvas);
    tex.colorSpace = THREE.SRGBColorSpace;
    return {
      texture: tex,
      size: [(width / PX_PER_EM) * fontSize, (height / PX_PER_EM) * fontSize] as [number, number],
    };
  }, [text, color, letterSpacing, fontSize]);

  useEffect(() => () => texture.dispose(), [texture]);

  return (
    <mesh {...props}>
      <planeGeometry args={size} />
      <meshBasicMaterial map={texture} transparent toneMapped={false} depthWrite={false} />
    </mesh>
  );
}

function NavItems({ items, textColor }: { items: NavItem[]; textColor: string }) {
  const group = useRef<THREE.Group>(null!);
  const { viewport, camera } = useThree();

  const device = useDevice();
  const { spacing, fontSize } = NAV_DEVICE[device];

  useFrame(() => {
    if (!group.current) return;
    const v = viewport.getCurrentViewport(camera, [0, 0, 15]);
    group.current.position.set(0, -v.height / 2 + 0.2, 15.1);

    group.current.children.forEach((child, i) => {
      child.position.x = (i - (items.length - 1) / 2) * spacing;
    });
  });

  const handleNavigate = (link: string) => {
    if (!link) return;
    if (link.startsWith("#")) window.location.hash = link;
    else window.location.href = link;
  };

  return (
    <group ref={group} renderOrder={10}>
      {items.map(({ label, link }) => (
        <CanvasText
          key={label}
          text={label}
          fontSize={fontSize}
          color={textColor}
          renderOrder={10}
          onClick={(e) => {
            e.stopPropagation();
            handleNavigate(link);
          }}
          onPointerOver={() => {
            document.body.style.cursor = "pointer";
          }}
          onPointerOut={() => {
            document.body.style.cursor = "auto";
          }}
        />
      ))}
    </group>
  );
}

function Images({ urls }: { urls: string[] }) {
  const url = (i: number) => urls[i % urls.length];
  const group = useRef<ZoomGroup>(null!);
  const data = useScroll();
  const { height } = useThree((s) => s.viewport);

  useFrame(() => {
    group.current.children[0].material.zoom = 1 + data.range(0, 1 / 3) / 3;
    group.current.children[1].material.zoom = 1 + data.range(0, 1 / 3) / 3;
    group.current.children[2].material.zoom = 1 + data.range(1.15 / 3, 1 / 3) / 2;
    group.current.children[3].material.zoom = 1 + data.range(1.15 / 3, 1 / 3) / 2;
    group.current.children[4].material.zoom = 1 + data.range(1.15 / 3, 1 / 3) / 2;
  });

  return (
    <group ref={group}>
      <Image position={[-2, 0, 0]} scale={[3, height / 1.1]} url={url(0)} />
      <Image position={[2, 0, 3]} scale={3} url={url(1)} />
      <Image position={[-2.05, -height, 6]} scale={[1, 3]} url={url(2)} />
      <Image position={[-0.6, -height, 9]} scale={[1, 2]} url={url(3)} />
      <Image position={[0.75, -height, 10.5]} scale={1.5} url={url(4)} />
    </group>
  );
}

function Typography({ textColor, title }: { textColor: string; title: string }) {
  const device = useDevice();
  const { fontSize } = TITLE_DEVICE[device];

  return (
    <CanvasText
      position={[0, 0, 12]}
      fontSize={fontSize}
      letterSpacing={-0.05}
      color={textColor}
      text={title}
    />
  );
}

export default FluidGlass;