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 1fc2569..e4643b5 100644 --- a/apps/docs/public/r/registry.json +++ b/apps/docs/public/r/registry.json @@ -731,6 +731,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 ca94b8d..25c7805 100644 --- a/apps/docs/registry/__index__.generated.tsx +++ b/apps/docs/registry/__index__.generated.tsx @@ -48,6 +48,7 @@ export const demos: Record = { 'theme-toggle-reveal:spiral': dynamic(() => import('./demos/theme-toggle-reveal-spiral')), 'elastic-slider:default': dynamic(() => import('./demos/elastic-slider')), 'package-command:default': dynamic(() => import('./demos/package-command')), + '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 8106c15..575ae59 100644 --- a/apps/docs/registry/__sources__.generated.ts +++ b/apps/docs/registry/__sources__.generated.ts @@ -187,6 +187,12 @@ export const usage: Record = { "codeHtml": "
import PackageCommand from '@/components/tweenui/package-command';\n\nexport default function Example() {\n  return <PackageCommand packages={['gsap', '@gsap/react']} />;\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}", @@ -592,6 +598,12 @@ export const manual: Record = { "codeHtml": "
'use client';\n\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ComponentPropsWithoutRef,\n  type KeyboardEvent,\n} from 'react';\nimport { useGSAP } from '@gsap/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\nexport const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const;\n\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number];\n\nexport type PackageCommandKind = 'install' | 'execute';\n\nconst STORAGE_KEY = 'tweenui:package-manager';\nconst COPIED_FOR = 1600;\n\nconst listeners = new Set<() => void>();\nlet chosen: PackageManager | null = null;\nlet chosenByUser = false;\n\nconst toManager = (value: unknown) => PACKAGE_MANAGERS.find((manager) => manager === value);\n\nconst readManager = (): PackageManager => {\n  if (chosen) return chosen;\n  try {\n    chosen = toManager(window.localStorage.getItem(STORAGE_KEY)) ?? 'npm';\n  } catch {\n    chosen = 'npm';\n  }\n  return chosen;\n};\n\nconst chooseManager = (manager: PackageManager) => {\n  if (manager === chosen) return;\n  chosen = manager;\n  chosenByUser = true;\n  try {\n    window.localStorage.setItem(STORAGE_KEY, manager);\n  } catch {}\n  listeners.forEach((listener) => listener());\n};\n\nconst subscribe = (listener: () => void) => {\n  const onStorage = (event: StorageEvent) => {\n    if (event.key !== STORAGE_KEY) return;\n    const next = toManager(event.newValue);\n    if (!next || next === chosen) return;\n    chosen = next;\n    chosenByUser = true;\n    listeners.forEach((each) => each());\n  };\n  listeners.add(listener);\n  window.addEventListener('storage', onStorage);\n  return () => {\n    listeners.delete(listener);\n    window.removeEventListener('storage', onStorage);\n  };\n};\n\nconst prefersReducedMotion = () =>\n  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nconst runner = (manager: PackageManager, kind: PackageCommandKind, dev: boolean) => {\n  if (kind === 'execute') {\n    if (manager === 'npm') return 'npx';\n    if (manager === 'bun') return 'bunx';\n    return `${manager} dlx`;\n  }\n  const verb = manager === 'npm' ? 'npm install' : `${manager} add`;\n  return dev ? `${verb} -D` : verb;\n};\n\nconst splitHead = (head: string) => {\n  const space = head.indexOf(' ');\n  return space === -1 ? [head, ''] : [head.slice(0, space), head.slice(space)];\n};\n\nconst FlipCells = ({ from, to }: { from: string; to: string }) => (\n  <span className=\"relative inline-flex items-center [clip-path:inset(0_-100vw)]\">\n    {Array.from(to, (character, index) => (\n      <span\n        key={index}\n        data-in\n        data-changed={character !== from[index] || undefined}\n        className=\"block w-[1ch]\"\n      >\n        {character}\n      </span>\n    ))}\n    {Array.from(from, (character, index) =>\n      character === to[index] || character === ' ' ? null : (\n        <span\n          key={`out-${index}`}\n          data-out\n          style={{ left: `${index}ch` }}\n          className=\"absolute inset-y-0 block w-[1ch]\"\n        >\n          {character}\n        </span>\n      )\n    )}\n  </span>\n);\n\nconst ClipboardIcon = () => (\n  <svg viewBox=\"0 0 24 24\" className=\"size-4\" fill=\"none\" aria-hidden=\"true\">\n    <rect x=\"8\" y=\"3\" width=\"8\" height=\"4\" rx=\"1\" stroke=\"currentColor\" strokeWidth=\"1.75\" />\n    <path\n      d=\"M16 5h1.5A1.5 1.5 0 0 1 19 6.5v12a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 18.5v-12A1.5 1.5 0 0 1 6.5 5H8\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.75\"\n      strokeLinecap=\"round\"\n    />\n  </svg>\n);\n\nexport interface PackageCommandProps extends Omit<ComponentPropsWithoutRef<'div'>, 'onCopy'> {\n  packages: string | string[];\n  kind?: PackageCommandKind;\n  dev?: boolean;\n  managers?: readonly PackageManager[];\n  onCopy?: (command: string) => void;\n}\n\nconst PackageCommand = ({\n  packages,\n  kind = 'install',\n  dev = false,\n  managers = PACKAGE_MANAGERS,\n  onCopy,\n  className,\n  ...props\n}: PackageCommandProps) => {\n  const id = useId();\n  const panelId = `${id}-panel`;\n  const rootRef = useRef<HTMLDivElement>(null);\n  const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);\n  const pillRef = useRef<HTMLSpanElement>(null);\n  const tailRef = useRef<HTMLSpanElement>(null);\n  const listRef = useRef<HTMLSpanElement>(null);\n  const sweepRef = useRef<HTMLSpanElement>(null);\n  const clipboardRef = useRef<HTMLSpanElement>(null);\n  const checkRef = useRef<SVGSVGElement>(null);\n  const checkPathRef = useRef<SVGPathElement>(null);\n  const copyTimer = useRef<number | undefined>(undefined);\n  const flipTimeline = useRef<gsap.core.Timeline | null>(null);\n\n  const stored = useSyncExternalStore(subscribe, readManager, () => 'npm');\n  const manager = managers.find((each) => each === stored) ?? managers[0] ?? 'npm';\n  const activeIndex = Math.max(0, managers.indexOf(manager));\n  const list = Array.isArray(packages) ? packages.join(' ') : packages.trim();\n  const head = runner(manager, kind, dev);\n  const command = `${head} ${list}`;\n\n  const [flip, setFlip] = useState({ from: head, to: head });\n  const [copied, setCopied] = useState(false);\n\n  if (flip.to !== head) setFlip({ from: flip.to, to: head });\n\n  const [fromTool, fromTail] = splitHead(flip.from);\n  const [toTool, toTail] = splitHead(flip.to);\n\n  const { contextSafe } = useGSAP({ scope: rootRef });\n\n  const highlight = (index: number) => {\n    tabRefs.current.forEach((tab, each) => {\n      if (tab) tab.dataset.highlighted = String(each === index);\n    });\n  };\n\n  const movePill = (index: number, animate: boolean) => {\n    const tab = tabRefs.current[index];\n    if (!tab) return;\n    highlight(index);\n    const bounds = { x: tab.offsetLeft, width: tab.offsetWidth };\n    if (!animate || prefersReducedMotion()) {\n      gsap.killTweensOf(pillRef.current);\n      gsap.set(pillRef.current, bounds);\n      return;\n    }\n    gsap.to(pillRef.current, { ...bounds, duration: 0.35, ease: 'power2.out', overwrite: 'auto' });\n  };\n\n  const followPointer = contextSafe((target: EventTarget) => {\n    if (!(target instanceof Element)) return;\n    const tab = target.closest('[role=\"tab\"]');\n    const index = tabRefs.current.findIndex((each) => each === tab);\n    if (index !== -1) movePill(index, true);\n  });\n\n  const returnToActive = contextSafe(() => movePill(activeIndex, true));\n\n  useGSAP(\n    () => {\n      movePill(activeIndex, chosenByUser);\n    },\n    { scope: rootRef, dependencies: [activeIndex, managers.length] }\n  );\n\n  useEffect(() => {\n    const tablist = tabRefs.current[0]?.parentElement;\n    if (!tablist || typeof ResizeObserver === 'undefined') return;\n    const observer = new ResizeObserver(() => movePill(activeIndex, false));\n    observer.observe(tablist);\n    return () => observer.disconnect();\n  }, [activeIndex, managers]);\n\n  useGSAP(\n    () => {\n      if (flip.from === flip.to) {\n        gsap.set(\n          [tailRef.current, listRef.current, ...gsap.utils.toArray('[data-in]', rootRef.current)],\n          {\n            clearProps: 'transform,opacity',\n          }\n        );\n        return;\n      }\n      flipTimeline.current?.kill();\n      const root = rootRef.current;\n      const listElement = listRef.current;\n      const incoming = gsap.utils.toArray<HTMLElement>('[data-in]', root);\n      gsap.set(incoming, { yPercent: 0, opacity: 1 });\n      const settle = () => setFlip((current) => ({ from: current.to, to: current.to }));\n      if (!chosenByUser || prefersReducedMotion()) {\n        gsap.set([tailRef.current, listElement], { x: 0 });\n        settle();\n        return;\n      }\n      const charWidth = incoming[0]?.getBoundingClientRect().width ?? 0;\n      const timeline = gsap.timeline({ onComplete: settle });\n      flipTimeline.current = timeline;\n      const slide = (element: HTMLElement | null, shift: number) => {\n        const currentX = Number(gsap.getProperty(element, 'x')) || 0;\n        timeline.fromTo(\n          element,\n          { x: shift * charWidth + currentX },\n          { x: 0, duration: 0.55, ease: 'power3.inOut' },\n          0\n        );\n      };\n      slide(tailRef.current, fromTool.length - toTool.length);\n      slide(listElement, flip.from.length - flip.to.length);\n      timeline.fromTo(\n        gsap.utils.toArray<HTMLElement>('[data-out]', root),\n        { yPercent: 0, opacity: 1 },\n        { yPercent: -70, opacity: 0, duration: 0.2, ease: 'power2.in' },\n        0\n      );\n      incoming\n        .filter((element) => element.hasAttribute('data-changed'))\n        .forEach((element, order) => {\n          timeline.fromTo(\n            element,\n            { yPercent: 100, opacity: 0 },\n            { yPercent: 0, opacity: 1, duration: 0.42, ease: 'power3.out' },\n            order * 0.03 + 0.1\n          );\n        });\n    },\n    { scope: rootRef, dependencies: [flip.from, flip.to] }\n  );\n\n  useEffect(() => () => window.clearTimeout(copyTimer.current), []);\n\n  const select = (index: number, focus = false) => {\n    const next = managers[(index + managers.length) % managers.length];\n    if (!next) return;\n    chooseManager(next);\n    if (focus) tabRefs.current[managers.indexOf(next)]?.focus();\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {\n    const moves: Record<string, number> = {\n      ArrowRight: activeIndex + 1,\n      ArrowLeft: activeIndex - 1,\n      Home: 0,\n      End: managers.length - 1,\n    };\n    const target = moves[event.key];\n    if (target === undefined) return;\n    event.preventDefault();\n    select(target, true);\n  };\n\n  const playCopied = contextSafe(() => {\n    if (prefersReducedMotion()) {\n      gsap.set(clipboardRef.current, { opacity: 0 });\n      gsap.set(checkRef.current, { opacity: 1 });\n      gsap.set(checkPathRef.current, { strokeDashoffset: 0 });\n      return;\n    }\n    gsap\n      .timeline({ defaults: { overwrite: 'auto' } })\n      .to(clipboardRef.current, { scale: 0.6, opacity: 0, duration: 0.2, ease: 'power2.in' }, 0)\n      .set(checkRef.current, { opacity: 1 }, 0.12)\n      .fromTo(\n        checkPathRef.current,\n        { strokeDashoffset: 1 },\n        { strokeDashoffset: 0, duration: 0.4, ease: 'power3.out' },\n        0.12\n      )\n      .fromTo(\n        sweepRef.current,\n        { scaleX: 0, opacity: 1 },\n        { scaleX: 1, duration: 0.5, ease: 'power3.out' },\n        0\n      )\n      .to(sweepRef.current, { opacity: 0, duration: 0.5, ease: 'power2.out' }, 0.7);\n  });\n\n  const playReset = contextSafe(() => {\n    const reduced = prefersReducedMotion();\n    gsap.to(checkRef.current, { opacity: 0, duration: reduced ? 0 : 0.2, ease: 'power2.out' });\n    gsap.fromTo(\n      clipboardRef.current,\n      { scale: reduced ? 1 : 0.6 },\n      {\n        scale: 1,\n        opacity: 1,\n        duration: reduced ? 0 : 0.35,\n        ease: 'power3.out',\n        delay: reduced ? 0 : 0.1,\n      }\n    );\n  });\n\n  const copy = async () => {\n    try {\n      await navigator.clipboard.writeText(command);\n    } catch {\n      return;\n    }\n    onCopy?.(command);\n    setCopied(true);\n    playCopied();\n    window.clearTimeout(copyTimer.current);\n    copyTimer.current = window.setTimeout(() => {\n      setCopied(false);\n      playReset();\n    }, COPIED_FOR);\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      data-package-command\n      className={cn(\n        'w-full max-w-lg overflow-hidden rounded-xl border border-current/10 bg-current/[0.03] [--package-accent:#045f64] dark:[--package-accent:#c6f56f]',\n        className\n      )}\n      {...props}\n    >\n      <div className=\"flex items-center justify-between gap-3 border-b border-current/10 px-1.5 py-1.5\">\n        <div\n          role=\"tablist\"\n          aria-label=\"Package manager\"\n          className=\"relative flex\"\n          onPointerOver={(event) => followPointer(event.target)}\n          onPointerLeave={returnToActive}\n          onFocus={(event) => followPointer(event.target)}\n          onBlur={(event) => {\n            if (!event.currentTarget.contains(event.relatedTarget)) returnToActive();\n          }}\n        >\n          <span\n            ref={pillRef}\n            aria-hidden=\"true\"\n            className=\"absolute inset-y-0 left-0 rounded-md bg-current/[0.08]\"\n          />\n          {managers.map((each, index) => {\n            const selected = index === activeIndex;\n            return (\n              <button\n                key={each}\n                ref={(node) => {\n                  tabRefs.current[index] = node;\n                }}\n                id={`${id}-${each}`}\n                type=\"button\"\n                role=\"tab\"\n                aria-selected={selected}\n                aria-controls={panelId}\n                tabIndex={selected ? 0 : -1}\n                onClick={() => select(index)}\n                onKeyDown={handleKeyDown}\n                data-highlighted={selected}\n                className=\"relative cursor-pointer rounded-md px-3 py-1.5 font-mono text-xs opacity-55 transition-opacity duration-300 focus-visible:outline-2 focus-visible:outline-current data-[highlighted=true]:opacity-100 motion-reduce:transition-none\"\n              >\n                {each}\n              </button>\n            );\n          })}\n        </div>\n\n        <button\n          type=\"button\"\n          onClick={copy}\n          aria-label={copied ? 'Copied' : 'Copy command'}\n          className=\"relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-md opacity-70 transition-[opacity,background-color] duration-200 hover:bg-current/[0.08] hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-current\"\n        >\n          <span ref={clipboardRef} className=\"flex\">\n            <ClipboardIcon />\n          </span>\n          <svg\n            ref={checkRef}\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            aria-hidden=\"true\"\n            className=\"absolute size-4 text-(--package-accent) opacity-0\"\n          >\n            <path\n              ref={checkPathRef}\n              d=\"M5 12.5l4.5 4.5L19 7.5\"\n              pathLength={1}\n              stroke=\"currentColor\"\n              strokeWidth=\"2.25\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              strokeDasharray=\"1\"\n              strokeDashoffset=\"1\"\n            />\n          </svg>\n        </button>\n      </div>\n\n      <div\n        id={panelId}\n        role=\"tabpanel\"\n        aria-labelledby={`${id}-${manager}`}\n        className=\"overflow-x-auto px-4 py-3.5\"\n      >\n        <p className=\"relative inline-flex items-center font-mono text-sm leading-6 whitespace-pre\">\n          <span\n            ref={sweepRef}\n            aria-hidden=\"true\"\n            className=\"absolute -inset-x-1 -inset-y-0.5 origin-left scale-x-0 rounded bg-(--package-accent)/15\"\n          />\n          <span aria-hidden=\"true\" className=\"relative text-(--package-accent) select-none\">\n            ${' '}\n          </span>\n          <span aria-hidden=\"true\" className=\"relative inline-flex items-center\">\n            <FlipCells from={fromTool} to={toTool} />\n            <span ref={tailRef} className=\"inline-flex items-center\">\n              <FlipCells from={fromTail} to={toTail} />\n            </span>\n            <span ref={listRef} className=\"block opacity-70\">\n              {' '}\n              {list}\n            </span>\n          </span>\n          <span className=\"sr-only\">{command}</span>\n        </p>\n      </div>\n\n      <span role=\"status\" className=\"sr-only\">\n        {copied ? 'Copied to clipboard' : ''}\n      </span>\n    </div>\n  );\n};\n\nexport default PackageCommand;\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 5e80553..28eaca9 100644 --- a/apps/docs/registry/registry-ui.ts +++ b/apps/docs/registry/registry-ui.ts @@ -1182,6 +1182,39 @@ export default function Example() { export default function Example() { return ; +}`, + }, + }, + { + 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'); + }); +});