From 5f86e2273011bfd2582394f5d5f9a15c0df5e14f Mon Sep 17 00:00:00 2001 From: zahid6999 Date: Sun, 15 Nov 2026 19:07:49 +0600 Subject: [PATCH] feat(registry): add ink stroke button A teal button with lime ink that flows under the cursor, simulated as a fluid in WebGL 2. Falls back to a CSS colour swap under reduced motion or without WebGL. --- .../content/1.component/ink-stroke-button.mdx | 90 +++ .../docs/public/r/ink-stroke-button-demo.json | 17 + apps/docs/public/r/ink-stroke-button.json | 24 + apps/docs/public/r/registry.json | 24 + apps/docs/registry/__index__.generated.tsx | 1 + apps/docs/registry/__sources__.generated.ts | 12 + .../docs/registry/demos/ink-stroke-button.tsx | 13 + apps/docs/registry/registry-ui.ts | 33 + .../registry/tweenui/ink-stroke-button.tsx | 716 ++++++++++++++++++ apps/docs/tests/ink-stroke-button.test.tsx | 72 ++ 10 files changed, 1002 insertions(+) create mode 100644 apps/docs/content/1.component/ink-stroke-button.mdx create mode 100644 apps/docs/public/r/ink-stroke-button-demo.json create mode 100644 apps/docs/public/r/ink-stroke-button.json create mode 100644 apps/docs/registry/demos/ink-stroke-button.tsx create mode 100644 apps/docs/registry/tweenui/ink-stroke-button.tsx create mode 100644 apps/docs/tests/ink-stroke-button.test.tsx diff --git a/apps/docs/content/1.component/ink-stroke-button.mdx b/apps/docs/content/1.component/ink-stroke-button.mdx new file mode 100644 index 0000000..6a563d1 --- /dev/null +++ b/apps/docs/content/1.component/ink-stroke-button.mdx @@ -0,0 +1,90 @@ +--- +title: Ink Stroke Button +description: A teal button with lime ink that flows under the cursor, simulated as a fluid in WebGL. +icon: brush +--- + +A teal call-to-action with **lime ink that flows under your cursor**. The ink +is a small fluid simulation in WebGL. **The moment the cursor crosses an +edge**, from any side, a pool of ink floods about a quarter of the button +there, holds for a beat and goes. Through a side it fills a full-height +band; through the top or bottom it spreads from where the cursor crossed. +Move and the ink is **pushed along the way you go**; stop and it **curls aside** as teal washes back in +behind it, then fades in about a second. Hold still and nothing new is added. +The label is part of the picture, so it reads lime on teal and **flips to teal +under the ink**. Pressing it scales the button down to 97%, the same press as +the other Tween UI buttons. + +::component-preview{name="ink-stroke-button"} +:: + +## Installation + +::tabs +:::tabs-item{label="CLI" icon="i-lucide-terminal"} + +::install-tabs{item="ink-stroke-button"} +:: + +::: +:::tabs-item{label="Manual" icon="i-lucide-clipboard"} + +::component-source{name="ink-stroke-button"} +:: + +::: +:: + +## Usage + +::tabs +:::tabs-item{label="React" icon="i-lucide-atom"} + +```tsx [components/start-project.tsx] +import InkStrokeButton from '@/components/tweenui/ink-stroke-button'; + +export default function StartProject() { + return {}}>Start a project; +} +``` + +::: +:: + +The canvas matches the button and is rebuilt when its size changes, so a +longer label or a full-width button works. The label is drawn with the +button's own font once fonts have loaded. The pointer is followed across the +page, but the simulation only runs while it is near the button and stops once +the ink has faded, so an idle button costs nothing. It needs WebGL 2. + +::note +Each button holds one WebGL context, and browsers allow about 16 per page. A +context is only created once the button scrolls into view, which is plenty for +navbar and hero buttons; don't use it for long lists of buttons. +:: + +## Props + +| Prop | Type | Default | Description | +| ----------- | -------- | ---------- | --------------------------------------------- | +| `children` | `string` | — | The label, drawn into the canvas on one line. | +| `type` | `string` | `'button'` | The native button type. | +| `className` | `string` | — | Extra classes for the `\n );\n};\n\nexport default InkStrokeButton;\n" + } + ], + "docs": "Docs, props and examples: https://tween-ui.vercel.app/component/ink-stroke-button" +} \ No newline at end of file diff --git a/apps/docs/public/r/registry.json b/apps/docs/public/r/registry.json index 079ea59..5ed8101 100644 --- a/apps/docs/public/r/registry.json +++ b/apps/docs/public/r/registry.json @@ -655,6 +655,30 @@ } ] }, + { + "name": "ink-stroke-button", + "type": "registry:ui", + "title": "Ink Stroke Button", + "description": "A teal button with lime ink that flows under the cursor. The ink is a small fluid simulation in WebGL: a pool floods in from whichever edge the cursor crosses, the ink is pushed along the way you move, curls aside when you stop and fades back to teal in about a second. The label flips colour under the ink.", + "files": [ + { + "path": "components/tweenui/ink-stroke-button.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "ink-stroke-button-demo", + "type": "registry:example", + "title": "Ink Stroke Button Demo", + "description": "Usage examples for Ink Stroke Button.", + "files": [ + { + "path": "examples/ink-stroke-button-demo.tsx", + "type": "registry:example" + } + ] + }, { "name": "pricing-plan-switch", "type": "registry:block", diff --git a/apps/docs/registry/__index__.generated.tsx b/apps/docs/registry/__index__.generated.tsx index c1139d3..0747202 100644 --- a/apps/docs/registry/__index__.generated.tsx +++ b/apps/docs/registry/__index__.generated.tsx @@ -38,6 +38,7 @@ export const demos: Record = { 'spring-tooltip:default': dynamic(() => import('./demos/spring-tooltip')), 'pixel-fill-button:default': dynamic(() => import('./demos/pixel-fill-button')), 'morphing-search:default': dynamic(() => import('./demos/morphing-search')), + 'ink-stroke-button:default': dynamic(() => import('./demos/ink-stroke-button')), 'pricing-plan-switch:default': dynamic(() => import('./demos/pricing-plan-switch')), 'process-card-reveal:default': dynamic(() => import('./demos/process-card-reveal')), 'process-sticky-steps:default': dynamic(() => import('./demos/process-sticky-steps')), diff --git a/apps/docs/registry/__sources__.generated.ts b/apps/docs/registry/__sources__.generated.ts index eec69ff..ebdc6d0 100644 --- a/apps/docs/registry/__sources__.generated.ts +++ b/apps/docs/registry/__sources__.generated.ts @@ -169,6 +169,12 @@ export const usage: Record = { "codeHtml": "
import MorphingSearch from '@/components/tweenui/morphing-search';\n\nexport default function Example() {\n  return (\n    <MorphingSearch\n      placeholder=\"Search Tween UI\"\n      label=\"Search Tween UI components\"\n      defaultChips={['Buttons']}\n      defaultRecents={['Spring Tooltip', 'Navbar Gooey Bloom']}\n      maxChips={4}\n      suggestions={['Pixel Fill Button', 'Glow Button', 'Sliding Tabs', 'Morphing Text']}\n    />\n  );\n}
" } }, + "ink-stroke-button": { + "react": { + "code": "import InkStrokeButton from '@/components/tweenui/ink-stroke-button';\n\nexport default function Example() {\n return {}}>Start a project;\n}", + "codeHtml": "
import InkStrokeButton from '@/components/tweenui/ink-stroke-button';\n\nexport default function Example() {\n  return <InkStrokeButton onClick={() => {}}>Start a project</InkStrokeButton>;\n}
" + } + }, "pricing-plan-switch": { "react": { "code": "import PricingPlanSwitch from '@/components/tweenui/pricing-plan-switch';\n\nexport default function Example() {\n return ;\n}", @@ -556,6 +562,12 @@ export const manual: Record = { "codeHtml": "
'use client';\n\nimport {\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type FocusEvent,\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport gsap from 'gsap';\nimport { CustomEase } from 'gsap/CustomEase';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(CustomEase);\n\nconst TEAL = '#045f64';\nconst LIME = '#c6f56f';\nconst INK = '#071d1b';\nconst CHIP_HEIGHT = 36;\nconst CHIP_INSET = 12;\nconst FLIGHT = 0.62;\nconst LIFT = 12;\nconst BAR_HEIGHT = 56;\nconst PANEL_GAP = 12;\nconst SEED = { width: 120, height: 40, bottom: 8, borderRadius: 20 };\nconst SEED_STYLE = { ...SEED };\n\ntype Kind = 'typed' | 'recent' | 'suggestion';\n\ninterface Option {\n  key: string;\n  term: string;\n  kind: Kind;\n}\n\ninterface Flight {\n  term: string;\n  to: 'bar' | 'list';\n  left: number;\n  top: number;\n  width: number;\n  height: number;\n  fontSize: string;\n}\n\nexport interface MorphingSearchProps {\n  suggestions?: readonly string[];\n  chips?: string[];\n  defaultChips?: string[];\n  onChipsChange?: (chips: string[]) => void;\n  defaultRecents?: string[];\n  onRecentsChange?: (recents: string[]) => void;\n  maxRecents?: number;\n  maxSuggestions?: number;\n  maxChips?: number;\n  placeholder?: string;\n  label?: string;\n  name?: string;\n  className?: string;\n}\n\nconst prefersReducedMotion = () =>\n  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nconst sameTerm = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();\n\nconst createEases = () => {\n  CustomEase.create('search-glide', '0.32, 0.72, 0, 1');\n};\n\nconst SearchIcon = ({ className }: { className?: string }) => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" aria-hidden=\"true\" className={className}>\n    <circle cx=\"9\" cy=\"9\" r=\"5.75\" stroke=\"currentColor\" strokeWidth={1.6} />\n    <path d=\"m13.25 13.25 3.5 3.5\" stroke=\"currentColor\" strokeWidth={1.6} strokeLinecap=\"round\" />\n  </svg>\n);\n\nconst ClockIcon = () => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" aria-hidden=\"true\" className=\"size-4 shrink-0\">\n    <circle cx=\"10\" cy=\"10\" r=\"6.75\" stroke=\"currentColor\" strokeWidth={1.5} />\n    <path\n      d=\"M10 6.5V10l2.25 1.5\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n    />\n  </svg>\n);\n\nconst PlusIcon = () => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" aria-hidden=\"true\" className=\"size-4 shrink-0\">\n    <path d=\"M10 4.5v11M4.5 10h11\" stroke=\"currentColor\" strokeWidth={1.6} strokeLinecap=\"round\" />\n  </svg>\n);\n\nconst CloseIcon = () => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" aria-hidden=\"true\" className=\"size-3.5\">\n    <path d=\"m6 6 8 8M14 6l-8 8\" stroke=\"currentColor\" strokeWidth={1.8} strokeLinecap=\"round\" />\n  </svg>\n);\n\nconst Match = ({ term, query }: { term: string; query: string }) => {\n  const at = query ? term.toLowerCase().indexOf(query.toLowerCase()) : -1;\n  if (at < 0) return term;\n  return (\n    <>\n      {term.slice(0, at)}\n      <strong className=\"font-semibold text-[#045f64]\">{term.slice(at, at + query.length)}</strong>\n      {term.slice(at + query.length)}\n    </>\n  );\n};\n\nconst MorphingSearch = ({\n  suggestions = [],\n  chips: chipsProp,\n  defaultChips = [],\n  onChipsChange,\n  defaultRecents = [],\n  onRecentsChange,\n  maxRecents = 5,\n  maxSuggestions = 5,\n  maxChips,\n  placeholder = 'Search',\n  label = 'Search',\n  name,\n  className,\n}: MorphingSearchProps) => {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const chipRowRef = useRef<HTMLDivElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n  const blobRef = useRef<HTMLSpanElement>(null);\n  const markerRef = useRef<HTMLSpanElement>(null);\n  const ghostRef = useRef<HTMLSpanElement>(null);\n  const revealed = useRef<boolean | null>(null);\n  const markerShown = useRef(false);\n  const latestChips = useRef<string[]>(defaultChips);\n  const id = useId();\n  const gooId = `search-goo-${id.replace(/[^a-zA-Z0-9_-]/g, '')}`;\n  const [ownChips, setOwnChips] = useState(defaultChips);\n  const [recents, setRecents] = useState(defaultRecents);\n  const [query, setQuery] = useState('');\n  const [open, setOpen] = useState(false);\n  const [active, setActive] = useState(0);\n  const [marked, setMarked] = useState<string | null>(null);\n  const [flight, setFlight] = useState<Flight | null>(null);\n  const [landing, setLanding] = useState<string | null>(null);\n  const [leaving, setLeaving] = useState<string | null>(null);\n  const [note, setNote] = useState({ text: '', count: 0 });\n\n  const chips = chipsProp ?? ownChips;\n  const typed = query.trim();\n  const listId = `${id}-list`;\n  const hintId = `${id}-hint`;\n  const optionId = (index: number) => `${id}-option-${index}`;\n\n  useLayoutEffect(() => {\n    latestChips.current = chips;\n  });\n\n  const options = useMemo<Option[]>(() => {\n    const held = chips.filter((chip) => chip !== leaving);\n    if (!typed) {\n      return recents\n        .filter((term) => !held.some((chip) => sameTerm(chip, term)))\n        .map((term) => ({ key: `recent-${term}`, term, kind: 'recent' }));\n    }\n    const needle = typed.toLowerCase();\n    const taken = new Set([needle, ...held.map((chip) => chip.toLowerCase())]);\n    const found: Option[] = [];\n    const consider = (term: string, kind: Kind) => {\n      const key = term.toLowerCase();\n      if (taken.has(key) || !key.includes(needle)) return;\n      taken.add(key);\n      found.push({ key: `${kind}-${term}`, term, kind });\n    };\n    recents.forEach((term) => consider(term, 'recent'));\n    suggestions.forEach((term) => consider(term, 'suggestion'));\n    return [\n      { key: `typed-${typed}`, term: typed, kind: 'typed' },\n      ...found.slice(0, maxSuggestions),\n    ];\n  }, [typed, recents, suggestions, chips, leaving, maxSuggestions]);\n\n  const current = Math.min(active, Math.max(options.length - 1, 0));\n  const showPanel = open && options.length > 0;\n  const activeId = showPanel ? optionId(current) : undefined;\n\n  const announce = (text: string) => setNote((last) => ({ text, count: last.count + 1 }));\n\n  const commitChips = (next: string[]) => {\n    if (chipsProp === undefined) setOwnChips(next);\n    onChipsChange?.(next);\n  };\n\n  const commitRecents = (next: string[]) => {\n    setRecents(next);\n    onRecentsChange?.(next);\n  };\n\n  const chipElement = (term: string) =>\n    Array.from(rootRef.current?.querySelectorAll<HTMLElement>('[data-chip]') ?? []).find(\n      (element) => element.dataset.chip === term\n    );\n\n  const rowLabel = (term: string) =>\n    Array.from(panelRef.current?.querySelectorAll<HTMLElement>('[data-value]') ?? [])\n      .find((element) => element.dataset.value === term)\n      ?.querySelector<HTMLElement>('[data-term]');\n\n  const add = (term: string, source: HTMLElement | null) => {\n    const value = term.trim();\n    if (!value) return;\n    const exists = chips.some((chip) => sameTerm(chip, value));\n    if (!exists && maxChips !== undefined && chips.length >= maxChips) {\n      announce(`You can add up to ${maxChips} filters`);\n      return;\n    }\n    if (!exists) {\n      if (source && !prefersReducedMotion()) {\n        const box = source.getBoundingClientRect();\n        setFlight({\n          term: value,\n          to: 'bar',\n          left: box.left - CHIP_INSET,\n          top: box.top + (box.height - CHIP_HEIGHT) / 2,\n          width: 0,\n          height: CHIP_HEIGHT,\n          fontSize: getComputedStyle(source).fontSize,\n        });\n        setLanding(value);\n      }\n      commitChips([...chips, value]);\n      announce(`Added filter ${value}`);\n    }\n    commitRecents(\n      [value, ...recents.filter((recent) => !sameTerm(recent, value))].slice(0, maxRecents)\n    );\n    setQuery('');\n    setActive(0);\n  };\n\n  const remove = (term: string) => {\n    const finish = () => {\n      commitChips(latestChips.current.filter((chip) => chip !== term));\n      setLeaving((current) => (current === term ? null : current));\n      announce(`Removed filter ${term}`);\n    };\n    commitRecents(\n      [term, ...recents.filter((recent) => !sameTerm(recent, term))].slice(0, maxRecents)\n    );\n    const element = chipElement(term);\n    if (!element || prefersReducedMotion()) finish();\n    else {\n      const box = element.getBoundingClientRect();\n      setLeaving(term);\n      setLanding(term);\n      setFlight({\n        term,\n        to: 'list',\n        left: box.left,\n        top: box.top,\n        width: box.width,\n        height: box.height,\n        fontSize: getComputedStyle(element).fontSize,\n      });\n      gsap.to(element, {\n        width: 0,\n        paddingLeft: 0,\n        paddingRight: 0,\n        marginRight: -6,\n        opacity: 0,\n        duration: 0.3,\n        ease: 'power2.inOut',\n        onComplete: finish,\n      });\n    }\n    setMarked(null);\n    inputRef.current?.focus();\n  };\n\n  const forgetRecent = (term: string) => {\n    commitRecents(recents.filter((recent) => recent !== term));\n    announce(`Removed ${term} from recent searches`);\n  };\n\n  const moveTo = (index: number) => {\n    setActive(index);\n    document.getElementById(optionId(index))?.scrollIntoView?.({ block: 'nearest' });\n  };\n\n  const sourceFor = (index: number) => {\n    const option = options[index];\n    if (!option || option.kind === 'typed') return inputRef.current;\n    return (\n      document.getElementById(optionId(index))?.querySelector<HTMLElement>('[data-term]') ?? null\n    );\n  };\n\n  const stepMark = (direction: -1 | 1) => {\n    const at = marked === null ? chips.length : chips.indexOf(marked);\n    const next = at + direction;\n    setMarked(next >= chips.length ? null : (chips[Math.max(next, 0)] ?? null));\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n    if (event.nativeEvent.isComposing) return;\n    const field = event.currentTarget;\n    const atStart = field.selectionStart === 0 && field.selectionEnd === 0;\n\n    if (marked !== null) {\n      if (event.key === 'Backspace' || event.key === 'Delete') {\n        event.preventDefault();\n        remove(marked);\n        return;\n      }\n      if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {\n        event.preventDefault();\n        stepMark(event.key === 'ArrowLeft' ? -1 : 1);\n        return;\n      }\n      if (event.key === 'Escape') {\n        event.preventDefault();\n        setMarked(null);\n        return;\n      }\n      setMarked(null);\n    }\n\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      if (query) setQuery('');\n      else setOpen(false);\n    } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n      event.preventDefault();\n      if (!open) setOpen(true);\n      else if (options.length) {\n        const step = event.key === 'ArrowDown' ? 1 : options.length - 1;\n        moveTo((current + step) % options.length);\n      }\n    } else if (event.key === 'Enter') {\n      const option = options[current];\n      if (!showPanel || !option) return;\n      event.preventDefault();\n      add(option.term, sourceFor(current));\n    } else if (event.key === 'Delete' && showPanel && options[current]?.kind === 'recent') {\n      event.preventDefault();\n      const option = options[current];\n      if (option) forgetRecent(option.term);\n    } else if (\n      (event.key === 'Backspace' || event.key === 'ArrowLeft') &&\n      atStart &&\n      chips.length\n    ) {\n      event.preventDefault();\n      const last = chips[chips.length - 1] ?? null;\n      setMarked(last);\n      if (last) announce(`${last} selected. Press Backspace again to remove it.`);\n    }\n  };\n\n  const onBarPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (event.target instanceof Element && event.target.closest('button, input')) return;\n    event.preventDefault();\n    inputRef.current?.focus();\n    setOpen(true);\n  };\n\n  const onBlur = (event: FocusEvent<HTMLDivElement>) => {\n    const next = event.relatedTarget;\n    if (!(next instanceof Node) || rootRef.current?.contains(next)) return;\n    setOpen(false);\n    setMarked(null);\n  };\n\n  useEffect(() => {\n    if (!open) return;\n    const onPointerDown = (event: PointerEvent) => {\n      if (event.target instanceof Node && rootRef.current?.contains(event.target)) return;\n      setOpen(false);\n      setMarked(null);\n    };\n    document.addEventListener('pointerdown', onPointerDown, true);\n    return () => document.removeEventListener('pointerdown', onPointerDown, true);\n  }, [open]);\n\n  useLayoutEffect(() => {\n    if (!flight) return;\n    const root = rootRef.current;\n    const ghost = ghostRef.current;\n    const toBar = flight.to === 'bar';\n    const target = toBar ? chipElement(flight.term) : rowLabel(flight.term);\n    if (!root || !ghost || !target) {\n      setFlight(null);\n      setLanding(null);\n      return;\n    }\n    createEases();\n    const row = chipRowRef.current;\n    if (toBar && row) row.scrollLeft = row.scrollWidth;\n\n    const rootBox = root.getBoundingClientRect();\n    const goal = target.getBoundingClientRect();\n    const fromX = flight.left - rootBox.left;\n    const fromY = flight.top - rootBox.top;\n    const toX = goal.left - rootBox.left - (toBar ? 0 : CHIP_INSET);\n    const toY = goal.top - rootBox.top + (toBar ? 0 : (goal.height - CHIP_HEIGHT) / 2);\n\n    gsap.set(ghost, { x: fromX, y: fromY, fontSize: flight.fontSize, opacity: 1 });\n    const natural = ghost.offsetWidth;\n    gsap.set(ghost, {\n      width: toBar ? natural : flight.width,\n      color: toBar ? INK : LIME,\n      backgroundColor: toBar ? 'rgba(198, 245, 111, 0)' : TEAL,\n    });\n\n    const timeline = gsap.timeline({\n      onComplete: () => {\n        setLanding(null);\n        setFlight(null);\n      },\n    });\n    timeline\n      .to(\n        ghost,\n        {\n          x: toX,\n          width: toBar ? goal.width : natural,\n          fontSize: 14,\n          duration: FLIGHT,\n          ease: 'search-glide',\n        },\n        0\n      )\n      .to(ghost, { y: Math.min(fromY, toY) - LIFT, duration: FLIGHT * 0.4, ease: 'power2.out' }, 0)\n      .to(ghost, { y: toY, duration: FLIGHT * 0.6, ease: 'power2.inOut' }, FLIGHT * 0.4)\n      .to(\n        ghost,\n        { backgroundColor: LIME, color: INK, duration: FLIGHT * 0.35, ease: 'power1.out' },\n        0\n      )\n      .to(\n        ghost,\n        toBar\n          ? { backgroundColor: TEAL, color: LIME, duration: FLIGHT * 0.5, ease: 'power1.inOut' }\n          : {\n              backgroundColor: 'rgba(198, 245, 111, 0)',\n              duration: FLIGHT * 0.5,\n              ease: 'power1.inOut',\n            },\n        FLIGHT * 0.45\n      );\n    return () => {\n      timeline.kill();\n    };\n  }, [flight]);\n\n  useLayoutEffect(() => {\n    const panel = panelRef.current;\n    const blob = blobRef.current;\n    if (!panel || !blob) return;\n    createEases();\n    const first = revealed.current === null;\n    const changed = revealed.current !== showPanel;\n    revealed.current = showPanel;\n\n    const settled = () => ({\n      width: panel.offsetWidth,\n      height: panel.offsetHeight,\n      bottom: BAR_HEIGHT + PANEL_GAP,\n      borderRadius: 28,\n    });\n\n    if (!changed && gsap.isTweening(blob)) return;\n    if (!changed || first || prefersReducedMotion()) {\n      gsap.killTweensOf([blob, panel]);\n      gsap.set(blob, showPanel ? settled() : { ...SEED });\n      gsap.set(panel, { opacity: showPanel ? 1 : 0, y: 0 });\n      return;\n    }\n\n    if (showPanel) {\n      gsap.to(blob, {\n        ...settled(),\n        duration: 0.64,\n        ease: 'search-glide',\n        overwrite: true,\n        onComplete: () => {\n          gsap.to(blob, { ...settled(), duration: 0.2, ease: 'power2.out' });\n        },\n      });\n      gsap.fromTo(\n        panel,\n        { opacity: 0, y: 10 },\n        { opacity: 1, y: 0, duration: 0.3, delay: 0.24, ease: 'power2.out', overwrite: true }\n      );\n    } else {\n      gsap.to(panel, { opacity: 0, duration: 0.12, ease: 'power1.out', overwrite: true });\n      gsap.to(blob, { ...SEED, duration: 0.44, ease: 'power3.inOut', overwrite: true });\n    }\n  }, [showPanel]);\n\n  useEffect(() => {\n    const panel = panelRef.current;\n    const blob = blobRef.current;\n    if (!showPanel || !panel || !blob) return;\n    const observer = new ResizeObserver(() => {\n      if (gsap.isTweening(blob)) return;\n      gsap.to(blob, {\n        width: panel.offsetWidth,\n        height: panel.offsetHeight,\n        bottom: BAR_HEIGHT + PANEL_GAP,\n        borderRadius: 28,\n        duration: prefersReducedMotion() ? 0 : 0.3,\n        ease: 'search-glide',\n        overwrite: true,\n      });\n    });\n    observer.observe(panel);\n    return () => observer.disconnect();\n  }, [showPanel]);\n\n  useLayoutEffect(() => {\n    const marker = markerRef.current;\n    if (!marker) return;\n    const row = activeId ? document.getElementById(activeId) : null;\n    if (!row) {\n      gsap.killTweensOf(marker);\n      gsap.set(marker, { opacity: 0 });\n      markerShown.current = false;\n      return;\n    }\n    gsap.set(marker, { height: row.offsetHeight, opacity: 1 });\n    if (markerShown.current && !prefersReducedMotion()) {\n      gsap.to(marker, { y: row.offsetTop, duration: 0.3, ease: 'power3.out', overwrite: true });\n    } else {\n      gsap.killTweensOf(marker);\n      gsap.set(marker, { y: row.offsetTop });\n    }\n    markerShown.current = true;\n  }, [activeId, options]);\n\n  return (\n    <div ref={rootRef} onBlur={onBlur} className={cn('relative w-full max-w-xl', className)}>\n      <svg aria-hidden=\"true\" className=\"pointer-events-none absolute size-0\">\n        <defs>\n          <filter\n            id={gooId}\n            x=\"-20%\"\n            y=\"-20%\"\n            width=\"140%\"\n            height=\"140%\"\n            colorInterpolationFilters=\"sRGB\"\n          >\n            <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"7\" result=\"blur\" />\n            <feColorMatrix\n              in=\"blur\"\n              mode=\"matrix\"\n              values=\"1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 22 -9\"\n              result=\"goo\"\n            />\n            <feComposite in=\"SourceGraphic\" in2=\"goo\" operator=\"atop\" />\n          </filter>\n        </defs>\n      </svg>\n      <div\n        aria-hidden=\"true\"\n        data-goo\n        className=\"pointer-events-none absolute inset-x-0 bottom-0 h-[460px]\"\n        style={{\n          filter: `url(#${gooId}) drop-shadow(0 6px 12px rgba(4, 95, 100, 0.08))`,\n        }}\n      >\n        <span className=\"absolute inset-x-0 bottom-0 h-14 rounded-full bg-white\" />\n        <span ref={blobRef} style={SEED_STYLE} className=\"absolute inset-x-0 mx-auto bg-white\" />\n      </div>\n      <div\n        ref={panelRef}\n        inert={!showPanel}\n        aria-hidden={!showPanel}\n        className=\"absolute inset-x-0 bottom-full z-10 mb-3 p-2 opacity-0\"\n      >\n        <div className=\"flex h-9 items-center justify-between px-3\">\n          <span className=\"text-[11px] font-medium tracking-[0.08em] text-[#045f64]/60 uppercase\">\n            {typed ? 'Suggestions' : 'Recent'}\n          </span>\n          {!typed && options.length > 0 && (\n            <button\n              type=\"button\"\n              onClick={() => {\n                commitRecents([]);\n                announce('Cleared recent searches');\n                inputRef.current?.focus();\n              }}\n              className=\"cursor-pointer rounded-md border-0 bg-transparent px-1.5 py-0.5 text-xs text-[#045f64]/60 transition-colors outline-none hover:text-[#045f64] focus-visible:ring-2 focus-visible:ring-[#045f64] motion-reduce:transition-none\"\n            >\n              Clear\n            </button>\n          )}\n        </div>\n        <div className=\"relative max-h-72 [scrollbar-width:thin] overflow-y-auto overscroll-contain\">\n          <span\n            ref={markerRef}\n            aria-hidden=\"true\"\n            // Panel radius (28) minus its padding (8), so the corners stay concentric.\n            className=\"pointer-events-none absolute inset-x-0 top-0 rounded-[20px] bg-[#045f64]/[0.08] opacity-0\"\n          />\n          <div id={listId} role=\"listbox\" aria-label={typed ? 'Suggestions' : 'Recent searches'}>\n            {options.map((option, index) => (\n              <div\n                key={option.key}\n                id={optionId(index)}\n                data-value={option.term}\n                role=\"option\"\n                aria-selected={index === current}\n                onPointerDown={(event) => event.preventDefault()}\n                onPointerMove={() => index !== current && setActive(index)}\n                onClick={() => add(option.term, sourceFor(index))}\n                className=\"relative flex h-11 cursor-pointer items-center gap-3 rounded-[20px] px-3 text-sm text-[#071d1b]\"\n              >\n                <span className=\"flex text-[#045f64]/60\">\n                  {option.kind === 'recent' ? (\n                    <ClockIcon />\n                  ) : option.kind === 'typed' ? (\n                    <PlusIcon />\n                  ) : (\n                    <SearchIcon className=\"size-4 shrink-0\" />\n                  )}\n                </span>\n                <span\n                  data-term\n                  className={cn(\n                    'min-w-0 flex-1 truncate',\n                    flight?.to === 'list' && landing === option.term && 'opacity-0'\n                  )}\n                >\n                  {option.kind === 'typed' ? (\n                    option.term\n                  ) : (\n                    <Match term={option.term} query={typed} />\n                  )}\n                </span>\n              </div>\n            ))}\n          </div>\n        </div>\n      </div>\n\n      <div\n        onPointerDown={onBarPointerDown}\n        className=\"relative z-20 flex h-14 cursor-text items-center gap-2 rounded-full border border-[#045f64]/15 bg-white/80 ps-4 pe-4 backdrop-blur-xl transition-[border-color,box-shadow] duration-200 ease-out focus-within:border-[#045f64]/35 focus-within:shadow-[0_0_0_4px_rgba(4,95,100,0.1)] motion-reduce:transition-none\"\n      >\n        <span className=\"flex shrink-0 text-[#045f64]\">\n          <SearchIcon className=\"size-5\" />\n        </span>\n        <div\n          ref={chipRowRef}\n          className=\"flex min-w-0 shrink [scrollbar-width:none] items-center gap-1.5 overflow-x-auto\"\n        >\n          {chips.map((chip) => (\n            <span\n              key={chip}\n              data-chip={chip}\n              className={cn(\n                'flex h-9 shrink-0 items-center gap-1 overflow-hidden rounded-full ps-3 pe-1 text-sm whitespace-nowrap text-[#c6f56f] transition-[background-color,box-shadow] duration-150 motion-reduce:transition-none',\n                marked === chip ? 'bg-[#0f3f42] ring-2 ring-[#c6f56f] ring-inset' : 'bg-[#045f64]',\n                flight?.to === 'bar' && landing === chip && 'opacity-0'\n              )}\n            >\n              {chip}\n              <button\n                type=\"button\"\n                aria-label={`Remove filter ${chip}`}\n                onClick={() => remove(chip)}\n                className=\"grid size-7 shrink-0 cursor-pointer place-items-center rounded-full border-0 bg-transparent text-[#c6f56f]/70 transition-colors outline-none hover:bg-[#c6f56f]/15 hover:text-[#c6f56f] focus-visible:ring-2 focus-visible:ring-[#c6f56f] motion-reduce:transition-none\"\n              >\n                <CloseIcon />\n              </button>\n            </span>\n          ))}\n        </div>\n        <input\n          ref={inputRef}\n          type=\"text\"\n          role=\"combobox\"\n          aria-label={label}\n          aria-expanded={showPanel}\n          aria-controls={showPanel ? listId : undefined}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={activeId}\n          aria-describedby={hintId}\n          autoComplete=\"off\"\n          spellCheck={false}\n          enterKeyHint=\"search\"\n          value={query}\n          placeholder={placeholder}\n          onChange={(event) => {\n            setQuery(event.target.value);\n            setActive(0);\n            setOpen(true);\n          }}\n          onFocus={() => setOpen(true)}\n          onClick={() => setOpen(true)}\n          onKeyDown={onKeyDown}\n          className=\"h-9 min-w-24 flex-1 border-0 bg-transparent p-0 text-base text-[#071d1b] outline-none placeholder:text-[#045f64]/50\"\n        />\n      </div>\n\n      {flight && (\n        <span\n          ref={ghostRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute top-0 left-0 z-30 flex h-9 w-max items-center rounded-full ps-3 pe-3 whitespace-nowrap opacity-0\"\n        >\n          {flight.term}\n        </span>\n      )}\n\n      {name && chips.map((chip) => <input key={chip} type=\"hidden\" name={name} value={chip} />)}\n      <span id={hintId} className=\"sr-only\">\n        Press Enter to add a filter. Backspace at the start of the field selects the last filter;\n        press it again to remove it. Delete removes the highlighted recent search.\n      </span>\n      <span aria-live=\"polite\" className=\"sr-only\">\n        <span key={note.count}>{note.text}</span>\n      </span>\n    </div>\n  );\n};\n\nexport default MorphingSearch;\n
" } }, + "ink-stroke-button": { + "react": { + "code": "'use client';\n\nimport { useRef, useState, type ComponentPropsWithRef } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\ntype Rgb = [number, number, number];\nconst TEAL: Rgb = [4 / 255, 95 / 255, 100 / 255];\nconst LIME: Rgb = [198 / 255, 245 / 255, 111 / 255];\n\n// Brush: the ink that trails the cursor.\nconst RADIUS = 0.52; // dab size, in button heights\nconst FOLLOW = 0.08; // seconds the brush lags the pointer; the lag is the glide\nconst INK_PER_PX = 0.06; // ink per pixel moved, so circling builds up more\nconst INK_MAX = 1.6;\nconst INK_FADE = 1.6; // ink lost per second\nconst PUSH = 0.15; // share of the pointer's speed handed to the fluid\nconst FLOW_FADE = 2.5; // motion lost per second\n\n// Pool: the ink that floods in when the cursor crosses an edge.\nconst POOL_X = 0.28; // from a side: reach in, in widths\nconst POOL_Y = 1; // from a side: height, in heights; 1 fills top to bottom\nconst POOL_SPAN = 0.22; // from top or bottom: half its width, in widths\nconst POOL_DEPTH = 0.8; // from top or bottom: reach in, in heights\nconst POOL_INK = 1.6;\nconst POOL_FADE = 2.4; // lost per second, apart from the brush's ink\nconst POOL_GROW = 0.88; // seconds to spread in\nconst POOL_GAP = 0.35; // shortest time between two pools\n\n// Solver.\nconst CELL = 3; // simulation cell size, in CSS pixels\nconst PRESSURE_STEPS = 12;\nconst PRESSURE_KEEP = 0.8; // last frame's pressure, reused as a head start\nconst IDLE_AFTER = 3.5; // seconds without new ink before the loop sleeps\n\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nout vec2 vUv;\nvoid main() {\n vUv = aPos * 0.5 + 0.5;\n gl_Position = vec4(aPos, 0.0, 1.0);\n}`;\n\nconst head = `#version 300 es\nprecision highp float;\nin vec2 vUv;\nout vec4 outColor;\n`;\n\n// Adds a soft dab. Ink has two layers: x is the brush, which builds up to a\n// cap, and y the pools, which keep the highest dab so their edge stays soft.\nconst SPLAT = `${head}\nuniform sampler2D uTarget;\nuniform vec2 uPoint;\nuniform vec2 uValue;\nuniform float uRadius;\nuniform float uAspect;\nuniform float uShape;\nuniform float uMax;\nuniform float uInk;\nvoid main() {\n vec2 d = vUv - uPoint;\n d.x *= uAspect;\n float dab = exp(-pow(dot(d, d) / uRadius, uShape));\n vec4 base = texture(uTarget, vUv);\n outColor = uInk > 0.5\n ? vec4(min(base.x + dab * uValue.x, uMax), max(base.y, dab * uValue.y), 0.0, 1.0)\n : vec4(base.xy + dab * uValue, 0.0, 1.0);\n}`;\n\n// Moves a field along the velocity and fades it: ink by a fixed amount a\n// second, motion in proportion.\nconst ADVECT = `${head}\nuniform sampler2D uVelocity;\nuniform sampler2D uSource;\nuniform vec2 uCell;\nuniform float uDt;\nuniform vec4 uFade;\nuniform float uInk;\nvoid main() {\n vec2 from = vUv - uDt * texture(uVelocity, vUv).xy * uCell;\n vec4 value = texture(uSource, from);\n // Nothing flows in from outside, so teal washes back in behind the ink.\n vec2 edge = min(from, 1.0 - from) / (uCell * 0.75);\n vec4 carried = value * clamp(min(edge.x, edge.y), 0.0, 1.0);\n if (uInk > 0.5) {\n carried.y = value.y; // pools sit against the edge, so they keep it\n outColor = max(carried - uFade * uDt, 0.0);\n } else {\n outColor = carried / (1.0 + uFade * uDt);\n }\n}`;\n\n// The cell to the left, right, below and above, for the three passes below.\nconst neighbours = `${head}\nuniform vec2 uCell;\nvec4 L(sampler2D s) { return texture(s, vUv - vec2(uCell.x, 0.0)); }\nvec4 R(sampler2D s) { return texture(s, vUv + vec2(uCell.x, 0.0)); }\nvec4 B(sampler2D s) { return texture(s, vUv - vec2(0.0, uCell.y)); }\nvec4 T(sampler2D s) { return texture(s, vUv + vec2(0.0, uCell.y)); }\n`;\n\nconst DIVERGENCE = `${neighbours}\nuniform sampler2D uVelocity;\nvoid main() {\n float div = R(uVelocity).x - L(uVelocity).x + T(uVelocity).y - B(uVelocity).y;\n outColor = vec4(0.5 * div, 0.0, 0.0, 1.0);\n}`;\n\n// One relaxation pass. uKeep scales the neighbours: PRESSURE_KEEP on the first\n// pass, so it starts from most of last frame's pressure, then 1.\nconst PRESSURE = `${neighbours}\nuniform sampler2D uPressure;\nuniform sampler2D uDivergence;\nuniform float uKeep;\nvoid main() {\n float sum = L(uPressure).x + R(uPressure).x + B(uPressure).x + T(uPressure).x;\n outColor = vec4((sum * uKeep - texture(uDivergence, vUv).x) * 0.25, 0.0, 0.0, 1.0);\n}`;\n\nconst GRADIENT = `${neighbours}\nuniform sampler2D uPressure;\nuniform sampler2D uVelocity;\nvoid main() {\n vec2 grad = vec2(R(uPressure).x - L(uPressure).x, T(uPressure).x - B(uPressure).x);\n outColor = vec4(texture(uVelocity, vUv).xy - 0.5 * grad, 0.0, 1.0);\n}`;\n\n// Shows the ink as a soft threshold, so the lime has an edge, and flips the\n// label's colours under it.\nconst DISPLAY = `${head}\nuniform sampler2D uInk;\nuniform sampler2D uLabel;\nuniform vec3 uBase;\nuniform vec3 uFill;\nvoid main() {\n vec2 ink = texture(uInk, vUv).xy;\n float k = smoothstep(0.3, 0.72, ink.x + ink.y);\n vec3 surface = mix(uBase, uFill, k);\n vec3 text = mix(uFill, uBase, k);\n outColor = vec4(mix(surface, text, texture(uLabel, vUv).a), 1.0);\n}`;\n\nconst prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n// Where a move from a (outside) to b (inside) crossed into a w×h box, and\n// whether it came in through a side rather than the top or bottom.\nconst entryPoint = (ax: number, ay: number, bx: number, by: number, w: number, h: number) => {\n const tx = ax < 0 ? -ax / (bx - ax) : ax > w ? (ax - w) / (ax - bx) : -1;\n const ty = ay < 0 ? -ay / (by - ay) : ay > h ? (ay - h) / (ay - by) : -1;\n const t = Math.max(tx, ty);\n return { x: ax + (bx - ax) * t, y: ay + (by - ay) * t, side: tx >= ty };\n};\n\nconst isFocusVisible = (el: Element) => {\n try {\n return el.matches(':focus-visible');\n } catch {\n return true;\n }\n};\n\ntype Gl = WebGL2RenderingContext;\ntype Target = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number };\ntype Pair = { read: Target; write: Target; swap: () => void };\ntype Program = { use: () => void; set: Record };\n\nconst program = (gl: Gl, fragment: string): Program | null => {\n const prog = gl.createProgram();\n if (!prog) return null;\n for (const [type, source] of [\n [gl.VERTEX_SHADER, VERTEX],\n [gl.FRAGMENT_SHADER, fragment],\n ] as const) {\n const shader = gl.createShader(type);\n if (!shader) return null;\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n gl.attachShader(prog, shader);\n gl.deleteShader(shader); // freed with the program\n }\n gl.bindAttribLocation(prog, 0, 'aPos');\n gl.linkProgram(prog);\n if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null;\n const set: Program['set'] = {};\n const count = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;\n for (let i = 0; i < count; i += 1) {\n const name = gl.getActiveUniform(prog, i)?.name;\n if (name) set[name] = gl.getUniformLocation(prog, name);\n }\n return { use: () => gl.useProgram(prog), set };\n};\n\nconst free = (gl: Gl, ...items: (Target | Pair | null)[]) => {\n for (const item of items) {\n if (!item) continue;\n for (const t of 'read' in item ? [item.read, item.write] : [item]) {\n gl.deleteTexture(t.tex);\n gl.deleteFramebuffer(t.fbo);\n }\n }\n};\n\n// A half-float texture to draw into. Null if the device can't render to one.\nconst target = (gl: Gl, w: number, h: number): Target | null => {\n const tex = gl.createTexture();\n const fbo = gl.createFramebuffer();\n if (!tex || !fbo) return null;\n gl.bindTexture(gl.TEXTURE_2D, tex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n const t = { tex, fbo, w, h };\n if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {\n free(gl, t);\n return null;\n }\n gl.clearColor(0, 0, 0, 1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n return t;\n};\n\n// Two targets to read from one while writing the other, then swap.\nconst pair = (gl: Gl, w: number, h: number): Pair | null => {\n const a = target(gl, w, h);\n const b = target(gl, w, h);\n if (!a || !b) {\n free(gl, a, b);\n return null;\n }\n const p: Pair = {\n read: a,\n write: b,\n swap: () => {\n [p.read, p.write] = [p.write, p.read];\n },\n };\n return p;\n};\n\ntype Stroke = { x: number; y: number; vx: number; vy: number; moved: number };\n\ntype Renderer = {\n /** Fits the canvas to the button. False if the device can't run it. */\n resize: () => boolean;\n step: (dt: number, stroke: Stroke | null) => void;\n /** A pool at (x, y) reaching rx widths across and ry heights up and down. */\n pool: (x: number, y: number, rx: number, ry: number, size: number) => void;\n dispose: () => void;\n};\n\n// A small stable-fluids solver. The pointer pushes motion and drops ink, a few\n// pressure passes keep the motion swirling rather than piling up, and both are\n// carried along and fade.\nconst createRenderer = (\n canvas: HTMLCanvasElement,\n button: HTMLElement,\n label: HTMLElement\n): Renderer | null => {\n const gl = canvas.getContext('webgl2', {\n alpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n // A button never needs the discrete GPU; don't wake it on dual-GPU laptops.\n powerPreference: 'low-power',\n });\n if (!gl) return null;\n gl.getExtension('EXT_color_buffer_float');\n gl.getExtension('EXT_color_buffer_half_float');\n const dispose = () => gl.getExtension('WEBGL_lose_context')?.loseContext();\n\n const sources = [SPLAT, ADVECT, DIVERGENCE, PRESSURE, GRADIENT, DISPLAY];\n const programs = sources.map((source) => program(gl, source));\n if (programs.some((p) => !p)) {\n dispose();\n return null;\n }\n const [splatP, advectP, divergenceP, pressureP, gradientP, displayP] = programs as Program[];\n\n // One quad covering the target; every pass draws it.\n gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n\n const labelTex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, labelTex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n const text = document.createElement('canvas');\n\n let velocity: Pair | null = null;\n let pressure: Pair | null = null;\n let divergence: Target | null = null;\n let ink: Pair | null = null;\n // Button size in CSS pixels, and canvas size in device pixels.\n let cssW = 1;\n let cssH = 1;\n let width = 1;\n let height = 1;\n let dpr = 1;\n\n const draw = (to: Target | null) => {\n gl.bindFramebuffer(gl.FRAMEBUFFER, to ? to.fbo : null);\n gl.viewport(0, 0, to ? to.w : width, to ? to.h : height);\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n };\n\n const bind = (unit: number, tex: WebGLTexture | null) => {\n gl.activeTexture(gl.TEXTURE0 + unit);\n gl.bindTexture(gl.TEXTURE_2D, tex);\n return unit;\n };\n\n // Adds a dab to a field at (x, y) in button pixels. The radius is in button\n // heights; aspect stretches it across.\n const splat = (\n field: Pair,\n x: number,\n y: number,\n value: [number, number],\n {\n radius,\n aspect,\n shape,\n isInk,\n }: { radius: number; aspect: number; shape: number; isInk: boolean }\n ) => {\n splatP.use();\n gl.uniform1i(splatP.set.uTarget, bind(0, field.read.tex));\n gl.uniform2f(splatP.set.uPoint, x / cssW, 1 - y / cssH);\n gl.uniform2f(splatP.set.uValue, ...value);\n gl.uniform1f(splatP.set.uRadius, radius * radius);\n gl.uniform1f(splatP.set.uAspect, aspect);\n gl.uniform1f(splatP.set.uShape, shape);\n gl.uniform1f(splatP.set.uMax, INK_MAX);\n gl.uniform1f(splatP.set.uInk, isInk ? 1 : 0);\n draw(field.write);\n field.swap();\n };\n\n const advect = (field: Pair, cell: readonly [number, number], dt: number, fade: Rgb) => {\n if (!velocity) return;\n const isInk = field === ink;\n advectP.use();\n gl.uniform1i(advectP.set.uVelocity, bind(0, velocity.read.tex));\n gl.uniform1i(advectP.set.uSource, bind(1, field.read.tex));\n gl.uniform2f(advectP.set.uCell, ...cell);\n gl.uniform1f(advectP.set.uDt, dt);\n gl.uniform4f(advectP.set.uFade, ...fade, 0);\n gl.uniform1f(advectP.set.uInk, isInk ? 1 : 0);\n draw(field.write);\n field.swap();\n };\n\n // The DOM label stays for assistive tech; its pixels are drawn here so the\n // shader can recolour them under the ink.\n const drawLabel = () => {\n const ctx = text.getContext('2d');\n if (!ctx) return;\n text.width = width;\n text.height = height;\n const style = getComputedStyle(label);\n ctx.font = `${style.fontStyle} ${style.fontWeight} ${parseFloat(style.fontSize) * dpr}px ${style.fontFamily}`;\n if ('letterSpacing' in ctx) {\n ctx.letterSpacing = `${(parseFloat(style.letterSpacing) || 0) * dpr}px`;\n }\n const words = label.textContent ?? '';\n const metrics = ctx.measureText(words);\n // Font box metrics arrived in Firefox 116; the glyph box is close enough.\n const ascent = metrics.fontBoundingBoxAscent ?? metrics.actualBoundingBoxAscent;\n const descent = metrics.fontBoundingBoxDescent ?? metrics.actualBoundingBoxDescent;\n const gap = (label.offsetHeight * dpr - (ascent + descent)) / 2;\n ctx.fillStyle = '#fff';\n ctx.fillText(words, label.offsetLeft * dpr, label.offsetTop * dpr + gap + ascent);\n gl.bindTexture(gl.TEXTURE_2D, labelTex);\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, text);\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n };\n\n const show = () => {\n if (!ink) return;\n displayP.use();\n gl.uniform1i(displayP.set.uInk, bind(0, ink.read.tex));\n gl.uniform1i(displayP.set.uLabel, bind(1, labelTex));\n gl.uniform3fv(displayP.set.uBase, TEAL);\n gl.uniform3fv(displayP.set.uFill, LIME);\n draw(null);\n };\n\n return {\n resize: () => {\n cssW = Math.max(1, button.offsetWidth);\n cssH = Math.max(1, button.offsetHeight);\n dpr = Math.min(window.devicePixelRatio || 1, 2);\n width = Math.round(cssW * dpr);\n height = Math.round(cssH * dpr);\n canvas.width = width;\n canvas.height = height;\n\n free(gl, velocity, pressure, divergence, ink);\n const simW = Math.max(8, Math.round(cssW / CELL));\n const simH = Math.max(8, Math.round(cssH / CELL));\n velocity = pair(gl, simW, simH);\n pressure = pair(gl, simW, simH);\n divergence = target(gl, simW, simH);\n ink = pair(gl, Math.max(8, cssW), Math.max(8, cssH));\n if (!velocity || !pressure || !divergence || !ink) return false;\n\n drawLabel();\n show();\n return true;\n },\n\n step: (dt, stroke) => {\n if (!velocity || !pressure || !divergence || !ink) return;\n const cell = [1 / velocity.read.w, 1 / velocity.read.h] as const;\n\n if (stroke) {\n const brush = { radius: RADIUS, aspect: cssW / cssH, shape: 1 };\n const push: [number, number] = [(stroke.vx / CELL) * PUSH, (-stroke.vy / CELL) * PUSH];\n splat(velocity, stroke.x, stroke.y, push, { ...brush, isInk: false });\n splat(ink, stroke.x, stroke.y, [stroke.moved * INK_PER_PX, 0], { ...brush, isInk: true });\n }\n\n // Pressure: start from most of last frame's, then relax it.\n divergenceP.use();\n gl.uniform2f(divergenceP.set.uCell, ...cell);\n gl.uniform1i(divergenceP.set.uVelocity, bind(0, velocity.read.tex));\n draw(divergence);\n\n pressureP.use();\n gl.uniform2f(pressureP.set.uCell, ...cell);\n gl.uniform1i(pressureP.set.uDivergence, bind(1, divergence.tex));\n for (let i = 0; i < PRESSURE_STEPS; i += 1) {\n gl.uniform1f(pressureP.set.uKeep, i === 0 ? PRESSURE_KEEP : 1);\n gl.uniform1i(pressureP.set.uPressure, bind(0, pressure.read.tex));\n draw(pressure.write);\n pressure.swap();\n }\n\n gradientP.use();\n gl.uniform2f(gradientP.set.uCell, ...cell);\n gl.uniform1i(gradientP.set.uPressure, bind(0, pressure.read.tex));\n gl.uniform1i(gradientP.set.uVelocity, bind(1, velocity.read.tex));\n draw(velocity.write);\n velocity.swap();\n\n advect(velocity, cell, dt, [FLOW_FADE, FLOW_FADE, 0]);\n advect(ink, cell, dt, [INK_FADE, POOL_FADE, 0]);\n show();\n },\n\n pool: (x, y, rx, ry, size) => {\n if (!ink) return;\n // Measured in heights, so squeeze x to reach rx of the width.\n splat(ink, x, y, [0, POOL_INK], {\n radius: ry * size,\n aspect: ry / rx,\n shape: 2,\n isInk: true,\n });\n },\n\n dispose,\n };\n};\n\nexport interface InkStrokeButtonProps extends ComponentPropsWithRef<'button'> {\n children: string;\n}\n\nconst InkStrokeButton = ({\n children,\n className,\n type = 'button',\n ref,\n ...props\n}: InkStrokeButtonProps) => {\n const btnRef = useRef(null);\n const canvasRef = useRef(null);\n const labelRef = useRef(null);\n const [live, setLive] = useState(false);\n\n const setRef = (node: HTMLButtonElement | null) => {\n btnRef.current = node;\n if (typeof ref === 'function') ref(node);\n else if (ref) ref.current = node;\n };\n\n useGSAP(\n () => {\n const btn = btnRef.current;\n const canvas = canvasRef.current;\n const label = labelRef.current;\n if (!btn || !canvas || !label) return;\n\n let renderer: Renderer | null = null;\n let ticking = false;\n let lastInk = -Infinity;\n let sweep: gsap.core.Tween | null = null;\n // All positions are in the button's own pixels. The pointer is tracked\n // across the page, so the ink is ready as the cursor arrives.\n const pointer = { x: 0, y: 0, known: false };\n const brush = { x: 0, y: 0 };\n const pool = { x: 0, y: 0, rx: POOL_X, ry: POOL_Y, at: -Infinity };\n\n const near = (x: number, y: number, margin: number) =>\n x > -margin && y > -margin && x < btn.offsetWidth + margin && y < btn.offsetHeight + margin;\n\n const stop = () => {\n gsap.ticker.remove(tick);\n ticking = false;\n };\n\n function tick(time: number, deltaTime: number) {\n if (!renderer || !btn) return stop();\n const dt = Math.min(deltaTime / 1000, 1 / 30);\n\n // The brush eases after the pointer, which is what makes the ink glide.\n const ease = 1 - Math.exp(-dt / FOLLOW);\n const x = brush.x + (pointer.x - brush.x) * ease;\n const y = brush.y + (pointer.y - brush.y) * ease;\n const dx = x - brush.x;\n const dy = y - brush.y;\n const moved = Math.hypot(dx, dy);\n const painting =\n pointer.known && moved > 0.2 && near(x, y, btn.offsetHeight * RADIUS * 0.6);\n brush.x = x;\n brush.y = y;\n\n // A new pool eases out from 15% to full size.\n const grown = (time - pool.at) / POOL_GROW;\n if (grown < 1)\n renderer.pool(pool.x, pool.y, pool.rx, pool.ry, 0.15 + 0.85 * (1 - (1 - grown) ** 3));\n\n renderer.step(dt, painting ? { x, y, vx: dx / dt, vy: dy / dt, moved } : null);\n if (painting || grown < 1) lastInk = time;\n // Sleep once the ink has faded; the next move wakes it.\n if (!sweep?.isActive() && time - lastInk > IDLE_AFTER) stop();\n }\n\n const wake = () => {\n if (ticking || !renderer) return;\n ticking = true;\n gsap.ticker.add(tick);\n };\n\n const onMove = (event: PointerEvent) => {\n if (event.pointerType === 'touch' || !renderer || btn.disabled) return;\n const box = btn.getBoundingClientRect();\n const scale = box.width / btn.offsetWidth || 1;\n const x = (event.clientX - box.left) / scale;\n const y = (event.clientY - box.top) / scale;\n\n // Coming in over an edge floods a pool in from that edge. Through a\n // side it fills a full-height band; through the top or bottom it\n // spreads from where the cursor crossed.\n const now = gsap.ticker.time;\n const entered = pointer.known && near(x, y, 0) && !near(pointer.x, pointer.y, 0);\n if (entered && now - pool.at > POOL_GAP) {\n const w = btn.offsetWidth;\n const h = btn.offsetHeight;\n const at = entryPoint(pointer.x, pointer.y, x, y, w, h);\n Object.assign(\n pool,\n at.side\n ? { x: at.x < w / 2 ? 0 : w, y: h / 2, rx: POOL_X, ry: POOL_Y }\n : {\n x: Math.min(Math.max(at.x, 0), w),\n y: at.y < h / 2 ? 0 : h,\n rx: POOL_SPAN,\n ry: POOL_DEPTH,\n },\n { at: now }\n );\n }\n\n // A sleeping brush starts where the pointer was, not where it rested.\n if (!pointer.known || !ticking) {\n brush.x = pointer.known ? pointer.x : x;\n brush.y = pointer.known ? pointer.y : y;\n }\n Object.assign(pointer, { x, y, known: true });\n if (near(x, y, btn.offsetHeight * RADIUS * 2)) wake();\n };\n\n // Chrome sends pointer events to disabled buttons, so skip those.\n const onHover = (event: PointerEvent) => {\n btn.dataset.active = String(event.type === 'pointerenter' && !btn.disabled);\n };\n\n // A keyboard user has no cursor, so focus sweeps one across for them.\n const onFocus = () => {\n if (!isFocusVisible(btn)) return;\n btn.dataset.active = 'true';\n if (!renderer) return;\n sweep?.kill();\n const y = btn.offsetHeight / 2;\n Object.assign(pointer, { x: -btn.offsetHeight * 0.4, y, known: true });\n Object.assign(brush, { x: pointer.x, y });\n wake();\n sweep = gsap.to(pointer, { x: btn.offsetWidth * 0.75, duration: 0.6, ease: 'power2.out' });\n };\n const onBlur = () => {\n if (!btn.matches(':hover')) btn.dataset.active = 'false';\n };\n\n // Without WebGL the CSS colour swap takes over (data-live=false).\n const fallBack = () => {\n stop();\n renderer?.dispose();\n renderer = null;\n setLive(false);\n };\n const fit = () => {\n if (renderer && !renderer.resize()) fallBack();\n };\n const resize = new ResizeObserver(fit);\n\n const start = () => {\n if (renderer || prefersReducedMotion()) return;\n renderer = createRenderer(canvas, btn, label);\n if (!renderer) return;\n if (!renderer.resize()) return fallBack();\n setLive(true);\n resize.observe(btn);\n // The label too: new text in a fixed-width button must be redrawn.\n resize.observe(label);\n document.fonts?.ready.then(fit);\n };\n\n // Not restored: the CSS fallback takes over for the rest of the visit.\n const onLost = () => {\n stop();\n renderer = null;\n setLive(false);\n };\n\n // Contexts are limited per page, so one is only made once on screen.\n const visible =\n typeof IntersectionObserver === 'undefined'\n ? null\n : new IntersectionObserver((entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n visible?.disconnect();\n start();\n }\n });\n if (visible) visible.observe(btn);\n else start();\n\n window.addEventListener('pointermove', onMove, { passive: true });\n btn.addEventListener('pointerenter', onHover);\n btn.addEventListener('pointerleave', onHover);\n btn.addEventListener('focus', onFocus);\n btn.addEventListener('blur', onBlur);\n canvas.addEventListener('webglcontextlost', onLost);\n return () => {\n window.removeEventListener('pointermove', onMove);\n btn.removeEventListener('pointerenter', onHover);\n btn.removeEventListener('pointerleave', onHover);\n btn.removeEventListener('focus', onFocus);\n btn.removeEventListener('blur', onBlur);\n canvas.removeEventListener('webglcontextlost', onLost);\n visible?.disconnect();\n resize.disconnect();\n sweep?.kill();\n stop();\n renderer?.dispose();\n renderer = null; // so a late fonts.ready finds nothing to resize\n };\n },\n { scope: btnRef }\n );\n\n return (\n \n \n \n {children}\n \n \n );\n};\n\nexport default InkStrokeButton;\n", + "codeHtml": "
'use client';\n\nimport { useRef, useState, type ComponentPropsWithRef } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\ntype Rgb = [number, number, number];\nconst TEAL: Rgb = [4 / 255, 95 / 255, 100 / 255];\nconst LIME: Rgb = [198 / 255, 245 / 255, 111 / 255];\n\n// Brush: the ink that trails the cursor.\nconst RADIUS = 0.52; // dab size, in button heights\nconst FOLLOW = 0.08; // seconds the brush lags the pointer; the lag is the glide\nconst INK_PER_PX = 0.06; // ink per pixel moved, so circling builds up more\nconst INK_MAX = 1.6;\nconst INK_FADE = 1.6; // ink lost per second\nconst PUSH = 0.15; // share of the pointer's speed handed to the fluid\nconst FLOW_FADE = 2.5; // motion lost per second\n\n// Pool: the ink that floods in when the cursor crosses an edge.\nconst POOL_X = 0.28; // from a side: reach in, in widths\nconst POOL_Y = 1; // from a side: height, in heights; 1 fills top to bottom\nconst POOL_SPAN = 0.22; // from top or bottom: half its width, in widths\nconst POOL_DEPTH = 0.8; // from top or bottom: reach in, in heights\nconst POOL_INK = 1.6;\nconst POOL_FADE = 2.4; // lost per second, apart from the brush's ink\nconst POOL_GROW = 0.88; // seconds to spread in\nconst POOL_GAP = 0.35; // shortest time between two pools\n\n// Solver.\nconst CELL = 3; // simulation cell size, in CSS pixels\nconst PRESSURE_STEPS = 12;\nconst PRESSURE_KEEP = 0.8; // last frame's pressure, reused as a head start\nconst IDLE_AFTER = 3.5; // seconds without new ink before the loop sleeps\n\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nout vec2 vUv;\nvoid main() {\n  vUv = aPos * 0.5 + 0.5;\n  gl_Position = vec4(aPos, 0.0, 1.0);\n}`;\n\nconst head = `#version 300 es\nprecision highp float;\nin vec2 vUv;\nout vec4 outColor;\n`;\n\n// Adds a soft dab. Ink has two layers: x is the brush, which builds up to a\n// cap, and y the pools, which keep the highest dab so their edge stays soft.\nconst SPLAT = `${head}\nuniform sampler2D uTarget;\nuniform vec2 uPoint;\nuniform vec2 uValue;\nuniform float uRadius;\nuniform float uAspect;\nuniform float uShape;\nuniform float uMax;\nuniform float uInk;\nvoid main() {\n  vec2 d = vUv - uPoint;\n  d.x *= uAspect;\n  float dab = exp(-pow(dot(d, d) / uRadius, uShape));\n  vec4 base = texture(uTarget, vUv);\n  outColor = uInk > 0.5\n    ? vec4(min(base.x + dab * uValue.x, uMax), max(base.y, dab * uValue.y), 0.0, 1.0)\n    : vec4(base.xy + dab * uValue, 0.0, 1.0);\n}`;\n\n// Moves a field along the velocity and fades it: ink by a fixed amount a\n// second, motion in proportion.\nconst ADVECT = `${head}\nuniform sampler2D uVelocity;\nuniform sampler2D uSource;\nuniform vec2 uCell;\nuniform float uDt;\nuniform vec4 uFade;\nuniform float uInk;\nvoid main() {\n  vec2 from = vUv - uDt * texture(uVelocity, vUv).xy * uCell;\n  vec4 value = texture(uSource, from);\n  // Nothing flows in from outside, so teal washes back in behind the ink.\n  vec2 edge = min(from, 1.0 - from) / (uCell * 0.75);\n  vec4 carried = value * clamp(min(edge.x, edge.y), 0.0, 1.0);\n  if (uInk > 0.5) {\n    carried.y = value.y; // pools sit against the edge, so they keep it\n    outColor = max(carried - uFade * uDt, 0.0);\n  } else {\n    outColor = carried / (1.0 + uFade * uDt);\n  }\n}`;\n\n// The cell to the left, right, below and above, for the three passes below.\nconst neighbours = `${head}\nuniform vec2 uCell;\nvec4 L(sampler2D s) { return texture(s, vUv - vec2(uCell.x, 0.0)); }\nvec4 R(sampler2D s) { return texture(s, vUv + vec2(uCell.x, 0.0)); }\nvec4 B(sampler2D s) { return texture(s, vUv - vec2(0.0, uCell.y)); }\nvec4 T(sampler2D s) { return texture(s, vUv + vec2(0.0, uCell.y)); }\n`;\n\nconst DIVERGENCE = `${neighbours}\nuniform sampler2D uVelocity;\nvoid main() {\n  float div = R(uVelocity).x - L(uVelocity).x + T(uVelocity).y - B(uVelocity).y;\n  outColor = vec4(0.5 * div, 0.0, 0.0, 1.0);\n}`;\n\n// One relaxation pass. uKeep scales the neighbours: PRESSURE_KEEP on the first\n// pass, so it starts from most of last frame's pressure, then 1.\nconst PRESSURE = `${neighbours}\nuniform sampler2D uPressure;\nuniform sampler2D uDivergence;\nuniform float uKeep;\nvoid main() {\n  float sum = L(uPressure).x + R(uPressure).x + B(uPressure).x + T(uPressure).x;\n  outColor = vec4((sum * uKeep - texture(uDivergence, vUv).x) * 0.25, 0.0, 0.0, 1.0);\n}`;\n\nconst GRADIENT = `${neighbours}\nuniform sampler2D uPressure;\nuniform sampler2D uVelocity;\nvoid main() {\n  vec2 grad = vec2(R(uPressure).x - L(uPressure).x, T(uPressure).x - B(uPressure).x);\n  outColor = vec4(texture(uVelocity, vUv).xy - 0.5 * grad, 0.0, 1.0);\n}`;\n\n// Shows the ink as a soft threshold, so the lime has an edge, and flips the\n// label's colours under it.\nconst DISPLAY = `${head}\nuniform sampler2D uInk;\nuniform sampler2D uLabel;\nuniform vec3 uBase;\nuniform vec3 uFill;\nvoid main() {\n  vec2 ink = texture(uInk, vUv).xy;\n  float k = smoothstep(0.3, 0.72, ink.x + ink.y);\n  vec3 surface = mix(uBase, uFill, k);\n  vec3 text = mix(uFill, uBase, k);\n  outColor = vec4(mix(surface, text, texture(uLabel, vUv).a), 1.0);\n}`;\n\nconst prefersReducedMotion = () =>\n  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n// Where a move from a (outside) to b (inside) crossed into a w×h box, and\n// whether it came in through a side rather than the top or bottom.\nconst entryPoint = (ax: number, ay: number, bx: number, by: number, w: number, h: number) => {\n  const tx = ax < 0 ? -ax / (bx - ax) : ax > w ? (ax - w) / (ax - bx) : -1;\n  const ty = ay < 0 ? -ay / (by - ay) : ay > h ? (ay - h) / (ay - by) : -1;\n  const t = Math.max(tx, ty);\n  return { x: ax + (bx - ax) * t, y: ay + (by - ay) * t, side: tx >= ty };\n};\n\nconst isFocusVisible = (el: Element) => {\n  try {\n    return el.matches(':focus-visible');\n  } catch {\n    return true;\n  }\n};\n\ntype Gl = WebGL2RenderingContext;\ntype Target = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number };\ntype Pair = { read: Target; write: Target; swap: () => void };\ntype Program = { use: () => void; set: Record<string, WebGLUniformLocation | null> };\n\nconst program = (gl: Gl, fragment: string): Program | null => {\n  const prog = gl.createProgram();\n  if (!prog) return null;\n  for (const [type, source] of [\n    [gl.VERTEX_SHADER, VERTEX],\n    [gl.FRAGMENT_SHADER, fragment],\n  ] as const) {\n    const shader = gl.createShader(type);\n    if (!shader) return null;\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    gl.attachShader(prog, shader);\n    gl.deleteShader(shader); // freed with the program\n  }\n  gl.bindAttribLocation(prog, 0, 'aPos');\n  gl.linkProgram(prog);\n  if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null;\n  const set: Program['set'] = {};\n  const count = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;\n  for (let i = 0; i < count; i += 1) {\n    const name = gl.getActiveUniform(prog, i)?.name;\n    if (name) set[name] = gl.getUniformLocation(prog, name);\n  }\n  return { use: () => gl.useProgram(prog), set };\n};\n\nconst free = (gl: Gl, ...items: (Target | Pair | null)[]) => {\n  for (const item of items) {\n    if (!item) continue;\n    for (const t of 'read' in item ? [item.read, item.write] : [item]) {\n      gl.deleteTexture(t.tex);\n      gl.deleteFramebuffer(t.fbo);\n    }\n  }\n};\n\n// A half-float texture to draw into. Null if the device can't render to one.\nconst target = (gl: Gl, w: number, h: number): Target | null => {\n  const tex = gl.createTexture();\n  const fbo = gl.createFramebuffer();\n  if (!tex || !fbo) return null;\n  gl.bindTexture(gl.TEXTURE_2D, tex);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n  const t = { tex, fbo, w, h };\n  if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {\n    free(gl, t);\n    return null;\n  }\n  gl.clearColor(0, 0, 0, 1);\n  gl.clear(gl.COLOR_BUFFER_BIT);\n  return t;\n};\n\n// Two targets to read from one while writing the other, then swap.\nconst pair = (gl: Gl, w: number, h: number): Pair | null => {\n  const a = target(gl, w, h);\n  const b = target(gl, w, h);\n  if (!a || !b) {\n    free(gl, a, b);\n    return null;\n  }\n  const p: Pair = {\n    read: a,\n    write: b,\n    swap: () => {\n      [p.read, p.write] = [p.write, p.read];\n    },\n  };\n  return p;\n};\n\ntype Stroke = { x: number; y: number; vx: number; vy: number; moved: number };\n\ntype Renderer = {\n  /** Fits the canvas to the button. False if the device can't run it. */\n  resize: () => boolean;\n  step: (dt: number, stroke: Stroke | null) => void;\n  /** A pool at (x, y) reaching rx widths across and ry heights up and down. */\n  pool: (x: number, y: number, rx: number, ry: number, size: number) => void;\n  dispose: () => void;\n};\n\n// A small stable-fluids solver. The pointer pushes motion and drops ink, a few\n// pressure passes keep the motion swirling rather than piling up, and both are\n// carried along and fade.\nconst createRenderer = (\n  canvas: HTMLCanvasElement,\n  button: HTMLElement,\n  label: HTMLElement\n): Renderer | null => {\n  const gl = canvas.getContext('webgl2', {\n    alpha: false,\n    antialias: false,\n    depth: false,\n    stencil: false,\n    // A button never needs the discrete GPU; don't wake it on dual-GPU laptops.\n    powerPreference: 'low-power',\n  });\n  if (!gl) return null;\n  gl.getExtension('EXT_color_buffer_float');\n  gl.getExtension('EXT_color_buffer_half_float');\n  const dispose = () => gl.getExtension('WEBGL_lose_context')?.loseContext();\n\n  const sources = [SPLAT, ADVECT, DIVERGENCE, PRESSURE, GRADIENT, DISPLAY];\n  const programs = sources.map((source) => program(gl, source));\n  if (programs.some((p) => !p)) {\n    dispose();\n    return null;\n  }\n  const [splatP, advectP, divergenceP, pressureP, gradientP, displayP] = programs as Program[];\n\n  // One quad covering the target; every pass draws it.\n  gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n\n  const labelTex = gl.createTexture();\n  gl.bindTexture(gl.TEXTURE_2D, labelTex);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  const text = document.createElement('canvas');\n\n  let velocity: Pair | null = null;\n  let pressure: Pair | null = null;\n  let divergence: Target | null = null;\n  let ink: Pair | null = null;\n  // Button size in CSS pixels, and canvas size in device pixels.\n  let cssW = 1;\n  let cssH = 1;\n  let width = 1;\n  let height = 1;\n  let dpr = 1;\n\n  const draw = (to: Target | null) => {\n    gl.bindFramebuffer(gl.FRAMEBUFFER, to ? to.fbo : null);\n    gl.viewport(0, 0, to ? to.w : width, to ? to.h : height);\n    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n  };\n\n  const bind = (unit: number, tex: WebGLTexture | null) => {\n    gl.activeTexture(gl.TEXTURE0 + unit);\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    return unit;\n  };\n\n  // Adds a dab to a field at (x, y) in button pixels. The radius is in button\n  // heights; aspect stretches it across.\n  const splat = (\n    field: Pair,\n    x: number,\n    y: number,\n    value: [number, number],\n    {\n      radius,\n      aspect,\n      shape,\n      isInk,\n    }: { radius: number; aspect: number; shape: number; isInk: boolean }\n  ) => {\n    splatP.use();\n    gl.uniform1i(splatP.set.uTarget, bind(0, field.read.tex));\n    gl.uniform2f(splatP.set.uPoint, x / cssW, 1 - y / cssH);\n    gl.uniform2f(splatP.set.uValue, ...value);\n    gl.uniform1f(splatP.set.uRadius, radius * radius);\n    gl.uniform1f(splatP.set.uAspect, aspect);\n    gl.uniform1f(splatP.set.uShape, shape);\n    gl.uniform1f(splatP.set.uMax, INK_MAX);\n    gl.uniform1f(splatP.set.uInk, isInk ? 1 : 0);\n    draw(field.write);\n    field.swap();\n  };\n\n  const advect = (field: Pair, cell: readonly [number, number], dt: number, fade: Rgb) => {\n    if (!velocity) return;\n    const isInk = field === ink;\n    advectP.use();\n    gl.uniform1i(advectP.set.uVelocity, bind(0, velocity.read.tex));\n    gl.uniform1i(advectP.set.uSource, bind(1, field.read.tex));\n    gl.uniform2f(advectP.set.uCell, ...cell);\n    gl.uniform1f(advectP.set.uDt, dt);\n    gl.uniform4f(advectP.set.uFade, ...fade, 0);\n    gl.uniform1f(advectP.set.uInk, isInk ? 1 : 0);\n    draw(field.write);\n    field.swap();\n  };\n\n  // The DOM label stays for assistive tech; its pixels are drawn here so the\n  // shader can recolour them under the ink.\n  const drawLabel = () => {\n    const ctx = text.getContext('2d');\n    if (!ctx) return;\n    text.width = width;\n    text.height = height;\n    const style = getComputedStyle(label);\n    ctx.font = `${style.fontStyle} ${style.fontWeight} ${parseFloat(style.fontSize) * dpr}px ${style.fontFamily}`;\n    if ('letterSpacing' in ctx) {\n      ctx.letterSpacing = `${(parseFloat(style.letterSpacing) || 0) * dpr}px`;\n    }\n    const words = label.textContent ?? '';\n    const metrics = ctx.measureText(words);\n    // Font box metrics arrived in Firefox 116; the glyph box is close enough.\n    const ascent = metrics.fontBoundingBoxAscent ?? metrics.actualBoundingBoxAscent;\n    const descent = metrics.fontBoundingBoxDescent ?? metrics.actualBoundingBoxDescent;\n    const gap = (label.offsetHeight * dpr - (ascent + descent)) / 2;\n    ctx.fillStyle = '#fff';\n    ctx.fillText(words, label.offsetLeft * dpr, label.offsetTop * dpr + gap + ascent);\n    gl.bindTexture(gl.TEXTURE_2D, labelTex);\n    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, text);\n    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);\n  };\n\n  const show = () => {\n    if (!ink) return;\n    displayP.use();\n    gl.uniform1i(displayP.set.uInk, bind(0, ink.read.tex));\n    gl.uniform1i(displayP.set.uLabel, bind(1, labelTex));\n    gl.uniform3fv(displayP.set.uBase, TEAL);\n    gl.uniform3fv(displayP.set.uFill, LIME);\n    draw(null);\n  };\n\n  return {\n    resize: () => {\n      cssW = Math.max(1, button.offsetWidth);\n      cssH = Math.max(1, button.offsetHeight);\n      dpr = Math.min(window.devicePixelRatio || 1, 2);\n      width = Math.round(cssW * dpr);\n      height = Math.round(cssH * dpr);\n      canvas.width = width;\n      canvas.height = height;\n\n      free(gl, velocity, pressure, divergence, ink);\n      const simW = Math.max(8, Math.round(cssW / CELL));\n      const simH = Math.max(8, Math.round(cssH / CELL));\n      velocity = pair(gl, simW, simH);\n      pressure = pair(gl, simW, simH);\n      divergence = target(gl, simW, simH);\n      ink = pair(gl, Math.max(8, cssW), Math.max(8, cssH));\n      if (!velocity || !pressure || !divergence || !ink) return false;\n\n      drawLabel();\n      show();\n      return true;\n    },\n\n    step: (dt, stroke) => {\n      if (!velocity || !pressure || !divergence || !ink) return;\n      const cell = [1 / velocity.read.w, 1 / velocity.read.h] as const;\n\n      if (stroke) {\n        const brush = { radius: RADIUS, aspect: cssW / cssH, shape: 1 };\n        const push: [number, number] = [(stroke.vx / CELL) * PUSH, (-stroke.vy / CELL) * PUSH];\n        splat(velocity, stroke.x, stroke.y, push, { ...brush, isInk: false });\n        splat(ink, stroke.x, stroke.y, [stroke.moved * INK_PER_PX, 0], { ...brush, isInk: true });\n      }\n\n      // Pressure: start from most of last frame's, then relax it.\n      divergenceP.use();\n      gl.uniform2f(divergenceP.set.uCell, ...cell);\n      gl.uniform1i(divergenceP.set.uVelocity, bind(0, velocity.read.tex));\n      draw(divergence);\n\n      pressureP.use();\n      gl.uniform2f(pressureP.set.uCell, ...cell);\n      gl.uniform1i(pressureP.set.uDivergence, bind(1, divergence.tex));\n      for (let i = 0; i < PRESSURE_STEPS; i += 1) {\n        gl.uniform1f(pressureP.set.uKeep, i === 0 ? PRESSURE_KEEP : 1);\n        gl.uniform1i(pressureP.set.uPressure, bind(0, pressure.read.tex));\n        draw(pressure.write);\n        pressure.swap();\n      }\n\n      gradientP.use();\n      gl.uniform2f(gradientP.set.uCell, ...cell);\n      gl.uniform1i(gradientP.set.uPressure, bind(0, pressure.read.tex));\n      gl.uniform1i(gradientP.set.uVelocity, bind(1, velocity.read.tex));\n      draw(velocity.write);\n      velocity.swap();\n\n      advect(velocity, cell, dt, [FLOW_FADE, FLOW_FADE, 0]);\n      advect(ink, cell, dt, [INK_FADE, POOL_FADE, 0]);\n      show();\n    },\n\n    pool: (x, y, rx, ry, size) => {\n      if (!ink) return;\n      // Measured in heights, so squeeze x to reach rx of the width.\n      splat(ink, x, y, [0, POOL_INK], {\n        radius: ry * size,\n        aspect: ry / rx,\n        shape: 2,\n        isInk: true,\n      });\n    },\n\n    dispose,\n  };\n};\n\nexport interface InkStrokeButtonProps extends ComponentPropsWithRef<'button'> {\n  children: string;\n}\n\nconst InkStrokeButton = ({\n  children,\n  className,\n  type = 'button',\n  ref,\n  ...props\n}: InkStrokeButtonProps) => {\n  const btnRef = useRef<HTMLButtonElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const labelRef = useRef<HTMLSpanElement>(null);\n  const [live, setLive] = useState(false);\n\n  const setRef = (node: HTMLButtonElement | null) => {\n    btnRef.current = node;\n    if (typeof ref === 'function') ref(node);\n    else if (ref) ref.current = node;\n  };\n\n  useGSAP(\n    () => {\n      const btn = btnRef.current;\n      const canvas = canvasRef.current;\n      const label = labelRef.current;\n      if (!btn || !canvas || !label) return;\n\n      let renderer: Renderer | null = null;\n      let ticking = false;\n      let lastInk = -Infinity;\n      let sweep: gsap.core.Tween | null = null;\n      // All positions are in the button's own pixels. The pointer is tracked\n      // across the page, so the ink is ready as the cursor arrives.\n      const pointer = { x: 0, y: 0, known: false };\n      const brush = { x: 0, y: 0 };\n      const pool = { x: 0, y: 0, rx: POOL_X, ry: POOL_Y, at: -Infinity };\n\n      const near = (x: number, y: number, margin: number) =>\n        x > -margin && y > -margin && x < btn.offsetWidth + margin && y < btn.offsetHeight + margin;\n\n      const stop = () => {\n        gsap.ticker.remove(tick);\n        ticking = false;\n      };\n\n      function tick(time: number, deltaTime: number) {\n        if (!renderer || !btn) return stop();\n        const dt = Math.min(deltaTime / 1000, 1 / 30);\n\n        // The brush eases after the pointer, which is what makes the ink glide.\n        const ease = 1 - Math.exp(-dt / FOLLOW);\n        const x = brush.x + (pointer.x - brush.x) * ease;\n        const y = brush.y + (pointer.y - brush.y) * ease;\n        const dx = x - brush.x;\n        const dy = y - brush.y;\n        const moved = Math.hypot(dx, dy);\n        const painting =\n          pointer.known && moved > 0.2 && near(x, y, btn.offsetHeight * RADIUS * 0.6);\n        brush.x = x;\n        brush.y = y;\n\n        // A new pool eases out from 15% to full size.\n        const grown = (time - pool.at) / POOL_GROW;\n        if (grown < 1)\n          renderer.pool(pool.x, pool.y, pool.rx, pool.ry, 0.15 + 0.85 * (1 - (1 - grown) ** 3));\n\n        renderer.step(dt, painting ? { x, y, vx: dx / dt, vy: dy / dt, moved } : null);\n        if (painting || grown < 1) lastInk = time;\n        // Sleep once the ink has faded; the next move wakes it.\n        if (!sweep?.isActive() && time - lastInk > IDLE_AFTER) stop();\n      }\n\n      const wake = () => {\n        if (ticking || !renderer) return;\n        ticking = true;\n        gsap.ticker.add(tick);\n      };\n\n      const onMove = (event: PointerEvent) => {\n        if (event.pointerType === 'touch' || !renderer || btn.disabled) return;\n        const box = btn.getBoundingClientRect();\n        const scale = box.width / btn.offsetWidth || 1;\n        const x = (event.clientX - box.left) / scale;\n        const y = (event.clientY - box.top) / scale;\n\n        // Coming in over an edge floods a pool in from that edge. Through a\n        // side it fills a full-height band; through the top or bottom it\n        // spreads from where the cursor crossed.\n        const now = gsap.ticker.time;\n        const entered = pointer.known && near(x, y, 0) && !near(pointer.x, pointer.y, 0);\n        if (entered && now - pool.at > POOL_GAP) {\n          const w = btn.offsetWidth;\n          const h = btn.offsetHeight;\n          const at = entryPoint(pointer.x, pointer.y, x, y, w, h);\n          Object.assign(\n            pool,\n            at.side\n              ? { x: at.x < w / 2 ? 0 : w, y: h / 2, rx: POOL_X, ry: POOL_Y }\n              : {\n                  x: Math.min(Math.max(at.x, 0), w),\n                  y: at.y < h / 2 ? 0 : h,\n                  rx: POOL_SPAN,\n                  ry: POOL_DEPTH,\n                },\n            { at: now }\n          );\n        }\n\n        // A sleeping brush starts where the pointer was, not where it rested.\n        if (!pointer.known || !ticking) {\n          brush.x = pointer.known ? pointer.x : x;\n          brush.y = pointer.known ? pointer.y : y;\n        }\n        Object.assign(pointer, { x, y, known: true });\n        if (near(x, y, btn.offsetHeight * RADIUS * 2)) wake();\n      };\n\n      // Chrome sends pointer events to disabled buttons, so skip those.\n      const onHover = (event: PointerEvent) => {\n        btn.dataset.active = String(event.type === 'pointerenter' && !btn.disabled);\n      };\n\n      // A keyboard user has no cursor, so focus sweeps one across for them.\n      const onFocus = () => {\n        if (!isFocusVisible(btn)) return;\n        btn.dataset.active = 'true';\n        if (!renderer) return;\n        sweep?.kill();\n        const y = btn.offsetHeight / 2;\n        Object.assign(pointer, { x: -btn.offsetHeight * 0.4, y, known: true });\n        Object.assign(brush, { x: pointer.x, y });\n        wake();\n        sweep = gsap.to(pointer, { x: btn.offsetWidth * 0.75, duration: 0.6, ease: 'power2.out' });\n      };\n      const onBlur = () => {\n        if (!btn.matches(':hover')) btn.dataset.active = 'false';\n      };\n\n      // Without WebGL the CSS colour swap takes over (data-live=false).\n      const fallBack = () => {\n        stop();\n        renderer?.dispose();\n        renderer = null;\n        setLive(false);\n      };\n      const fit = () => {\n        if (renderer && !renderer.resize()) fallBack();\n      };\n      const resize = new ResizeObserver(fit);\n\n      const start = () => {\n        if (renderer || prefersReducedMotion()) return;\n        renderer = createRenderer(canvas, btn, label);\n        if (!renderer) return;\n        if (!renderer.resize()) return fallBack();\n        setLive(true);\n        resize.observe(btn);\n        // The label too: new text in a fixed-width button must be redrawn.\n        resize.observe(label);\n        document.fonts?.ready.then(fit);\n      };\n\n      // Not restored: the CSS fallback takes over for the rest of the visit.\n      const onLost = () => {\n        stop();\n        renderer = null;\n        setLive(false);\n      };\n\n      // Contexts are limited per page, so one is only made once on screen.\n      const visible =\n        typeof IntersectionObserver === 'undefined'\n          ? null\n          : new IntersectionObserver((entries) => {\n              if (entries.some((entry) => entry.isIntersecting)) {\n                visible?.disconnect();\n                start();\n              }\n            });\n      if (visible) visible.observe(btn);\n      else start();\n\n      window.addEventListener('pointermove', onMove, { passive: true });\n      btn.addEventListener('pointerenter', onHover);\n      btn.addEventListener('pointerleave', onHover);\n      btn.addEventListener('focus', onFocus);\n      btn.addEventListener('blur', onBlur);\n      canvas.addEventListener('webglcontextlost', onLost);\n      return () => {\n        window.removeEventListener('pointermove', onMove);\n        btn.removeEventListener('pointerenter', onHover);\n        btn.removeEventListener('pointerleave', onHover);\n        btn.removeEventListener('focus', onFocus);\n        btn.removeEventListener('blur', onBlur);\n        canvas.removeEventListener('webglcontextlost', onLost);\n        visible?.disconnect();\n        resize.disconnect();\n        sweep?.kill();\n        stop();\n        renderer?.dispose();\n        renderer = null; // so a late fonts.ready finds nothing to resize\n      };\n    },\n    { scope: btnRef }\n  );\n\n  return (\n    <button\n      ref={setRef}\n      type={type}\n      data-active=\"false\"\n      data-live={live}\n      className={cn(\n        'relative inline-flex h-12 cursor-pointer items-center justify-center overflow-hidden rounded-[14px] bg-[#045f64] px-6 text-base font-medium text-[#c6f56f] transition-[background-color,color,scale] duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] outline-none select-none focus-visible:ring-2 focus-visible:ring-[#045f64] focus-visible:ring-offset-2 not-disabled:active:scale-[0.97] disabled:cursor-not-allowed disabled:opacity-50 data-[active=true]:data-[live=false]:bg-[#c6f56f] data-[active=true]:data-[live=false]:text-[#045f64] motion-reduce:transition-none motion-reduce:active:scale-100',\n        className\n      )}\n      {...props}\n    >\n      <canvas\n        ref={canvasRef}\n        aria-hidden=\"true\"\n        className={cn(\n          // High-contrast mode forces the label visible, so hide the copy.\n          'pointer-events-none absolute inset-0 size-full forced-colors:hidden',\n          live ? 'opacity-100' : 'opacity-0'\n        )}\n      />\n      <span ref={labelRef} className={cn('relative whitespace-nowrap', live && 'text-transparent')}>\n        {children}\n      </span>\n    </button>\n  );\n};\n\nexport default InkStrokeButton;\n
" + } + }, "pricing-plan-switch": { "react": { "code": "'use client';\n\nimport { useRef, useState, type ComponentPropsWithoutRef } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport NumberFlow from '@number-flow/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\nconst prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nexport interface PricingPlan {\n /** Stable id used as the animation key. */\n id: string;\n /** Plan name, shown in the left selector and the morphing card badge. */\n name: string;\n /** Supporting line under the name in the selector. */\n subtitle: string;\n /** Body copy that crossfades in when the plan is selected. */\n description: string;\n /** Price billed monthly. */\n monthly: number;\n /** Price billed yearly. */\n yearly: number;\n /** How many of `features` are included (the rest render dimmed). */\n includedCount: number;\n}\n\nexport interface PricingPlanSwitchProps extends Omit, 'title'> {\n /** Plans shown in the selector. Defaults to a 3-tier sample. */\n plans?: PricingPlan[];\n /** Feature checklist; each plan lights up its first `includedCount` rows. */\n features?: string[];\n /** Eyebrow badge above the heading. */\n eyebrow?: string;\n /** Section heading. */\n heading?: string;\n /** Section sub-heading. */\n description?: string;\n /** Currency symbol shown before the price. */\n currency?: string;\n /** Primary CTA label. */\n ctaText?: string;\n /** Primary CTA link. */\n ctaHref?: string;\n}\n\nconst DEFAULT_PLANS: PricingPlan[] = [\n {\n id: 'starter',\n name: 'Starter',\n subtitle: 'For early-stage teams',\n description:\n 'Everything you need to get moving — core automation, a shared workspace, and email support to keep momentum.',\n monthly: 2500,\n yearly: 25000,\n includedCount: 5,\n },\n {\n id: 'pro',\n name: 'Pro',\n subtitle: 'For growing teams',\n description:\n 'Built for growing teams with advanced automation, priority workflows, and deeper analytics to keep everything moving.',\n monthly: 4190,\n yearly: 41900,\n includedCount: 7,\n },\n {\n id: 'business',\n name: 'Business',\n subtitle: 'For established businesses',\n description:\n 'Enterprise-grade controls with custom workflows, team-wide governance, and dedicated support for large-scale operations.',\n monthly: 8290,\n yearly: 82900,\n includedCount: 9,\n },\n];\n\nconst DEFAULT_FEATURES: string[] = [\n 'Unlimited workflows',\n 'Team workspace',\n 'Email support',\n 'Advanced automation',\n 'Priority queue',\n 'Usage analytics',\n 'Role-based access',\n 'Custom integrations',\n 'Dedicated success manager',\n];\n\nconst ArrowIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst CheckIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst DotIcon = ({ className }: { className?: string }) => {\n return (\n \n \n \n );\n};\n\nconst PricingPlanSwitch = ({\n plans = DEFAULT_PLANS,\n features = DEFAULT_FEATURES,\n eyebrow = 'Pricing',\n heading = 'Simple pricing that scales with you',\n description = 'Upgrade anytime as your needs evolve, and stay focused on building and expanding your product with confidence.',\n currency = '$',\n ctaText = 'Get started',\n ctaHref = '#',\n className,\n ...props\n}: PricingPlanSwitchProps) => {\n const firstId = plans[0]?.id ?? '';\n const [selectedId, setSelectedId] = useState(firstId);\n const [isYearly, setIsYearly] = useState(false);\n\n const cardRef = useRef(null);\n const badgeWrapperRef = useRef(null);\n const prevIdRef = useRef(firstId);\n const badgeRefs = useRef>({});\n const descriptionRefs = useRef>({});\n\n const currentPlan = plans.find((p) => p.id === selectedId) ?? plans[0];\n const price = isYearly ? (currentPlan?.yearly ?? 0) : (currentPlan?.monthly ?? 0);\n\n // Establish the starting state: only the first badge/description is visible,\n // and the wrapper is sized to that badge so its width can morph later.\n useGSAP(\n () => {\n const wrapper = badgeWrapperRef.current;\n if (!wrapper) return;\n\n plans.forEach((plan, index) => {\n const badge = badgeRefs.current[plan.id];\n if (badge) gsap.set(badge, { opacity: index === 0 ? 1 : 0, y: 0 });\n });\n\n const first = badgeRefs.current[firstId];\n if (first) wrapper.style.width = `${first.offsetWidth}px`;\n },\n { scope: cardRef }\n );\n\n // Crossfade the badge + description and morph the badge width on selection.\n useGSAP(\n () => {\n const prev = prevIdRef.current;\n const next = selectedId;\n if (prev === next) return;\n\n const fromBadge = badgeRefs.current[prev];\n const toBadge = badgeRefs.current[next];\n const fromDescription = descriptionRefs.current[prev];\n const toDescription = descriptionRefs.current[next];\n const wrapper = badgeWrapperRef.current;\n\n if (prefersReducedMotion()) {\n plans.forEach((plan) => {\n const badge = badgeRefs.current[plan.id];\n const desc = descriptionRefs.current[plan.id];\n if (badge) gsap.set(badge, { opacity: plan.id === next ? 1 : 0, y: 0 });\n if (desc) gsap.set(desc, { opacity: plan.id === next ? 1 : 0, y: 0 });\n });\n if (wrapper && toBadge) wrapper.style.width = `${toBadge.offsetWidth}px`;\n prevIdRef.current = next;\n return;\n }\n\n const tl = gsap.timeline({ defaults: { ease: 'power3.out' } });\n\n if (fromBadge && toBadge) {\n const fromWidth = wrapper?.offsetWidth ?? fromBadge.offsetWidth;\n const toWidth = toBadge.offsetWidth;\n\n tl.set(toBadge, { y: 12, opacity: 0 }, 0);\n tl.to(fromBadge, { y: -12, opacity: 0, duration: 0.22 }, 0);\n tl.to(toBadge, { y: 0, opacity: 1, duration: 0.28 }, 0.12);\n tl.set(fromBadge, { y: 0 }, 0.3);\n\n if (wrapper) {\n tl.to(wrapper, { width: toWidth, duration: 0.28 }, toWidth > fromWidth ? 0 : 0.12);\n }\n }\n\n if (fromDescription && toDescription) {\n tl.set(toDescription, { y: 12, opacity: 0 }, 0);\n tl.to(fromDescription, { y: -12, opacity: 0, duration: 0.22 }, 0);\n tl.to(toDescription, { y: 0, opacity: 1, duration: 0.28 }, 0.12);\n tl.set(fromDescription, { y: 0 }, 0.3);\n }\n\n prevIdRef.current = next;\n },\n { scope: cardRef, dependencies: [selectedId] }\n );\n\n return (\n
\n
\n {/* Header */}\n
\n
\n \n {eyebrow}\n \n
\n

\n {heading}\n

\n

\n {description}\n

\n
\n
\n\n {/* Billing toggle */}\n
\n \n
\n
\n\n
\n {/* Plan selector */}\n
\n
\n {plans.map((plan) => {\n const isActive = selectedId === plan.id;\n return (\n setSelectedId(plan.id)}\n data-active={isActive ? 'true' : 'false'}\n className=\"group flex w-full cursor-pointer items-center justify-between gap-x-6 rounded-xl px-5 py-3 text-left transition-colors hover:bg-white data-[active=true]:bg-white data-[active=true]:shadow-sm dark:hover:bg-white/10 dark:data-[active=true]:bg-white/10\"\n >\n \n \n {plan.name}\n \n \n {plan.subtitle}\n \n \n \n \n \n \n );\n })}\n
\n\n
\n \n \n Free trial\n \n \n \n Cancel anytime\n \n
\n
\n\n {/* Card */}\n \n
\n \n {plans.map((plan) => (\n {\n badgeRefs.current[plan.id] = el ?? undefined;\n }}\n className=\"absolute inset-y-0 left-0 flex w-max items-center px-3 text-xs font-medium whitespace-nowrap text-[#045f64] dark:text-[#9fd4d6]\"\n >\n {plan.name}\n \n ))}\n \n\n
\n
\n

\n Subscription\n

\n

\n {currency}\n \n \n {isYearly ? '/year' : '/month'}\n \n

\n
\n\n \n {plans.map((plan, index) => (\n {\n descriptionRefs.current[plan.id] = el ?? undefined;\n }}\n className={cn(\n 'col-start-1 row-start-1 text-sm text-[#045f64]/70 dark:text-[#9fd4d6]/80',\n index !== 0 && 'opacity-0'\n )}\n >\n {plan.description}\n

\n ))}\n
\n
\n\n \n {ctaText}\n \n \n
\n\n
\n

\n What's included:\n

\n
    \n {features.map((feature, index) => {\n const isActive = index < (currentPlan?.includedCount ?? 0);\n return (\n
  • \n \n \n \n \n {feature}\n \n
  • \n );\n })}\n
\n
\n
\n
\n \n
\n );\n};\n\nexport default PricingPlanSwitch;\n", diff --git a/apps/docs/registry/demos/ink-stroke-button.tsx b/apps/docs/registry/demos/ink-stroke-button.tsx new file mode 100644 index 0000000..d8e4ca1 --- /dev/null +++ b/apps/docs/registry/demos/ink-stroke-button.tsx @@ -0,0 +1,13 @@ +'use client'; + +import InkStrokeButton from '@/registry/tweenui/ink-stroke-button'; + +const InkStrokeButtonDemo = () => { + return ( +
+ Start a project +
+ ); +}; + +export default InkStrokeButtonDemo; diff --git a/apps/docs/registry/registry-ui.ts b/apps/docs/registry/registry-ui.ts index 48cf8a0..6c54cb4 100644 --- a/apps/docs/registry/registry-ui.ts +++ b/apps/docs/registry/registry-ui.ts @@ -1024,6 +1024,39 @@ export default function Example() { suggestions={['Pixel Fill Button', 'Glow Button', 'Sliding Tabs', 'Morphing Text']} /> ); +}`, + }, + }, + { + name: 'ink-stroke-button', + type: 'component', + addedAt: '2026-11-08', + title: 'Ink Stroke Button', + description: + 'A teal button with lime ink that flows under the cursor. The ink is a small fluid simulation in WebGL: a pool floods in from whichever edge the cursor crosses, the ink is pushed along the way you move, curls aside when you stop and fades back to teal in about a second. The label flips colour under the ink.', + media: {}, + dependencies: ['gsap', '@gsap/react'], + registryDependencies: [], + cssVars: {}, + files: [ + { + path: 'registry/tweenui/ink-stroke-button.tsx', + target: 'components/tweenui/ink-stroke-button.tsx', + kind: 'react', + }, + ], + variants: [ + { + id: 'default', + label: 'Preview', + reactSource: 'registry/tweenui/ink-stroke-button.tsx', + }, + ], + usage: { + react: `import InkStrokeButton from '@/components/tweenui/ink-stroke-button'; + +export default function Example() { + return {}}>Start a project; }`, }, }, diff --git a/apps/docs/registry/tweenui/ink-stroke-button.tsx b/apps/docs/registry/tweenui/ink-stroke-button.tsx new file mode 100644 index 0000000..a9439b3 --- /dev/null +++ b/apps/docs/registry/tweenui/ink-stroke-button.tsx @@ -0,0 +1,716 @@ +'use client'; + +import { useRef, useState, type ComponentPropsWithRef } from 'react'; +import { useGSAP } from '@gsap/react'; +import gsap from 'gsap'; +import { cn } from '@/lib/utils'; + +gsap.registerPlugin(useGSAP); + +type Rgb = [number, number, number]; +const TEAL: Rgb = [4 / 255, 95 / 255, 100 / 255]; +const LIME: Rgb = [198 / 255, 245 / 255, 111 / 255]; + +// Brush: the ink that trails the cursor. +const RADIUS = 0.52; // dab size, in button heights +const FOLLOW = 0.08; // seconds the brush lags the pointer; the lag is the glide +const INK_PER_PX = 0.06; // ink per pixel moved, so circling builds up more +const INK_MAX = 1.6; +const INK_FADE = 1.6; // ink lost per second +const PUSH = 0.15; // share of the pointer's speed handed to the fluid +const FLOW_FADE = 2.5; // motion lost per second + +// Pool: the ink that floods in when the cursor crosses an edge. +const POOL_X = 0.28; // from a side: reach in, in widths +const POOL_Y = 1; // from a side: height, in heights; 1 fills top to bottom +const POOL_SPAN = 0.22; // from top or bottom: half its width, in widths +const POOL_DEPTH = 0.8; // from top or bottom: reach in, in heights +const POOL_INK = 1.6; +const POOL_FADE = 2.4; // lost per second, apart from the brush's ink +const POOL_GROW = 0.88; // seconds to spread in +const POOL_GAP = 0.35; // shortest time between two pools + +// Solver. +const CELL = 3; // simulation cell size, in CSS pixels +const PRESSURE_STEPS = 12; +const PRESSURE_KEEP = 0.8; // last frame's pressure, reused as a head start +const IDLE_AFTER = 3.5; // seconds without new ink before the loop sleeps + +const VERTEX = `#version 300 es +in vec2 aPos; +out vec2 vUv; +void main() { + vUv = aPos * 0.5 + 0.5; + gl_Position = vec4(aPos, 0.0, 1.0); +}`; + +const head = `#version 300 es +precision highp float; +in vec2 vUv; +out vec4 outColor; +`; + +// Adds a soft dab. Ink has two layers: x is the brush, which builds up to a +// cap, and y the pools, which keep the highest dab so their edge stays soft. +const SPLAT = `${head} +uniform sampler2D uTarget; +uniform vec2 uPoint; +uniform vec2 uValue; +uniform float uRadius; +uniform float uAspect; +uniform float uShape; +uniform float uMax; +uniform float uInk; +void main() { + vec2 d = vUv - uPoint; + d.x *= uAspect; + float dab = exp(-pow(dot(d, d) / uRadius, uShape)); + vec4 base = texture(uTarget, vUv); + outColor = uInk > 0.5 + ? vec4(min(base.x + dab * uValue.x, uMax), max(base.y, dab * uValue.y), 0.0, 1.0) + : vec4(base.xy + dab * uValue, 0.0, 1.0); +}`; + +// Moves a field along the velocity and fades it: ink by a fixed amount a +// second, motion in proportion. +const ADVECT = `${head} +uniform sampler2D uVelocity; +uniform sampler2D uSource; +uniform vec2 uCell; +uniform float uDt; +uniform vec4 uFade; +uniform float uInk; +void main() { + vec2 from = vUv - uDt * texture(uVelocity, vUv).xy * uCell; + vec4 value = texture(uSource, from); + // Nothing flows in from outside, so teal washes back in behind the ink. + vec2 edge = min(from, 1.0 - from) / (uCell * 0.75); + vec4 carried = value * clamp(min(edge.x, edge.y), 0.0, 1.0); + if (uInk > 0.5) { + carried.y = value.y; // pools sit against the edge, so they keep it + outColor = max(carried - uFade * uDt, 0.0); + } else { + outColor = carried / (1.0 + uFade * uDt); + } +}`; + +// The cell to the left, right, below and above, for the three passes below. +const neighbours = `${head} +uniform vec2 uCell; +vec4 L(sampler2D s) { return texture(s, vUv - vec2(uCell.x, 0.0)); } +vec4 R(sampler2D s) { return texture(s, vUv + vec2(uCell.x, 0.0)); } +vec4 B(sampler2D s) { return texture(s, vUv - vec2(0.0, uCell.y)); } +vec4 T(sampler2D s) { return texture(s, vUv + vec2(0.0, uCell.y)); } +`; + +const DIVERGENCE = `${neighbours} +uniform sampler2D uVelocity; +void main() { + float div = R(uVelocity).x - L(uVelocity).x + T(uVelocity).y - B(uVelocity).y; + outColor = vec4(0.5 * div, 0.0, 0.0, 1.0); +}`; + +// One relaxation pass. uKeep scales the neighbours: PRESSURE_KEEP on the first +// pass, so it starts from most of last frame's pressure, then 1. +const PRESSURE = `${neighbours} +uniform sampler2D uPressure; +uniform sampler2D uDivergence; +uniform float uKeep; +void main() { + float sum = L(uPressure).x + R(uPressure).x + B(uPressure).x + T(uPressure).x; + outColor = vec4((sum * uKeep - texture(uDivergence, vUv).x) * 0.25, 0.0, 0.0, 1.0); +}`; + +const GRADIENT = `${neighbours} +uniform sampler2D uPressure; +uniform sampler2D uVelocity; +void main() { + vec2 grad = vec2(R(uPressure).x - L(uPressure).x, T(uPressure).x - B(uPressure).x); + outColor = vec4(texture(uVelocity, vUv).xy - 0.5 * grad, 0.0, 1.0); +}`; + +// Shows the ink as a soft threshold, so the lime has an edge, and flips the +// label's colours under it. +const DISPLAY = `${head} +uniform sampler2D uInk; +uniform sampler2D uLabel; +uniform vec3 uBase; +uniform vec3 uFill; +void main() { + vec2 ink = texture(uInk, vUv).xy; + float k = smoothstep(0.3, 0.72, ink.x + ink.y); + vec3 surface = mix(uBase, uFill, k); + vec3 text = mix(uFill, uBase, k); + outColor = vec4(mix(surface, text, texture(uLabel, vUv).a), 1.0); +}`; + +const prefersReducedMotion = () => + typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + +// Where a move from a (outside) to b (inside) crossed into a w×h box, and +// whether it came in through a side rather than the top or bottom. +const entryPoint = (ax: number, ay: number, bx: number, by: number, w: number, h: number) => { + const tx = ax < 0 ? -ax / (bx - ax) : ax > w ? (ax - w) / (ax - bx) : -1; + const ty = ay < 0 ? -ay / (by - ay) : ay > h ? (ay - h) / (ay - by) : -1; + const t = Math.max(tx, ty); + return { x: ax + (bx - ax) * t, y: ay + (by - ay) * t, side: tx >= ty }; +}; + +const isFocusVisible = (el: Element) => { + try { + return el.matches(':focus-visible'); + } catch { + return true; + } +}; + +type Gl = WebGL2RenderingContext; +type Target = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number }; +type Pair = { read: Target; write: Target; swap: () => void }; +type Program = { use: () => void; set: Record }; + +const program = (gl: Gl, fragment: string): Program | null => { + const prog = gl.createProgram(); + if (!prog) return null; + for (const [type, source] of [ + [gl.VERTEX_SHADER, VERTEX], + [gl.FRAGMENT_SHADER, fragment], + ] as const) { + const shader = gl.createShader(type); + if (!shader) return null; + gl.shaderSource(shader, source); + gl.compileShader(shader); + gl.attachShader(prog, shader); + gl.deleteShader(shader); // freed with the program + } + gl.bindAttribLocation(prog, 0, 'aPos'); + gl.linkProgram(prog); + if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null; + const set: Program['set'] = {}; + const count = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number; + for (let i = 0; i < count; i += 1) { + const name = gl.getActiveUniform(prog, i)?.name; + if (name) set[name] = gl.getUniformLocation(prog, name); + } + return { use: () => gl.useProgram(prog), set }; +}; + +const free = (gl: Gl, ...items: (Target | Pair | null)[]) => { + for (const item of items) { + if (!item) continue; + for (const t of 'read' in item ? [item.read, item.write] : [item]) { + gl.deleteTexture(t.tex); + gl.deleteFramebuffer(t.fbo); + } + } +}; + +// A half-float texture to draw into. Null if the device can't render to one. +const target = (gl: Gl, w: number, h: number): Target | null => { + const tex = gl.createTexture(); + const fbo = gl.createFramebuffer(); + if (!tex || !fbo) return null; + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); + const t = { tex, fbo, w, h }; + if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { + free(gl, t); + return null; + } + gl.clearColor(0, 0, 0, 1); + gl.clear(gl.COLOR_BUFFER_BIT); + return t; +}; + +// Two targets to read from one while writing the other, then swap. +const pair = (gl: Gl, w: number, h: number): Pair | null => { + const a = target(gl, w, h); + const b = target(gl, w, h); + if (!a || !b) { + free(gl, a, b); + return null; + } + const p: Pair = { + read: a, + write: b, + swap: () => { + [p.read, p.write] = [p.write, p.read]; + }, + }; + return p; +}; + +type Stroke = { x: number; y: number; vx: number; vy: number; moved: number }; + +type Renderer = { + /** Fits the canvas to the button. False if the device can't run it. */ + resize: () => boolean; + step: (dt: number, stroke: Stroke | null) => void; + /** A pool at (x, y) reaching rx widths across and ry heights up and down. */ + pool: (x: number, y: number, rx: number, ry: number, size: number) => void; + dispose: () => void; +}; + +// A small stable-fluids solver. The pointer pushes motion and drops ink, a few +// pressure passes keep the motion swirling rather than piling up, and both are +// carried along and fade. +const createRenderer = ( + canvas: HTMLCanvasElement, + button: HTMLElement, + label: HTMLElement +): Renderer | null => { + const gl = canvas.getContext('webgl2', { + alpha: false, + antialias: false, + depth: false, + stencil: false, + // A button never needs the discrete GPU; don't wake it on dual-GPU laptops. + powerPreference: 'low-power', + }); + if (!gl) return null; + gl.getExtension('EXT_color_buffer_float'); + gl.getExtension('EXT_color_buffer_half_float'); + const dispose = () => gl.getExtension('WEBGL_lose_context')?.loseContext(); + + const sources = [SPLAT, ADVECT, DIVERGENCE, PRESSURE, GRADIENT, DISPLAY]; + const programs = sources.map((source) => program(gl, source)); + if (programs.some((p) => !p)) { + dispose(); + return null; + } + const [splatP, advectP, divergenceP, pressureP, gradientP, displayP] = programs as Program[]; + + // One quad covering the target; every pass draws it. + gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW); + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0); + + const labelTex = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, labelTex); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + const text = document.createElement('canvas'); + + let velocity: Pair | null = null; + let pressure: Pair | null = null; + let divergence: Target | null = null; + let ink: Pair | null = null; + // Button size in CSS pixels, and canvas size in device pixels. + let cssW = 1; + let cssH = 1; + let width = 1; + let height = 1; + let dpr = 1; + + const draw = (to: Target | null) => { + gl.bindFramebuffer(gl.FRAMEBUFFER, to ? to.fbo : null); + gl.viewport(0, 0, to ? to.w : width, to ? to.h : height); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + }; + + const bind = (unit: number, tex: WebGLTexture | null) => { + gl.activeTexture(gl.TEXTURE0 + unit); + gl.bindTexture(gl.TEXTURE_2D, tex); + return unit; + }; + + // Adds a dab to a field at (x, y) in button pixels. The radius is in button + // heights; aspect stretches it across. + const splat = ( + field: Pair, + x: number, + y: number, + value: [number, number], + { + radius, + aspect, + shape, + isInk, + }: { radius: number; aspect: number; shape: number; isInk: boolean } + ) => { + splatP.use(); + gl.uniform1i(splatP.set.uTarget, bind(0, field.read.tex)); + gl.uniform2f(splatP.set.uPoint, x / cssW, 1 - y / cssH); + gl.uniform2f(splatP.set.uValue, ...value); + gl.uniform1f(splatP.set.uRadius, radius * radius); + gl.uniform1f(splatP.set.uAspect, aspect); + gl.uniform1f(splatP.set.uShape, shape); + gl.uniform1f(splatP.set.uMax, INK_MAX); + gl.uniform1f(splatP.set.uInk, isInk ? 1 : 0); + draw(field.write); + field.swap(); + }; + + const advect = (field: Pair, cell: readonly [number, number], dt: number, fade: Rgb) => { + if (!velocity) return; + const isInk = field === ink; + advectP.use(); + gl.uniform1i(advectP.set.uVelocity, bind(0, velocity.read.tex)); + gl.uniform1i(advectP.set.uSource, bind(1, field.read.tex)); + gl.uniform2f(advectP.set.uCell, ...cell); + gl.uniform1f(advectP.set.uDt, dt); + gl.uniform4f(advectP.set.uFade, ...fade, 0); + gl.uniform1f(advectP.set.uInk, isInk ? 1 : 0); + draw(field.write); + field.swap(); + }; + + // The DOM label stays for assistive tech; its pixels are drawn here so the + // shader can recolour them under the ink. + const drawLabel = () => { + const ctx = text.getContext('2d'); + if (!ctx) return; + text.width = width; + text.height = height; + const style = getComputedStyle(label); + ctx.font = `${style.fontStyle} ${style.fontWeight} ${parseFloat(style.fontSize) * dpr}px ${style.fontFamily}`; + if ('letterSpacing' in ctx) { + ctx.letterSpacing = `${(parseFloat(style.letterSpacing) || 0) * dpr}px`; + } + const words = label.textContent ?? ''; + const metrics = ctx.measureText(words); + // Font box metrics arrived in Firefox 116; the glyph box is close enough. + const ascent = metrics.fontBoundingBoxAscent ?? metrics.actualBoundingBoxAscent; + const descent = metrics.fontBoundingBoxDescent ?? metrics.actualBoundingBoxDescent; + const gap = (label.offsetHeight * dpr - (ascent + descent)) / 2; + ctx.fillStyle = '#fff'; + ctx.fillText(words, label.offsetLeft * dpr, label.offsetTop * dpr + gap + ascent); + gl.bindTexture(gl.TEXTURE_2D, labelTex); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, text); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + }; + + const show = () => { + if (!ink) return; + displayP.use(); + gl.uniform1i(displayP.set.uInk, bind(0, ink.read.tex)); + gl.uniform1i(displayP.set.uLabel, bind(1, labelTex)); + gl.uniform3fv(displayP.set.uBase, TEAL); + gl.uniform3fv(displayP.set.uFill, LIME); + draw(null); + }; + + return { + resize: () => { + cssW = Math.max(1, button.offsetWidth); + cssH = Math.max(1, button.offsetHeight); + dpr = Math.min(window.devicePixelRatio || 1, 2); + width = Math.round(cssW * dpr); + height = Math.round(cssH * dpr); + canvas.width = width; + canvas.height = height; + + free(gl, velocity, pressure, divergence, ink); + const simW = Math.max(8, Math.round(cssW / CELL)); + const simH = Math.max(8, Math.round(cssH / CELL)); + velocity = pair(gl, simW, simH); + pressure = pair(gl, simW, simH); + divergence = target(gl, simW, simH); + ink = pair(gl, Math.max(8, cssW), Math.max(8, cssH)); + if (!velocity || !pressure || !divergence || !ink) return false; + + drawLabel(); + show(); + return true; + }, + + step: (dt, stroke) => { + if (!velocity || !pressure || !divergence || !ink) return; + const cell = [1 / velocity.read.w, 1 / velocity.read.h] as const; + + if (stroke) { + const brush = { radius: RADIUS, aspect: cssW / cssH, shape: 1 }; + const push: [number, number] = [(stroke.vx / CELL) * PUSH, (-stroke.vy / CELL) * PUSH]; + splat(velocity, stroke.x, stroke.y, push, { ...brush, isInk: false }); + splat(ink, stroke.x, stroke.y, [stroke.moved * INK_PER_PX, 0], { ...brush, isInk: true }); + } + + // Pressure: start from most of last frame's, then relax it. + divergenceP.use(); + gl.uniform2f(divergenceP.set.uCell, ...cell); + gl.uniform1i(divergenceP.set.uVelocity, bind(0, velocity.read.tex)); + draw(divergence); + + pressureP.use(); + gl.uniform2f(pressureP.set.uCell, ...cell); + gl.uniform1i(pressureP.set.uDivergence, bind(1, divergence.tex)); + for (let i = 0; i < PRESSURE_STEPS; i += 1) { + gl.uniform1f(pressureP.set.uKeep, i === 0 ? PRESSURE_KEEP : 1); + gl.uniform1i(pressureP.set.uPressure, bind(0, pressure.read.tex)); + draw(pressure.write); + pressure.swap(); + } + + gradientP.use(); + gl.uniform2f(gradientP.set.uCell, ...cell); + gl.uniform1i(gradientP.set.uPressure, bind(0, pressure.read.tex)); + gl.uniform1i(gradientP.set.uVelocity, bind(1, velocity.read.tex)); + draw(velocity.write); + velocity.swap(); + + advect(velocity, cell, dt, [FLOW_FADE, FLOW_FADE, 0]); + advect(ink, cell, dt, [INK_FADE, POOL_FADE, 0]); + show(); + }, + + pool: (x, y, rx, ry, size) => { + if (!ink) return; + // Measured in heights, so squeeze x to reach rx of the width. + splat(ink, x, y, [0, POOL_INK], { + radius: ry * size, + aspect: ry / rx, + shape: 2, + isInk: true, + }); + }, + + dispose, + }; +}; + +export interface InkStrokeButtonProps extends ComponentPropsWithRef<'button'> { + children: string; +} + +const InkStrokeButton = ({ + children, + className, + type = 'button', + ref, + ...props +}: InkStrokeButtonProps) => { + const btnRef = useRef(null); + const canvasRef = useRef(null); + const labelRef = useRef(null); + const [live, setLive] = useState(false); + + const setRef = (node: HTMLButtonElement | null) => { + btnRef.current = node; + if (typeof ref === 'function') ref(node); + else if (ref) ref.current = node; + }; + + useGSAP( + () => { + const btn = btnRef.current; + const canvas = canvasRef.current; + const label = labelRef.current; + if (!btn || !canvas || !label) return; + + let renderer: Renderer | null = null; + let ticking = false; + let lastInk = -Infinity; + let sweep: gsap.core.Tween | null = null; + // All positions are in the button's own pixels. The pointer is tracked + // across the page, so the ink is ready as the cursor arrives. + const pointer = { x: 0, y: 0, known: false }; + const brush = { x: 0, y: 0 }; + const pool = { x: 0, y: 0, rx: POOL_X, ry: POOL_Y, at: -Infinity }; + + const near = (x: number, y: number, margin: number) => + x > -margin && y > -margin && x < btn.offsetWidth + margin && y < btn.offsetHeight + margin; + + const stop = () => { + gsap.ticker.remove(tick); + ticking = false; + }; + + function tick(time: number, deltaTime: number) { + if (!renderer || !btn) return stop(); + const dt = Math.min(deltaTime / 1000, 1 / 30); + + // The brush eases after the pointer, which is what makes the ink glide. + const ease = 1 - Math.exp(-dt / FOLLOW); + const x = brush.x + (pointer.x - brush.x) * ease; + const y = brush.y + (pointer.y - brush.y) * ease; + const dx = x - brush.x; + const dy = y - brush.y; + const moved = Math.hypot(dx, dy); + const painting = + pointer.known && moved > 0.2 && near(x, y, btn.offsetHeight * RADIUS * 0.6); + brush.x = x; + brush.y = y; + + // A new pool eases out from 15% to full size. + const grown = (time - pool.at) / POOL_GROW; + if (grown < 1) + renderer.pool(pool.x, pool.y, pool.rx, pool.ry, 0.15 + 0.85 * (1 - (1 - grown) ** 3)); + + renderer.step(dt, painting ? { x, y, vx: dx / dt, vy: dy / dt, moved } : null); + if (painting || grown < 1) lastInk = time; + // Sleep once the ink has faded; the next move wakes it. + if (!sweep?.isActive() && time - lastInk > IDLE_AFTER) stop(); + } + + const wake = () => { + if (ticking || !renderer) return; + ticking = true; + gsap.ticker.add(tick); + }; + + const onMove = (event: PointerEvent) => { + if (event.pointerType === 'touch' || !renderer || btn.disabled) return; + const box = btn.getBoundingClientRect(); + const scale = box.width / btn.offsetWidth || 1; + const x = (event.clientX - box.left) / scale; + const y = (event.clientY - box.top) / scale; + + // Coming in over an edge floods a pool in from that edge. Through a + // side it fills a full-height band; through the top or bottom it + // spreads from where the cursor crossed. + const now = gsap.ticker.time; + const entered = pointer.known && near(x, y, 0) && !near(pointer.x, pointer.y, 0); + if (entered && now - pool.at > POOL_GAP) { + const w = btn.offsetWidth; + const h = btn.offsetHeight; + const at = entryPoint(pointer.x, pointer.y, x, y, w, h); + Object.assign( + pool, + at.side + ? { x: at.x < w / 2 ? 0 : w, y: h / 2, rx: POOL_X, ry: POOL_Y } + : { + x: Math.min(Math.max(at.x, 0), w), + y: at.y < h / 2 ? 0 : h, + rx: POOL_SPAN, + ry: POOL_DEPTH, + }, + { at: now } + ); + } + + // A sleeping brush starts where the pointer was, not where it rested. + if (!pointer.known || !ticking) { + brush.x = pointer.known ? pointer.x : x; + brush.y = pointer.known ? pointer.y : y; + } + Object.assign(pointer, { x, y, known: true }); + if (near(x, y, btn.offsetHeight * RADIUS * 2)) wake(); + }; + + // Chrome sends pointer events to disabled buttons, so skip those. + const onHover = (event: PointerEvent) => { + btn.dataset.active = String(event.type === 'pointerenter' && !btn.disabled); + }; + + // A keyboard user has no cursor, so focus sweeps one across for them. + const onFocus = () => { + if (!isFocusVisible(btn)) return; + btn.dataset.active = 'true'; + if (!renderer) return; + sweep?.kill(); + const y = btn.offsetHeight / 2; + Object.assign(pointer, { x: -btn.offsetHeight * 0.4, y, known: true }); + Object.assign(brush, { x: pointer.x, y }); + wake(); + sweep = gsap.to(pointer, { x: btn.offsetWidth * 0.75, duration: 0.6, ease: 'power2.out' }); + }; + const onBlur = () => { + if (!btn.matches(':hover')) btn.dataset.active = 'false'; + }; + + // Without WebGL the CSS colour swap takes over (data-live=false). + const fallBack = () => { + stop(); + renderer?.dispose(); + renderer = null; + setLive(false); + }; + const fit = () => { + if (renderer && !renderer.resize()) fallBack(); + }; + const resize = new ResizeObserver(fit); + + const start = () => { + if (renderer || prefersReducedMotion()) return; + renderer = createRenderer(canvas, btn, label); + if (!renderer) return; + if (!renderer.resize()) return fallBack(); + setLive(true); + resize.observe(btn); + // The label too: new text in a fixed-width button must be redrawn. + resize.observe(label); + document.fonts?.ready.then(fit); + }; + + // Not restored: the CSS fallback takes over for the rest of the visit. + const onLost = () => { + stop(); + renderer = null; + setLive(false); + }; + + // Contexts are limited per page, so one is only made once on screen. + const visible = + typeof IntersectionObserver === 'undefined' + ? null + : new IntersectionObserver((entries) => { + if (entries.some((entry) => entry.isIntersecting)) { + visible?.disconnect(); + start(); + } + }); + if (visible) visible.observe(btn); + else start(); + + window.addEventListener('pointermove', onMove, { passive: true }); + btn.addEventListener('pointerenter', onHover); + btn.addEventListener('pointerleave', onHover); + btn.addEventListener('focus', onFocus); + btn.addEventListener('blur', onBlur); + canvas.addEventListener('webglcontextlost', onLost); + return () => { + window.removeEventListener('pointermove', onMove); + btn.removeEventListener('pointerenter', onHover); + btn.removeEventListener('pointerleave', onHover); + btn.removeEventListener('focus', onFocus); + btn.removeEventListener('blur', onBlur); + canvas.removeEventListener('webglcontextlost', onLost); + visible?.disconnect(); + resize.disconnect(); + sweep?.kill(); + stop(); + renderer?.dispose(); + renderer = null; // so a late fonts.ready finds nothing to resize + }; + }, + { scope: btnRef } + ); + + return ( + + ); +}; + +export default InkStrokeButton; diff --git a/apps/docs/tests/ink-stroke-button.test.tsx b/apps/docs/tests/ink-stroke-button.test.tsx new file mode 100644 index 0000000..73607e1 --- /dev/null +++ b/apps/docs/tests/ink-stroke-button.test.tsx @@ -0,0 +1,72 @@ +import { createRef } from 'react'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import InkStrokeButton from '@/registry/tweenui/ink-stroke-button'; + +const setReducedMotion = (reduce: boolean) => { + window.matchMedia = vi.fn().mockImplementation((query: string) => ({ + matches: query.includes('reduce') ? reduce : false, + media: query, + onchange: null, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + addListener: vi.fn(), + removeListener: vi.fn(), + dispatchEvent: vi.fn(), + })) as unknown as typeof window.matchMedia; +}; + +describe('Ink Stroke Button', () => { + beforeEach(() => setReducedMotion(true)); + afterEach(() => vi.restoreAllMocks()); + + it('renders a button named by its label', () => { + render(Start a project); + const button = screen.getByRole('button', { name: 'Start a project' }); + expect(button).toHaveAttribute('type', 'button'); + }); + + it('forwards the ref and native attributes', () => { + const ref = createRef(); + render( + + Start a project + + ); + expect(ref.current).toBe(screen.getByRole('button')); + expect(ref.current).toBeDisabled(); + }); + + it('hides the canvas from assistive tech and keeps the label readable', () => { + render(Start a project); + expect(document.querySelector('canvas')).toHaveAttribute('aria-hidden', 'true'); + expect(screen.getByText('Start a project')).not.toHaveClass('text-transparent'); + }); + + it('falls back to a plain colour swap without WebGL', () => { + render(Start a project); + expect(screen.getByRole('button')).toHaveAttribute('data-live', 'false'); + }); + + it('marks the hover and keyboard focus state for the fallback', () => { + render(Start a project); + const button = screen.getByRole('button'); + + fireEvent.pointerEnter(button, { pointerType: 'mouse' }); + expect(button).toHaveAttribute('data-active', 'true'); + fireEvent.pointerLeave(button, { pointerType: 'mouse' }); + expect(button).toHaveAttribute('data-active', 'false'); + + act(() => button.focus()); + expect(button).toHaveAttribute('data-active', 'true'); + act(() => button.blur()); + expect(button).toHaveAttribute('data-active', 'false'); + }); + + it('stays inactive on hover while disabled', () => { + render(Start a project); + const button = screen.getByRole('button'); + fireEvent.pointerEnter(button, { pointerType: 'mouse' }); + expect(button).toHaveAttribute('data-active', 'false'); + }); +});