"use client";import * as React from "react";import { ArrowRight } from "lucide-react";import { SEARCHLIGHT_ART } from "./searchlight-art";import { cover, createSearchlight, onBox, readColor, type Layout, type Rgb, type Searchlight } from "./searchlight-gl";import { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, useInteractionReducedMotion } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * SEARCHLIGHT HERO: the headline, and a picture in the dark * * on when it first comes into view the lamp flickers * on (0.9s) and a cone of light opens from it * sweep left alone, the beam scans slowly across the * picture, 12s a pass * aim the pointer (or a sideways drag on a phone) takes * the beam; it follows on a spring and goes back to * sweeping 2.5s after the pointer leaves * found a spot in finds lit by the beam gets a ring and its * label, which stays 1.4s after the light moves on * reads words of the title the beam crosses light up * * The picture is yours (image + lamp, the point the light * comes from). Outside the beam it is graded into two dark * tones of your --primary, so it takes on any brand. * ───────────────────────────────────────────────────────── */export interface SearchlightPoint { /** Across the picture, 0 to 1. */ x: number; /** Down the picture, 0 to 1. */ y: number;}export interface SearchlightFind extends SearchlightPoint { label: string;}export interface SearchlightAction { label: string; href: string;}export interface SearchlightHeroProps { title: string; description?: string; /** A short line above the title. */ eyebrow?: string; primary?: SearchlightAction; secondary?: SearchlightAction; /** Your picture (a URL or a data URI). Defaults to the painted deep-sea scene. */ image?: string; /** What the picture shows, for screen readers. */ alt?: string; /** Where the light comes from, as a point in the picture. */ lamp?: SearchlightPoint; /** The lamp's lens radius as a share of the picture's width. */ lampSize?: number; /** Where the beam rests and centres its sweep. */ rest?: SearchlightPoint; /** What stays in view when the picture is cropped to the box. */ focus?: SearchlightPoint; /** Spots the beam can find, each with its label. */ finds?: SearchlightFind[]; /** The title's element. */ as?: "h1" | "h2"; className?: string;}const DEFAULT_LAMP: SearchlightPoint = { x: 0.709, y: 0.173 };const DEFAULT_REST: SearchlightPoint = { x: 0.4, y: 0.76 };const DEFAULT_FOCUS: SearchlightPoint = { x: 0.62, y: 0.55 };const NO_FINDS: SearchlightFind[] = [];const mix = (color: string, amount: number, into = "transparent") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;const ON = mix("var(--primary)", 6, "white");const STAGE: React.CSSProperties = { backgroundColor: mix("var(--primary)", 14, "black"), boxShadow: `0 0 0 1px ${mix("var(--primary)", 30, "black")}, inset 0 1px 0 ${mix(ON, 16)}`, color: ON,};// The one lit action: a plate of the light itself, with a 1px top edge.const PRIMARY: React.CSSProperties = { backgroundColor: ON, color: mix("var(--primary)", 40, "black"), boxShadow: `inset 0 -1px 0 ${mix("var(--primary)", 22)}`,};const SECONDARY: React.CSSProperties = { boxShadow: `inset 0 0 0 1px ${mix(ON, 30)}`, color: ON };const TAG: React.CSSProperties = { backgroundColor: mix(mix("var(--primary)", 30, "black"), 88), boxShadow: `inset 0 0 0 1px ${mix(ON, 26)}`, color: ON,};const SPREAD = 0.27;const SWEEP = 0.62;const PERIOD = 12;const MIN_ANGLE = 0.12 * Math.PI;const MAX_ANGLE = 1.22 * Math.PI;/** An angle in screen space (y down), turned into the lamp's working range. */function aim(dx: number, dy: number) { let a = Math.atan2(dy, dx); if (a < 0) a += Math.PI * 2; if (a > MAX_ANGLE) a = a > 1.62 * Math.PI ? MIN_ANGLE : MAX_ANGLE; return Math.max(MIN_ANGLE, a);}/** The switch-on: two short flickers, then steady. */const switchOn = (t: number) => (t < 0.12 ? 0 : t < 0.2 ? 0.9 : t < 0.32 ? 0.15 : t < 0.42 ? 1 : t < 0.5 ? 0.35 : Math.min(1, 0.6 + (t - 0.5) * 1.2));function themeTones(el: HTMLElement): [Rgb, Rgb] { const primary = readColor(getComputedStyle(el).getPropertyValue("--primary").trim() || "#305dde"); const deep = primary.map((v, i) => v * 0.1 + [0.012, 0.018, 0.034][i]) as Rgb; const tint = primary.map((v, i) => v * 0.42 + [0.03, 0.045, 0.07][i]) as Rgb; return [deep, tint];}export function SearchlightHero({ title, description, eyebrow, primary, secondary, image = SEARCHLIGHT_ART, alt = "A painted deep-sea scene: a wreck on a coral reef, lit by a submersible's searchlight", lamp = DEFAULT_LAMP, lampSize = 0.011, rest = DEFAULT_REST, focus = DEFAULT_FOCUS, finds = NO_FINDS, as: Heading = "h1", className = "",}: SearchlightHeroProps) { const reduced = useInteractionReducedMotion(); const stageRef = React.useRef<HTMLDivElement>(null); const canvasRef = React.useRef<HTMLCanvasElement>(null); const baseRef = React.useRef<HTMLImageElement>(null); const fallbackRef = React.useRef<HTMLImageElement>(null); const copyRef = React.useRef<HTMLDivElement>(null); const wordsRef = React.useRef<(HTMLSpanElement | null)[]>([]); const findsRef = React.useRef<(HTMLSpanElement | null)[]>([]); const words = React.useMemo(() => title.split(/\s+/).filter(Boolean), [title]); React.useEffect(() => { const stage = stageRef.current; const canvas = canvasRef.current; if (!stage || !canvas) return; let disposed = false; let light: Searchlight | null = null; let raf = 0; let visible = false; let layout: Layout | null = null; let wordPts: [number, number][] = []; let findPts: ([number, number] | null)[] = []; const litWords: boolean[] = []; const seen: number[] = []; // The beam: an angle on a spring towards the sweep or the pointer. const restAngle = { value: 0 }; const beam = { angle: 0, vel: 0, target: 0, pointer: false, lastPointer: 0, start: 0, last: 0, sweep0: 0 }; const img = new Image(); img.decoding = "async"; // A picture from another origin can only become a texture with CORS. if (!image.startsWith("data:")) img.crossOrigin = "anonymous"; img.src = image; const measure = () => { const box = stage.getBoundingClientRect(); const w = Math.max(1, box.width); const h = Math.max(1, box.height); const dpr = Math.min(window.devicePixelRatio || 1, 1.5); const crop = cover(w, h, img.naturalWidth || 16, img.naturalHeight || 9, [focus.x, focus.y]); const lampPx = onBox([lamp.x, lamp.y], crop, w, h); const restPx = onBox([rest.x, rest.y], crop, w, h); restAngle.value = aim(restPx[0] - lampPx[0], restPx[1] - lampPx[1]); const c = copyRef.current?.getBoundingClientRect(); const copy: Layout["copy"] = c ? [c.left - box.left, c.top - box.top, c.right - box.left, c.bottom - box.top] : [0, 0, 0, 0]; layout = { width: Math.round(w * dpr), height: Math.round(h * dpr), dpr, crop, lamp: lampPx, lens: Math.max(3, (lampSize / crop[2]) * w), reach: Math.hypot(w, h) * 0.6, copy }; light?.layout(layout); wordPts = wordsRef.current.map((el) => { if (!el) return [-1e4, -1e4]; const r = el.getBoundingClientRect(); return [r.left + r.width / 2 - box.left, r.top + r.height / 2 - box.top]; }); // A find shows only where it's in the picture's crop and clear of the copy. findPts = finds.map((f, i) => { const p = onBox([f.x, f.y], crop, w, h); const el = findsRef.current[i]; const overCopy = p[0] > copy[0] - 24 && p[0] < copy[2] + 24 && p[1] > copy[1] - 12 && p[1] < copy[3] + 40; const inside = p[0] > 16 && p[0] < w - 16 && p[1] > 40 && p[1] < h - 12 && !overCopy; if (el) { el.style.transform = `translate(${p[0].toFixed(1)}px, ${p[1].toFixed(1)}px)`; el.style.display = inside ? "" : "none"; } return inside ? p : null; }); // The first-paint picture is cropped exactly as the canvas will be, so nothing shifts when it fades in. const position = `${(crop[0] / (1 - crop[2] || 1)) * 100}% ${(crop[1] / (1 - crop[3] || 1)) * 100}%`; if (baseRef.current) baseRef.current.style.objectPosition = position; // Without WebGL, the lit copy of the picture shows through a still wedge. const lit = fallbackRef.current; if (lit && !light) { const a = restAngle.value; const far = Math.hypot(w, h) * 1.2; const p1 = [lampPx[0] + Math.cos(a - SPREAD) * far, lampPx[1] + Math.sin(a - SPREAD) * far]; const p2 = [lampPx[0] + Math.cos(a + SPREAD) * far, lampPx[1] + Math.sin(a + SPREAD) * far]; lit.style.clipPath = `polygon(${lampPx[0]}px ${lampPx[1]}px, ${p1[0]}px ${p1[1]}px, ${p2[0]}px ${p2[1]}px)`; lit.style.objectPosition = position; } }; // Which words and finds the beam is on; DOM writes only when something changes. const reveal = (angle: number, now: number) => { if (!layout) return; const [lx, ly] = layout.lamp; const inBeam = (p: [number, number], slack: number) => { const a = aim(p[0] - lx, p[1] - ly); return Math.abs(a - angle) < SPREAD * slack && Math.hypot(p[0] - lx, p[1] - ly) < layout!.reach * 1.4; }; wordPts.forEach((p, i) => { const on = inBeam(p, 1.05); if (on !== !!litWords[i]) { litWords[i] = on; wordsRef.current[i]?.classList.toggle("is-lit", on); } }); findPts.forEach((p, i) => { if (!p) return; const on = inBeam(p, 0.85); if (on) seen[i] = now; const show = on || now - (seen[i] ?? -1e9) < 1400; const el = findsRef.current[i]; if (el && el.classList.contains("is-found") !== show) el.classList.toggle("is-found", show); }); }; const frame = (now: number) => { raf = 0; if (!light || !visible || disposed) return; const dt = Math.min(1 / 30, (now - (beam.last || now)) / 1000); beam.last = now; const t = (now - beam.start) / 1000; if (beam.pointer && now - beam.lastPointer > 2500) { beam.pointer = false; beam.sweep0 = t - (PERIOD / (2 * Math.PI)) * Math.asin(Math.max(-1, Math.min(1, (beam.angle - restAngle.value) / SWEEP))); } if (!beam.pointer) beam.target = restAngle.value + SWEEP * Math.sin(((t - beam.sweep0) / PERIOD) * Math.PI * 2); const omega = beam.pointer ? 7 : 3; beam.vel += (omega * omega * (beam.target - beam.angle) - 2 * omega * beam.vel) * dt; beam.angle += beam.vel * dt; light.draw({ angle: beam.angle, spread: SPREAD, time: t, on: switchOn(t) }); reveal(beam.angle, now); raf = requestAnimationFrame(frame); }; const run = () => { if (!raf && visible && light && !reduced) raf = requestAnimationFrame(frame); }; const start = () => { if (disposed) return; try { light = createSearchlight(canvas, img); } catch { light = null; } measure(); if (!light) { stage.dataset.fallback = ""; reveal(restAngle.value, performance.now()); return; } light.colors(...themeTones(stage)); beam.angle = beam.target = restAngle.value; stage.dataset.ready = ""; if (reduced) { light.draw({ angle: restAngle.value, spread: SPREAD, time: 0, on: 1 }); reveal(restAngle.value, performance.now()); return; } beam.start = performance.now(); run(); }; img.decode().then(start, start); const ro = new ResizeObserver(() => { measure(); if (reduced && light) light.draw({ angle: restAngle.value, spread: SPREAD, time: 0, on: 1 }); }); ro.observe(stage); const io = new IntersectionObserver(([entry]) => { visible = entry.isIntersecting; run(); }); io.observe(stage); // A theme switch changes --primary: re-grade the night. const mo = new MutationObserver(() => { if (!light) return; light.colors(...themeTones(stage)); if (reduced) light.draw({ angle: restAngle.value, spread: SPREAD, time: 0, on: 1 }); }); mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] }); document.fonts?.ready.then(() => !disposed && measure()); const onMove = (e: PointerEvent) => { if (reduced || !layout || (e.pointerType === "touch" && e.buttons === 0)) return; const box = stage.getBoundingClientRect(); beam.target = aim(e.clientX - box.left - layout.lamp[0], e.clientY - box.top - layout.lamp[1]); beam.pointer = true; beam.lastPointer = e.timeStamp; }; stage.addEventListener("pointermove", onMove); stage.addEventListener("pointerdown", onMove); return () => { disposed = true; cancelAnimationFrame(raf); ro.disconnect(); io.disconnect(); mo.disconnect(); stage.removeEventListener("pointermove", onMove); stage.removeEventListener("pointerdown", onMove); light?.dispose(); delete stage.dataset.ready; }; }, [image, lamp.x, lamp.y, lampSize, rest.x, rest.y, focus.x, focus.y, finds, reduced]); const objectPosition = `${focus.x * 100}% ${focus.y * 100}%`; return ( <section className={`w-full max-w-[1200px] ${className}`}> {/* Its natural width where the parent sizes to its content, without forcing it on narrow screens. */} <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 1200px)" }} /> <div className="@container w-full"> <div ref={stageRef} className="group/stage relative isolate grid min-h-[780px] touch-pan-y overflow-clip rounded-[28px] @[640px]:aspect-[16/10] @[640px]:min-h-[520px] @[960px]:aspect-[16/9]" style={STAGE} > <div role="img" aria-label={alt} className="absolute inset-0"> {/* First paint, and the picture if WebGL isn't there: the night, and a still wedge of light. */} {/* eslint-disable-next-line @next/next/no-img-element */} <img ref={baseRef} src={image} alt="" draggable={false} className="absolute inset-0 size-full object-cover" style={{ objectPosition, filter: "brightness(0.3) saturate(0.55)" }} /> {/* eslint-disable-next-line @next/next/no-img-element */} <img ref={fallbackRef} src={image} alt="" draggable={false} className="absolute inset-0 hidden size-full object-cover group-data-[fallback]/stage:block" /> <canvas ref={canvasRef} aria-hidden="true" className="absolute inset-0 size-full opacity-0 transition-opacity duration-500 group-data-[ready]/stage:opacity-100" /> </div> {/* What the beam finds: a ring on the spot and its label above it. */} <div aria-hidden="true" className="pointer-events-none absolute inset-0"> {finds.map((f, i) => ( <span key={`${f.label}-${i}`} ref={(el) => void (findsRef.current[i] = el)} className="group/find absolute left-0 top-0 [&.is-found]:z-[1]"> <span className="absolute left-0 top-0 size-3 -translate-x-1/2 -translate-y-1/2 scale-50 rounded-full opacity-0 transition-[opacity,scale] duration-300 group-[.is-found]/find:scale-100 group-[.is-found]/find:opacity-100" style={{ boxShadow: `0 0 0 1px ${ON}, inset 0 0 0 1px ${mix("var(--primary)", 40, "black")}`, transitionTimingFunction: EASE_OUT }} /> <span className="absolute bottom-3 left-0 flex -translate-x-1/2 translate-y-1.5 items-center gap-1.5 whitespace-nowrap rounded-full py-1 pl-2 pr-2.5 text-[12px] font-medium leading-4 opacity-0 blur-[3px] transition-[opacity,translate,filter] duration-300 group-[.is-found]/find:translate-y-0 group-[.is-found]/find:opacity-100 group-[.is-found]/find:blur-[0px]" style={{ ...TAG, transitionTimingFunction: EASE_OUT }} > <span className="size-1.5 rounded-full" style={{ backgroundColor: ON }} /> {f.label} </span> </span> ))} </div> <div ref={copyRef} className="pointer-events-none relative z-[2] flex max-w-[34rem] flex-col items-start gap-4 self-start p-6 pt-8 @[640px]:self-center @[640px]:p-12 @[960px]:p-16"> {eyebrow && ( <p className="flex items-center gap-2 text-[13px] font-medium" style={{ color: mix(ON, 72) }}> <span aria-hidden="true" className="size-1.5 rounded-full" style={{ backgroundColor: ON }} /> {eyebrow} </p> )} <Heading className="text-balance text-[34px] font-semibold leading-[1.04] tracking-[-0.035em] @[640px]:text-[48px] @[960px]:text-[60px]"> <span className="sr-only">{title}</span> <span aria-hidden="true"> {words.map((w, i) => ( <React.Fragment key={i}> <span ref={(el) => void (wordsRef.current[i] = el)} className="transition-colors duration-300 [&.is-lit]:!text-[var(--lit)]" style={{ color: mix(ON, reduced ? 100 : 66), ["--lit" as string]: ON }} > {w} </span> {i < words.length - 1 ? " " : null} </React.Fragment> ))} </span> </Heading> {description && ( <p className="max-w-[28rem] text-[15px] leading-6 @[640px]:text-[16.5px] @[640px]:leading-7" style={{ color: mix(ON, 74) }}> {description} </p> )} {(primary || secondary) && ( <div className="pointer-events-auto mt-2 flex flex-wrap gap-2.5"> {primary && ( <a href={primary.href} className={`inline-flex h-12 cursor-pointer items-center gap-2 rounded-full px-5 text-[15px] font-semibold ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} style={PRIMARY}> {primary.label} <ArrowRight aria-hidden="true" className="size-4" /> </a> )} {secondary && ( <a href={secondary.href} className={`inline-flex h-12 cursor-pointer items-center rounded-full px-5 text-[15px] font-medium ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} style={SECONDARY}> {secondary.label} </a> )} </div> )} </div> </div> </div> </section> );}