liquid-glass.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. "use client";
  2. import {
  3. useEffect,
  4. useId,
  5. useRef,
  6. useState,
  7. type CSSProperties,
  8. type HTMLAttributes,
  9. type ReactNode,
  10. type RefObject,
  11. } from "react";
  12. import {
  13. buildLensMap,
  14. supportsBackdropRefraction,
  15. type LensMap,
  16. } from "./displacement";
  17. import { cn } from "@/lib/utils";
  18. /* ---------- Light: the cursor is the light source for every glass surface ---------- */
  19. const litElements = new Set<HTMLElement>();
  20. let lightFrame = 0;
  21. let lightX = -1;
  22. let lightY = -1;
  23. let lightBound = false;
  24. const clamp = (v: number, min: number, max: number) =>
  25. Math.min(max, Math.max(min, v));
  26. function paintLight() {
  27. lightFrame = 0;
  28. const vh = window.innerHeight;
  29. litElements.forEach((el) => {
  30. if (el.hasAttribute("data-steady-light")) return;
  31. const r = el.getBoundingClientRect();
  32. if (r.bottom < -80 || r.top > vh + 80 || !r.width) return;
  33. const cx = r.left + r.width / 2;
  34. const cy = r.top + r.height / 2;
  35. const angle = (Math.atan2(cx - lightX, -(cy - lightY)) * 180) / Math.PI;
  36. el.style.setProperty("--la", `${angle.toFixed(1)}deg`);
  37. el.style.setProperty(
  38. "--lx",
  39. `${clamp(((lightX - r.left) / r.width) * 100, -30, 130).toFixed(1)}%`,
  40. );
  41. el.style.setProperty(
  42. "--ly",
  43. `${clamp(((lightY - r.top) / r.height) * 100, -60, 160).toFixed(1)}%`,
  44. );
  45. });
  46. }
  47. function onPointerMove(e: PointerEvent) {
  48. if (e.pointerType === "touch") return;
  49. lightX = e.clientX;
  50. lightY = e.clientY;
  51. if (!lightFrame) lightFrame = requestAnimationFrame(paintLight);
  52. }
  53. export function registerLight(el: HTMLElement) {
  54. litElements.add(el);
  55. if (!lightBound) {
  56. window.addEventListener("pointermove", onPointerMove, { passive: true });
  57. lightBound = true;
  58. }
  59. return () => {
  60. litElements.delete(el);
  61. };
  62. }
  63. /* ---------- Refraction filter ---------- */
  64. export function GlassFilter({
  65. id,
  66. map,
  67. blur = 0.5,
  68. chroma = 0,
  69. saturate = 1.5,
  70. }: {
  71. id: string;
  72. map: LensMap;
  73. blur?: number;
  74. chroma?: number;
  75. saturate?: number;
  76. }) {
  77. const { url, scale, width, height } = map;
  78. const displace = (s: number, result: string) => (
  79. <feDisplacementMap
  80. in="blur"
  81. in2="map"
  82. result={result}
  83. scale={s}
  84. xChannelSelector="R"
  85. yChannelSelector="G"
  86. />
  87. );
  88. return (
  89. <svg
  90. aria-hidden
  91. height="0"
  92. style={{ position: "absolute", pointerEvents: "none" }}
  93. width="0"
  94. >
  95. <defs>
  96. <filter
  97. colorInterpolationFilters="sRGB"
  98. filterUnits="userSpaceOnUse"
  99. height={height}
  100. id={id}
  101. primitiveUnits="userSpaceOnUse"
  102. width={width}
  103. x="0"
  104. y="0"
  105. >
  106. <feGaussianBlur
  107. in="SourceGraphic"
  108. result="blur"
  109. stdDeviation={blur}
  110. />
  111. <feImage
  112. height={height}
  113. href={url}
  114. preserveAspectRatio="none"
  115. result="map"
  116. width={width}
  117. x="0"
  118. y="0"
  119. />
  120. {chroma > 0 ? (
  121. <>
  122. {displace(scale * (1 + chroma), "dr")}
  123. <feColorMatrix
  124. in="dr"
  125. result="r"
  126. type="matrix"
  127. values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0"
  128. />
  129. {displace(scale, "dg")}
  130. <feColorMatrix
  131. in="dg"
  132. result="g"
  133. type="matrix"
  134. values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0"
  135. />
  136. {displace(scale * (1 - chroma), "db")}
  137. <feColorMatrix
  138. in="db"
  139. result="b"
  140. type="matrix"
  141. values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0"
  142. />
  143. <feBlend in="r" in2="g" mode="screen" result="rg" />
  144. <feBlend in="rg" in2="b" mode="screen" result="disp" />
  145. </>
  146. ) : (
  147. displace(scale, "disp")
  148. )}
  149. <feColorMatrix in="disp" type="saturate" values={String(saturate)} />
  150. </filter>
  151. </defs>
  152. </svg>
  153. );
  154. }
  155. export type GlassOptions = {
  156. /** Width of the curved rim in px (defaults to ~1/3 of the shorter side). */
  157. bezel?: number;
  158. /** Glass thickness in px: drives how strongly the rim bends light. */
  159. thickness?: number;
  160. /** >1 turns the glass into a loupe. */
  161. magnify?: number;
  162. /** Corner radius in px; read from CSS when omitted. */
  163. radius?: number;
  164. blur?: number;
  165. chroma?: number;
  166. saturate?: number;
  167. /** Set false to keep the frosted fallback even in Chromium. */
  168. refract?: boolean;
  169. };
  170. /** Just the specular rim that follows the light, for glass that doesn't refract. */
  171. export function useGlassLight(ref: RefObject<HTMLElement | null>) {
  172. useEffect(
  173. () => (ref.current ? registerLight(ref.current) : undefined),
  174. [ref],
  175. );
  176. }
  177. /**
  178. * Turns the element in `ref` into liquid glass: real refraction through an
  179. * SVG displacement map in Chromium, frosted glass elsewhere, and a specular
  180. * rim that tracks the cursor everywhere.
  181. */
  182. export function useLiquidGlass(
  183. ref: RefObject<HTMLElement | null>,
  184. options: GlassOptions = {},
  185. ) {
  186. const id = `lg${useId().replace(/[^a-zA-Z0-9]/g, "")}`;
  187. const [map, setMap] = useState<LensMap | null>(null);
  188. const { bezel, thickness, magnify, radius, refract = true } = options;
  189. useEffect(() => {
  190. const el = ref.current;
  191. if (!el) return;
  192. const unlight = registerLight(el);
  193. if (!refract || !supportsBackdropRefraction()) return unlight;
  194. let frame = 0;
  195. const measure = () => {
  196. cancelAnimationFrame(frame);
  197. frame = requestAnimationFrame(() => {
  198. const w = el.offsetWidth;
  199. const h = el.offsetHeight;
  200. if (!w || !h) return;
  201. const r =
  202. radius ?? (parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0);
  203. const short = Math.min(w, h);
  204. setMap(
  205. buildLensMap({
  206. width: w,
  207. height: h,
  208. radius: r,
  209. bezel: bezel ?? short * 0.34,
  210. thickness: thickness ?? short * 0.5,
  211. magnify,
  212. }),
  213. );
  214. });
  215. };
  216. measure();
  217. const ro = new ResizeObserver(measure);
  218. ro.observe(el);
  219. return () => {
  220. ro.disconnect();
  221. cancelAnimationFrame(frame);
  222. unlight();
  223. };
  224. }, [ref, bezel, thickness, magnify, radius, refract]);
  225. return {
  226. glassProps: {
  227. "data-refract": map ? ("true" as const) : undefined,
  228. style: map
  229. ? ({ "--lg-filter": `url(#${id})` } as CSSProperties)
  230. : undefined,
  231. },
  232. filter: map ? (
  233. <GlassFilter
  234. blur={options.blur}
  235. chroma={options.chroma}
  236. id={id}
  237. map={map}
  238. saturate={options.saturate}
  239. />
  240. ) : null,
  241. };
  242. }
  243. type LiquidGlassProps = HTMLAttributes<HTMLDivElement> & {
  244. glass?: GlassOptions;
  245. children?: ReactNode;
  246. };
  247. export function LiquidGlass({
  248. glass,
  249. className,
  250. style,
  251. children,
  252. ...rest
  253. }: LiquidGlassProps) {
  254. const ref = useRef<HTMLDivElement>(null);
  255. const { glassProps, filter } = useLiquidGlass(ref, glass);
  256. return (
  257. <div
  258. ref={ref}
  259. {...rest}
  260. className={cn("lg", className)}
  261. data-refract={glassProps["data-refract"]}
  262. style={{ ...style, ...glassProps.style }}
  263. >
  264. {filter}
  265. <span aria-hidden className="lg-caustic" />
  266. {children}
  267. </div>
  268. );
  269. }