diff --git a/apps/docs/content/1.component/package-command.mdx b/apps/docs/content/1.component/package-command.mdx new file mode 100644 index 0000000..9210d13 --- /dev/null +++ b/apps/docs/content/1.component/package-command.mdx @@ -0,0 +1,100 @@ +--- +title: Package Command +description: An install command for npm, pnpm, yarn and bun where only the letters that change flip like a split-flap board. +icon: package +--- + +An install command in a small **terminal card**, with a tab for each +package manager. The pill **follows your pointer** across the tabs and slides back to the +selected one when you leave. When the command changes, only the **characters that differ flip**, +like a split-flap board: `pnpm add` to `yarn add` turns over four letters and +leaves ` add` alone. Copy it and a check **draws itself in** while a +selection sweeps across the line. The choice is **remembered**, and every +Package Command on the page follows it. Driven by GSAP. + +::component-preview{name="package-command"} +:: + +## Installation + +::tabs +:::tabs-item{label="CLI" icon="i-lucide-terminal"} + +::install-tabs{item="package-command"} +:: + +::: +:::tabs-item{label="Manual" icon="i-lucide-clipboard"} + +::component-source{name="package-command"} +:: + +::: +:: + +## Usage + +::tabs +:::tabs-item{label="React" icon="i-lucide-atom"} + +```tsx [app/page.tsx] +import PackageCommand from '@/components/tweenui/package-command'; + +export default function Page() { + return ( + <> + + + + + ); +} +``` + +::: +:: + +## How it moves + +- **Pill.** Slides under whichever tab you hover or focus and resizes to fit + it, 350ms on `power2.out`, and lights that label up. Leave the tabs and + it slides back to the selected one. +- **Command.** The text is laid out one monospace cell per character. Cells + that hold the same letter before and after stay still. The rest roll the + old letter up and out and the new one up from below, 30ms apart from left + to right. The line is laid out at its new length at once and the package + names slide in from where they were on `power3.inOut` over 550ms, using + only transforms, so nothing reflows mid-flip. +- **Copy.** The clipboard shrinks away, the check strokes itself in over + 400ms, and an accent band sweeps under the command and fades. After 1.6s + the clipboard returns. + +## Props + +| Prop | Type | Default | Description | +| ----------- | ------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------ | +| `packages` | `string \| string[]` | — | What to install, or with `kind="execute"` the command to run. | +| `kind` | `'install' \| 'execute'` | `'install'` | `install` gives `npm install` / `add`. `execute` gives `npx`, `pnpm dlx`, `yarn dlx` and `bunx`. | +| `dev` | `boolean` | `false` | Adds `-D` to an install. | +| `managers` | `PackageManager[]` | `['npm', 'pnpm', 'yarn', 'bun']` | Which tabs to show, in order. | +| `onCopy` | `(command) => void` | — | Called with the copied command. | +| `className` | `string` | — | Extra classes for the root. | + +The choice is saved to `localStorage` under `tweenui:package-manager` and +shared by every instance, including other open tabs. The server renders +`npm`, and the saved choice takes over after hydration without animating. +The accent comes from `--package-accent`. Override it with a class, e.g. +`[--package-accent:#e11d48]`. Everything else takes `currentColor`. + +## Accessibility + +::note +Under `prefers-reduced-motion: reduce` the pill jumps to the tab, the +command swaps without flipping and the check appears without drawing. +:: + +The tabs are a real `tablist` with one focusable tab. Arrow keys move and +wrap, and Home and End jump to the ends. The panel holds the full command as +text for screen readers, so they never hear it letter by letter. The copy +button is labelled "Copy command" and a status region announces "Copied to +clipboard". diff --git a/apps/docs/public/media/components/package-command-poster.webp b/apps/docs/public/media/components/package-command-poster.webp new file mode 100644 index 0000000..6dd1448 Binary files /dev/null and b/apps/docs/public/media/components/package-command-poster.webp differ diff --git a/apps/docs/public/media/components/package-command-preview.mp4 b/apps/docs/public/media/components/package-command-preview.mp4 new file mode 100644 index 0000000..663f8da Binary files /dev/null and b/apps/docs/public/media/components/package-command-preview.mp4 differ diff --git a/apps/docs/public/r/package-command-demo.json b/apps/docs/public/r/package-command-demo.json new file mode 100644 index 0000000..566ea5a --- /dev/null +++ b/apps/docs/public/r/package-command-demo.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://ui.shadcn.com/schema/registry-item.json", + "name": "package-command-demo", + "type": "registry:example", + "title": "Package Command Demo", + "description": "Usage examples for Package Command.", + "registryDependencies": [ + "https://tween-ui.vercel.app/r/package-command.json" + ], + "files": [ + { + "path": "examples/package-command-demo.tsx", + "type": "registry:example", + "content": "import PackageCommand from '@/components/tweenui/package-command';\n\nexport default function Page() {\n return (\n <>\n \n \n \n \n );\n}" + } + ] +} \ No newline at end of file diff --git a/apps/docs/public/r/package-command.json b/apps/docs/public/r/package-command.json new file mode 100644 index 0000000..ef26979 --- /dev/null +++ b/apps/docs/public/r/package-command.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://ui.shadcn.com/schema/registry-item.json", + "name": "package-command", + "type": "registry:ui", + "title": "Package Command", + "description": "An install command in npm, pnpm, yarn and bun inside a small terminal card. A pill slides between the tabs, and only the characters that differ between managers flip like a split-flap board. Copying draws a check and sweeps a selection across the line. The choice is remembered and every block on the page follows it.", + "dependencies": [ + "gsap", + "@gsap/react" + ], + "registryDependencies": [], + "cssVars": { + "theme": {} + }, + "files": [ + { + "path": "components/tweenui/package-command.tsx", + "type": "registry:component", + "target": "components/tweenui/package-command.tsx", + "content": "'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 \n {Array.from(to, (character, index) => (\n \n {character}\n \n ))}\n {Array.from(from, (character, index) =>\n character === to[index] || character === ' ' ? null : (\n \n {character}\n \n )\n )}\n \n);\n\nconst ClipboardIcon = () => (\n \n \n \n \n);\n\nexport interface PackageCommandProps extends Omit, '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(null);\n const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const pillRef = useRef(null);\n const tailRef = useRef(null);\n const listRef = useRef(null);\n const sweepRef = useRef(null);\n const clipboardRef = useRef(null);\n const checkRef = useRef(null);\n const checkPathRef = useRef(null);\n const copyTimer = useRef(undefined);\n const flipTimeline = useRef(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('[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('[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) => {\n const moves: Record = {\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 \n
\n 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 \n {managers.map((each, index) => {\n const selected = index === activeIndex;\n return (\n {\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 \n );\n })}\n
\n\n \n \n \n \n \n \n \n \n \n\n \n

\n \n \n ${' '}\n \n \n \n \n \n \n \n {' '}\n {list}\n \n \n {command}\n

\n \n\n \n {copied ? 'Copied to clipboard' : ''}\n \n \n );\n};\n\nexport default PackageCommand;\n" + } + ], + "docs": "Docs, props and examples: https://tween-ui.vercel.app/component/package-command" +} \ No newline at end of file diff --git a/apps/docs/public/r/registry.json b/apps/docs/public/r/registry.json index 83e2254..1fc2569 100644 --- a/apps/docs/public/r/registry.json +++ b/apps/docs/public/r/registry.json @@ -707,6 +707,30 @@ } ] }, + { + "name": "package-command", + "type": "registry:ui", + "title": "Package Command", + "description": "An install command in npm, pnpm, yarn and bun inside a small terminal card. A pill slides between the tabs, and only the characters that differ between managers flip like a split-flap board. Copying draws a check and sweeps a selection across the line. The choice is remembered and every block on the page follows it.", + "files": [ + { + "path": "components/tweenui/package-command.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "package-command-demo", + "type": "registry:example", + "title": "Package Command Demo", + "description": "Usage examples for Package Command.", + "files": [ + { + "path": "examples/package-command-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 3b02207..ca94b8d 100644 --- a/apps/docs/registry/__index__.generated.tsx +++ b/apps/docs/registry/__index__.generated.tsx @@ -47,6 +47,7 @@ export const demos: Record = { 'theme-toggle-reveal:sonar': dynamic(() => import('./demos/theme-toggle-reveal-sonar')), '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')), '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/__media__.generated.ts b/apps/docs/registry/__media__.generated.ts index 2ec5ee7..e74e724 100644 --- a/apps/docs/registry/__media__.generated.ts +++ b/apps/docs/registry/__media__.generated.ts @@ -36,6 +36,7 @@ export const discoveredMedia: Record = { 'morphing-search': {"image":"/media/components/morphing-search-poster.webp","video":"/media/components/morphing-search-preview.mp4"}, 'theme-toggle-reveal': {"image":"/media/components/theme-toggle-reveal-poster.webp","video":"/media/components/theme-toggle-reveal-preview.mp4"}, 'elastic-slider': {"image":"/media/components/elastic-slider-poster.webp","video":"/media/components/elastic-slider-preview.mp4"}, + 'package-command': {"image":"/media/components/package-command-poster.webp","video":"/media/components/package-command-preview.mp4"}, 'pricing-plan-switch': {"image":"/media/blocks/pricing-plan-switch-poster.webp","video":"/media/blocks/pricing-plan-switch-preview.mp4"}, 'process-card-reveal': {"image":"/media/blocks/process-card-reveal-poster.webp","video":"/media/blocks/process-card-reveal-preview.mp4"}, 'process-sticky-steps': {"image":"/media/blocks/process-sticky-steps-poster.webp","video":"/media/blocks/process-sticky-steps-preview.mp4"}, diff --git a/apps/docs/registry/__sources__.generated.ts b/apps/docs/registry/__sources__.generated.ts index ac434c9..8106c15 100644 --- a/apps/docs/registry/__sources__.generated.ts +++ b/apps/docs/registry/__sources__.generated.ts @@ -181,6 +181,12 @@ export const usage: Record = { "codeHtml": "
'use client';\n\nimport { useState } from 'react';\nimport ElasticSlider from '@/components/tweenui/elastic-slider';\n\nexport default function Example() {\n  const [budget, setBudget] = useState(7500);\n  return (\n    <ElasticSlider\n      label=\"Monthly budget\"\n      min={0}\n      max={20000}\n      step={100}\n      buttonStep={100}\n      value={budget}\n      onValueChange={setBudget}\n      prefix=\"$\"\n    />\n  );\n}
" } }, + "package-command": { + "react": { + "code": "import PackageCommand from '@/components/tweenui/package-command';\n\nexport default function Example() {\n return ;\n}", + "codeHtml": "
import PackageCommand from '@/components/tweenui/package-command';\n\nexport default function Example() {\n  return <PackageCommand packages={['gsap', '@gsap/react']} />;\n}
" + } + }, "pricing-plan-switch": { "react": { "code": "import PricingPlanSwitch from '@/components/tweenui/pricing-plan-switch';\n\nexport default function Example() {\n return ;\n}", @@ -580,6 +586,12 @@ export const manual: Record = { "codeHtml": "
'use client';\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ComponentPropsWithoutRef,\n  type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport { useGSAP } from '@gsap/react';\nimport NumberFlow, { type Format } 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\nconst MAX_STRETCH = 28;\nconst WAVE_WIDTH = 30;\nconst LIFT = { idle: 0.6, hover: 1.1, drag: 1.7 };\n\nconst STEP_BUTTON =\n  'grid size-9 cursor-pointer place-items-center transition-colors duration-200 hover:bg-current/10 focus-visible:bg-current/10 focus-visible:outline-none disabled:cursor-not-allowed disabled:hover:bg-transparent';\n\nconst clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));\n\nconst rubberBand = (overdrag: number) =>\n  Math.sign(overdrag) * MAX_STRETCH * (1 - Math.exp(-Math.abs(overdrag) / (MAX_STRETCH * 2.5)));\n\nconst decimalsOf = (step: number) => {\n  const [, fraction = ''] = String(step).split('.');\n  return fraction.length;\n};\n\nconst MinusIcon = () => (\n  <svg viewBox=\"0 0 24 24\" className=\"size-4\" fill=\"none\" aria-hidden=\"true\">\n    <path d=\"M5 12h14\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n  </svg>\n);\n\nconst PlusIcon = () => (\n  <svg viewBox=\"0 0 24 24\" className=\"size-4\" fill=\"none\" aria-hidden=\"true\">\n    <path d=\"M12 5v14M5 12h14\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" />\n  </svg>\n);\n\nexport interface ElasticSliderProps extends Omit<\n  ComponentPropsWithoutRef<'div'>,\n  'defaultValue' | 'onChange'\n> {\n  label: string;\n  min?: number;\n  max?: number;\n  step?: number;\n  value?: number;\n  defaultValue?: number;\n  onValueChange?: (value: number) => void;\n  format?: Format;\n  prefix?: string;\n  suffix?: string;\n  buttonStep?: number;\n  ticks?: number;\n  disabled?: boolean;\n}\n\nconst ElasticSlider = ({\n  label,\n  min = 0,\n  max = 100,\n  step = 1,\n  value: controlledValue,\n  defaultValue = 50,\n  onValueChange,\n  format,\n  prefix,\n  suffix,\n  buttonStep,\n  ticks = 41,\n  disabled = false,\n  className,\n  ...props\n}: ElasticSliderProps) => {\n  const inputId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const railRef = useRef<HTMLDivElement>(null);\n  const tickRefs = useRef<(HTMLSpanElement | null)[]>([]);\n  const indicatorRef = useRef<HTMLSpanElement>(null);\n  const decreaseRef = useRef<HTMLSpanElement>(null);\n  const increaseRef = useRef<HTMLSpanElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  const motion = useRef({ progress: 0, stretch: 0, focus: 0, lift: LIFT.idle });\n  const moveTo = useRef<((progress: number) => void) | null>(null);\n  const focusTo = useRef<((x: number) => void) | null>(null);\n  const liftTo = useRef<((lift: number) => void) | null>(null);\n  const hoverX = useRef<number | null>(null);\n\n  const [innerValue, setInnerValue] = useState(defaultValue);\n  const [dragging, setDragging] = useState(false);\n  const [reduced, setReduced] = useState(false);\n\n  const value = clamp(controlledValue ?? innerValue, min, max);\n  const span = max - min || 1;\n  const progress = (value - min) / span;\n  const numberFormat = { useGrouping: true, ...format };\n  const formatter = new Intl.NumberFormat(undefined, numberFormat);\n  const formatText = (number: number) =>\n    `${prefix ?? ''}${formatter.format(number)}${suffix ?? ''}`;\n\n  const render = useCallback(() => {\n    const rail = railRef.current;\n    if (!rail) return;\n    const width = rail.offsetWidth;\n    const { progress: current, stretch, focus, lift } = motion.current;\n    const offset = (t: number) => (stretch > 0 ? stretch * t : stretch * (1 - t));\n    const count = tickRefs.current.length;\n\n    tickRefs.current.forEach((tick, index) => {\n      if (!tick) return;\n      const t = count > 1 ? index / (count - 1) : 0;\n      const base = t * width;\n      const wave = Math.exp(-(((base - focus) / WAVE_WIDTH) ** 2));\n      gsap.set(tick, { x: base + offset(t), scaleY: 1 + lift * wave });\n      tick.toggleAttribute('data-on', t <= current + 0.0001);\n    });\n\n    gsap.set(indicatorRef.current, {\n      x: current * width + offset(current),\n      scaleY: 1 + (lift - LIFT.idle) * 0.12,\n    });\n  }, []);\n\n  useGSAP(\n    () => {\n      const isReduced = prefersReducedMotion();\n      setReduced(isReduced);\n      const width = railRef.current?.offsetWidth ?? 0;\n      motion.current.progress = progress;\n      motion.current.focus = progress * width;\n      motion.current.lift = isReduced ? 0 : LIFT.idle;\n      moveTo.current = gsap.quickTo(motion.current, 'progress', {\n        duration: isReduced ? 0 : 0.4,\n        ease: 'power3.out',\n        onUpdate: render,\n      });\n      focusTo.current = gsap.quickTo(motion.current, 'focus', {\n        duration: isReduced ? 0 : 0.5,\n        ease: 'power3.out',\n        onUpdate: render,\n      });\n      liftTo.current = gsap.quickTo(motion.current, 'lift', {\n        duration: isReduced ? 0 : 0.45,\n        ease: 'power2.out',\n        onUpdate: render,\n      });\n      render();\n\n      const rail = railRef.current;\n      if (!rail || typeof ResizeObserver === 'undefined') return;\n      const observer = new ResizeObserver(render);\n      observer.observe(rail);\n      return () => observer.disconnect();\n    },\n    { scope: rootRef, dependencies: [ticks] }\n  );\n\n  useEffect(() => {\n    moveTo.current?.(progress);\n    if (hoverX.current === null) focusTo.current?.(progress * (railRef.current?.offsetWidth ?? 0));\n  }, [progress]);\n\n  const setLift = (state: keyof typeof LIFT) => {\n    if (!reduced) liftTo.current?.(LIFT[state]);\n  };\n\n  const commit = (next: number) => {\n    const snapped = clamp(\n      Number((Math.round((next - min) / step) * step + min).toFixed(decimalsOf(step))),\n      min,\n      max\n    );\n    if (snapped === value) return;\n    if (controlledValue === undefined) setInnerValue(snapped);\n    onValueChange?.(snapped);\n  };\n\n  const stretchTo = (amount: number, release = false) => {\n    if (reduced) return;\n    gsap.to(motion.current, {\n      stretch: amount,\n      duration: release ? 0.9 : 0.2,\n      ease: release ? 'elastic.out(1, 0.32)' : 'power3.out',\n      overwrite: 'auto',\n      onUpdate: render,\n    });\n  };\n\n  const bump = (direction: number) => {\n    if (reduced) return;\n    gsap.to(motion.current, {\n      stretch: direction * 14,\n      duration: 0.14,\n      ease: 'power2.out',\n      overwrite: 'auto',\n      onUpdate: render,\n      onComplete: () => stretchTo(0, true),\n    });\n  };\n\n  const nudge = (direction: number) => {\n    if (disabled || !buttonStep) return;\n    if (!reduced) {\n      gsap.fromTo(\n        direction < 0 ? decreaseRef.current : increaseRef.current,\n        { scale: 0.6 },\n        { scale: 1, duration: 0.5, ease: 'back.out(3)', overwrite: true }\n      );\n    }\n    const atEdge = direction < 0 ? value <= min : value >= max;\n    if (atEdge) bump(direction);\n    else commit(value + direction * buttonStep);\n  };\n\n  const track = (clientX: number) => {\n    const rail = railRef.current;\n    if (!rail) return;\n    const rect = rail.getBoundingClientRect();\n    const overdrag =\n      clientX < rect.left ? clientX - rect.left : clientX > rect.right ? clientX - rect.right : 0;\n    commit(min + clamp((clientX - rect.left) / (rect.width || 1), 0, 1) * span);\n    stretchTo(rubberBand(overdrag));\n    hoverX.current = clamp(clientX - rect.left, 0, rect.width);\n    focusTo.current?.(hoverX.current);\n  };\n\n  const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (disabled || (event.pointerType === 'mouse' && event.button !== 0)) return;\n    event.preventDefault();\n    event.currentTarget.setPointerCapture(event.pointerId);\n    inputRef.current?.focus({ preventScroll: true });\n    setDragging(true);\n    setLift('drag');\n    track(event.clientX);\n  };\n\n  const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (dragging) {\n      track(event.clientX);\n      return;\n    }\n    if (disabled || event.pointerType !== 'mouse') return;\n    const rect = railRef.current?.getBoundingClientRect();\n    if (!rect) return;\n    hoverX.current = clamp(event.clientX - rect.left, 0, rect.width);\n    focusTo.current?.(hoverX.current);\n    setLift('hover');\n  };\n\n  const settle = () => {\n    hoverX.current = null;\n    focusTo.current?.(progress * (railRef.current?.offsetWidth ?? 0));\n    setLift('idle');\n  };\n\n  const handlePointerEnd = () => {\n    if (!dragging) return;\n    setDragging(false);\n    stretchTo(0, true);\n    settle();\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      data-elastic-slider\n      data-dragging={dragging || undefined}\n      className={cn(\n        'w-full max-w-md touch-none select-none [--elastic-accent:#045f64] motion-reduce:transition-none dark:[--elastic-accent:#c6f56f]',\n        disabled && 'opacity-50',\n        className\n      )}\n      {...props}\n    >\n      <div className=\"flex items-end justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <label htmlFor={inputId} className=\"block text-xs tracking-wide uppercase opacity-60\">\n            {label}\n          </label>\n          <NumberFlow\n            aria-hidden=\"true\"\n            value={value}\n            format={numberFormat}\n            prefix={prefix}\n            suffix={suffix}\n            animated={!reduced}\n            willChange\n            className=\"mt-1 block text-4xl font-medium tracking-tight tabular-nums\"\n          />\n        </div>\n\n        {buttonStep && (\n          <div className=\"flex shrink-0 overflow-hidden rounded-full border border-current/15\">\n            <button\n              type=\"button\"\n              disabled={disabled}\n              aria-label={`Decrease ${label} by ${formatText(buttonStep)}`}\n              onClick={() => nudge(-1)}\n              className={STEP_BUTTON}\n            >\n              <span ref={decreaseRef} className=\"flex\">\n                <MinusIcon />\n              </span>\n            </button>\n            <span aria-hidden=\"true\" className=\"w-px bg-current/15\" />\n            <button\n              type=\"button\"\n              disabled={disabled}\n              aria-label={`Increase ${label} by ${formatText(buttonStep)}`}\n              onClick={() => nudge(1)}\n              className={STEP_BUTTON}\n            >\n              <span ref={increaseRef} className=\"flex\">\n                <PlusIcon />\n              </span>\n            </button>\n          </div>\n        )}\n      </div>\n\n      <div\n        className={cn(\n          'relative mt-5 h-14',\n          disabled ? 'cursor-not-allowed' : dragging ? 'cursor-grabbing' : 'cursor-grab'\n        )}\n        onPointerDown={handlePointerDown}\n        onPointerMove={handlePointerMove}\n        onPointerLeave={() => !dragging && settle()}\n        onPointerUp={handlePointerEnd}\n        onPointerCancel={handlePointerEnd}\n        onLostPointerCapture={handlePointerEnd}\n      >\n        <input\n          ref={inputRef}\n          id={inputId}\n          type=\"range\"\n          min={min}\n          max={max}\n          step={step}\n          value={value}\n          disabled={disabled}\n          aria-valuetext={formatText(value)}\n          onChange={(event) => commit(Number(event.target.value))}\n          className=\"peer sr-only\"\n        />\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute -inset-x-3 -inset-y-1 rounded-xl outline-2 outline-transparent peer-focus-visible:outline-current\"\n        />\n        <div ref={railRef} aria-hidden=\"true\" className=\"absolute inset-0\">\n          {Array.from({ length: ticks }, (_, index) => (\n            <span\n              key={index}\n              ref={(node) => {\n                tickRefs.current[index] = node;\n              }}\n              className={cn(\n                'absolute top-1/2 left-0 -ml-px w-0.5 rounded-full bg-current/20 transition-colors duration-200 will-change-transform data-on:bg-(--elastic-accent)',\n                index % 5 === 0 ? '-mt-2.5 h-5' : '-mt-1.5 h-3'\n              )}\n            />\n          ))}\n          <span\n            ref={indicatorRef}\n            className=\"absolute top-1/2 left-0 -mt-6 -ml-[3px] h-12 w-1.5 rounded-full bg-(--elastic-accent) shadow-[0_0_0_3px_var(--color-white)] will-change-transform dark:shadow-[0_0_0_3px_#12161f]\"\n          />\n        </div>\n      </div>\n\n      <div aria-hidden=\"true\" className=\"mt-1 flex justify-between text-xs tabular-nums opacity-50\">\n        <span>{formatText(min)}</span>\n        <span>{formatText(max)}</span>\n      </div>\n    </div>\n  );\n};\n\nexport default ElasticSlider;\n
" } }, + "package-command": { + "react": { + "code": "'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 \n {Array.from(to, (character, index) => (\n \n {character}\n \n ))}\n {Array.from(from, (character, index) =>\n character === to[index] || character === ' ' ? null : (\n \n {character}\n \n )\n )}\n \n);\n\nconst ClipboardIcon = () => (\n \n \n \n \n);\n\nexport interface PackageCommandProps extends Omit, '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(null);\n const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const pillRef = useRef(null);\n const tailRef = useRef(null);\n const listRef = useRef(null);\n const sweepRef = useRef(null);\n const clipboardRef = useRef(null);\n const checkRef = useRef(null);\n const checkPathRef = useRef(null);\n const copyTimer = useRef(undefined);\n const flipTimeline = useRef(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('[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('[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) => {\n const moves: Record = {\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 \n
\n 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 \n {managers.map((each, index) => {\n const selected = index === activeIndex;\n return (\n {\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 \n );\n })}\n
\n\n \n \n \n \n \n \n \n \n \n\n \n

\n \n \n ${' '}\n \n \n \n \n \n \n \n {' '}\n {list}\n \n \n {command}\n

\n \n\n \n {copied ? 'Copied to clipboard' : ''}\n \n \n );\n};\n\nexport default PackageCommand;\n", + "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
" + } + }, "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/package-command.tsx b/apps/docs/registry/demos/package-command.tsx new file mode 100644 index 0000000..f817ff2 --- /dev/null +++ b/apps/docs/registry/demos/package-command.tsx @@ -0,0 +1,13 @@ +'use client'; + +import PackageCommand from '@/registry/tweenui/package-command'; + +const PackageCommandDemo = () => { + return ( +
+ +
+ ); +}; + +export default PackageCommandDemo; diff --git a/apps/docs/registry/registry-ui.ts b/apps/docs/registry/registry-ui.ts index 2211966..5e80553 100644 --- a/apps/docs/registry/registry-ui.ts +++ b/apps/docs/registry/registry-ui.ts @@ -1149,6 +1149,39 @@ export default function Example() { prefix="$" /> ); +}`, + }, + }, + { + name: 'package-command', + type: 'component', + addedAt: '2026-11-08', + title: 'Package Command', + description: + 'An install command in npm, pnpm, yarn and bun inside a small terminal card. A pill slides between the tabs, and only the characters that differ between managers flip like a split-flap board. Copying draws a check and sweeps a selection across the line. The choice is remembered and every block on the page follows it.', + media: {}, + dependencies: ['gsap', '@gsap/react'], + registryDependencies: [], + cssVars: {}, + files: [ + { + path: 'registry/tweenui/package-command.tsx', + target: 'components/tweenui/package-command.tsx', + kind: 'react', + }, + ], + variants: [ + { + id: 'default', + label: 'Default', + reactSource: 'registry/tweenui/package-command.tsx', + }, + ], + usage: { + react: `import PackageCommand from '@/components/tweenui/package-command'; + +export default function Example() { + return ; }`, }, }, diff --git a/apps/docs/registry/tweenui/package-command.tsx b/apps/docs/registry/tweenui/package-command.tsx new file mode 100644 index 0000000..e452716 --- /dev/null +++ b/apps/docs/registry/tweenui/package-command.tsx @@ -0,0 +1,473 @@ +'use client'; + +import { + useEffect, + useId, + useRef, + useState, + useSyncExternalStore, + type ComponentPropsWithoutRef, + type KeyboardEvent, +} from 'react'; +import { useGSAP } from '@gsap/react'; +import gsap from 'gsap'; +import { cn } from '@/lib/utils'; + +gsap.registerPlugin(useGSAP); + +export const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const; + +export type PackageManager = (typeof PACKAGE_MANAGERS)[number]; + +export type PackageCommandKind = 'install' | 'execute'; + +const STORAGE_KEY = 'tweenui:package-manager'; +const COPIED_FOR = 1600; + +const listeners = new Set<() => void>(); +let chosen: PackageManager | null = null; +let chosenByUser = false; + +const toManager = (value: unknown) => PACKAGE_MANAGERS.find((manager) => manager === value); + +const readManager = (): PackageManager => { + if (chosen) return chosen; + try { + chosen = toManager(window.localStorage.getItem(STORAGE_KEY)) ?? 'npm'; + } catch { + chosen = 'npm'; + } + return chosen; +}; + +const chooseManager = (manager: PackageManager) => { + if (manager === chosen) return; + chosen = manager; + chosenByUser = true; + try { + window.localStorage.setItem(STORAGE_KEY, manager); + } catch {} + listeners.forEach((listener) => listener()); +}; + +const subscribe = (listener: () => void) => { + const onStorage = (event: StorageEvent) => { + if (event.key !== STORAGE_KEY) return; + const next = toManager(event.newValue); + if (!next || next === chosen) return; + chosen = next; + chosenByUser = true; + listeners.forEach((each) => each()); + }; + listeners.add(listener); + window.addEventListener('storage', onStorage); + return () => { + listeners.delete(listener); + window.removeEventListener('storage', onStorage); + }; +}; + +const prefersReducedMotion = () => + typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + +const runner = (manager: PackageManager, kind: PackageCommandKind, dev: boolean) => { + if (kind === 'execute') { + if (manager === 'npm') return 'npx'; + if (manager === 'bun') return 'bunx'; + return `${manager} dlx`; + } + const verb = manager === 'npm' ? 'npm install' : `${manager} add`; + return dev ? `${verb} -D` : verb; +}; + +const splitHead = (head: string) => { + const space = head.indexOf(' '); + return space === -1 ? [head, ''] : [head.slice(0, space), head.slice(space)]; +}; + +const FlipCells = ({ from, to }: { from: string; to: string }) => ( + + {Array.from(to, (character, index) => ( + + {character} + + ))} + {Array.from(from, (character, index) => + character === to[index] || character === ' ' ? null : ( + + {character} + + ) + )} + +); + +const ClipboardIcon = () => ( + +); + +export interface PackageCommandProps extends Omit, 'onCopy'> { + packages: string | string[]; + kind?: PackageCommandKind; + dev?: boolean; + managers?: readonly PackageManager[]; + onCopy?: (command: string) => void; +} + +const PackageCommand = ({ + packages, + kind = 'install', + dev = false, + managers = PACKAGE_MANAGERS, + onCopy, + className, + ...props +}: PackageCommandProps) => { + const id = useId(); + const panelId = `${id}-panel`; + const rootRef = useRef(null); + const tabRefs = useRef<(HTMLButtonElement | null)[]>([]); + const pillRef = useRef(null); + const tailRef = useRef(null); + const listRef = useRef(null); + const sweepRef = useRef(null); + const clipboardRef = useRef(null); + const checkRef = useRef(null); + const checkPathRef = useRef(null); + const copyTimer = useRef(undefined); + const flipTimeline = useRef(null); + + const stored = useSyncExternalStore(subscribe, readManager, () => 'npm'); + const manager = managers.find((each) => each === stored) ?? managers[0] ?? 'npm'; + const activeIndex = Math.max(0, managers.indexOf(manager)); + const list = Array.isArray(packages) ? packages.join(' ') : packages.trim(); + const head = runner(manager, kind, dev); + const command = `${head} ${list}`; + + const [flip, setFlip] = useState({ from: head, to: head }); + const [copied, setCopied] = useState(false); + + if (flip.to !== head) setFlip({ from: flip.to, to: head }); + + const [fromTool, fromTail] = splitHead(flip.from); + const [toTool, toTail] = splitHead(flip.to); + + const { contextSafe } = useGSAP({ scope: rootRef }); + + const highlight = (index: number) => { + tabRefs.current.forEach((tab, each) => { + if (tab) tab.dataset.highlighted = String(each === index); + }); + }; + + const movePill = (index: number, animate: boolean) => { + const tab = tabRefs.current[index]; + if (!tab) return; + highlight(index); + const bounds = { x: tab.offsetLeft, width: tab.offsetWidth }; + if (!animate || prefersReducedMotion()) { + gsap.killTweensOf(pillRef.current); + gsap.set(pillRef.current, bounds); + return; + } + gsap.to(pillRef.current, { ...bounds, duration: 0.35, ease: 'power2.out', overwrite: 'auto' }); + }; + + const followPointer = contextSafe((target: EventTarget) => { + if (!(target instanceof Element)) return; + const tab = target.closest('[role="tab"]'); + const index = tabRefs.current.findIndex((each) => each === tab); + if (index !== -1) movePill(index, true); + }); + + const returnToActive = contextSafe(() => movePill(activeIndex, true)); + + useGSAP( + () => { + movePill(activeIndex, chosenByUser); + }, + { scope: rootRef, dependencies: [activeIndex, managers.length] } + ); + + useEffect(() => { + const tablist = tabRefs.current[0]?.parentElement; + if (!tablist || typeof ResizeObserver === 'undefined') return; + const observer = new ResizeObserver(() => movePill(activeIndex, false)); + observer.observe(tablist); + return () => observer.disconnect(); + }, [activeIndex, managers]); + + useGSAP( + () => { + if (flip.from === flip.to) { + gsap.set( + [tailRef.current, listRef.current, ...gsap.utils.toArray('[data-in]', rootRef.current)], + { + clearProps: 'transform,opacity', + } + ); + return; + } + flipTimeline.current?.kill(); + const root = rootRef.current; + const listElement = listRef.current; + const incoming = gsap.utils.toArray('[data-in]', root); + gsap.set(incoming, { yPercent: 0, opacity: 1 }); + const settle = () => setFlip((current) => ({ from: current.to, to: current.to })); + if (!chosenByUser || prefersReducedMotion()) { + gsap.set([tailRef.current, listElement], { x: 0 }); + settle(); + return; + } + const charWidth = incoming[0]?.getBoundingClientRect().width ?? 0; + const timeline = gsap.timeline({ onComplete: settle }); + flipTimeline.current = timeline; + const slide = (element: HTMLElement | null, shift: number) => { + const currentX = Number(gsap.getProperty(element, 'x')) || 0; + timeline.fromTo( + element, + { x: shift * charWidth + currentX }, + { x: 0, duration: 0.55, ease: 'power3.inOut' }, + 0 + ); + }; + slide(tailRef.current, fromTool.length - toTool.length); + slide(listElement, flip.from.length - flip.to.length); + timeline.fromTo( + gsap.utils.toArray('[data-out]', root), + { yPercent: 0, opacity: 1 }, + { yPercent: -70, opacity: 0, duration: 0.2, ease: 'power2.in' }, + 0 + ); + incoming + .filter((element) => element.hasAttribute('data-changed')) + .forEach((element, order) => { + timeline.fromTo( + element, + { yPercent: 100, opacity: 0 }, + { yPercent: 0, opacity: 1, duration: 0.42, ease: 'power3.out' }, + order * 0.03 + 0.1 + ); + }); + }, + { scope: rootRef, dependencies: [flip.from, flip.to] } + ); + + useEffect(() => () => window.clearTimeout(copyTimer.current), []); + + const select = (index: number, focus = false) => { + const next = managers[(index + managers.length) % managers.length]; + if (!next) return; + chooseManager(next); + if (focus) tabRefs.current[managers.indexOf(next)]?.focus(); + }; + + const handleKeyDown = (event: KeyboardEvent) => { + const moves: Record = { + ArrowRight: activeIndex + 1, + ArrowLeft: activeIndex - 1, + Home: 0, + End: managers.length - 1, + }; + const target = moves[event.key]; + if (target === undefined) return; + event.preventDefault(); + select(target, true); + }; + + const playCopied = contextSafe(() => { + if (prefersReducedMotion()) { + gsap.set(clipboardRef.current, { opacity: 0 }); + gsap.set(checkRef.current, { opacity: 1 }); + gsap.set(checkPathRef.current, { strokeDashoffset: 0 }); + return; + } + gsap + .timeline({ defaults: { overwrite: 'auto' } }) + .to(clipboardRef.current, { scale: 0.6, opacity: 0, duration: 0.2, ease: 'power2.in' }, 0) + .set(checkRef.current, { opacity: 1 }, 0.12) + .fromTo( + checkPathRef.current, + { strokeDashoffset: 1 }, + { strokeDashoffset: 0, duration: 0.4, ease: 'power3.out' }, + 0.12 + ) + .fromTo( + sweepRef.current, + { scaleX: 0, opacity: 1 }, + { scaleX: 1, duration: 0.5, ease: 'power3.out' }, + 0 + ) + .to(sweepRef.current, { opacity: 0, duration: 0.5, ease: 'power2.out' }, 0.7); + }); + + const playReset = contextSafe(() => { + const reduced = prefersReducedMotion(); + gsap.to(checkRef.current, { opacity: 0, duration: reduced ? 0 : 0.2, ease: 'power2.out' }); + gsap.fromTo( + clipboardRef.current, + { scale: reduced ? 1 : 0.6 }, + { + scale: 1, + opacity: 1, + duration: reduced ? 0 : 0.35, + ease: 'power3.out', + delay: reduced ? 0 : 0.1, + } + ); + }); + + const copy = async () => { + try { + await navigator.clipboard.writeText(command); + } catch { + return; + } + onCopy?.(command); + setCopied(true); + playCopied(); + window.clearTimeout(copyTimer.current); + copyTimer.current = window.setTimeout(() => { + setCopied(false); + playReset(); + }, COPIED_FOR); + }; + + return ( +
+
+
followPointer(event.target)} + onPointerLeave={returnToActive} + onFocus={(event) => followPointer(event.target)} + onBlur={(event) => { + if (!event.currentTarget.contains(event.relatedTarget)) returnToActive(); + }} + > +
+ + +
+ +
+

+

+
+ + + {copied ? 'Copied to clipboard' : ''} + +
+ ); +}; + +export default PackageCommand; diff --git a/apps/docs/tests/package-command.test.tsx b/apps/docs/tests/package-command.test.tsx new file mode 100644 index 0000000..70f106e --- /dev/null +++ b/apps/docs/tests/package-command.test.tsx @@ -0,0 +1,126 @@ +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import PackageCommand from '@/registry/tweenui/package-command'; + +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; +}; + +const writeText = vi.fn().mockResolvedValue(undefined); + +const storage = new Map(); + +Object.defineProperty(window, 'localStorage', { + configurable: true, + value: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), + clear: () => storage.clear(), + }, +}); + +const pick = (name: string) => fireEvent.click(screen.getAllByRole('tab', { name })[0]!); + +describe('Package Command', () => { + beforeEach(() => { + setReducedMotion(true); + writeText.mockClear(); + Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true }); + render().unmount(); + }); + + it('renders a tab per manager and the npm command', () => { + render(); + pick('npm'); + expect(screen.getAllByRole('tab').map((tab) => tab.textContent)).toEqual([ + 'npm', + 'pnpm', + 'yarn', + 'bun', + ]); + expect(screen.getByRole('tabpanel')).toHaveTextContent('npm install gsap @gsap/react'); + }); + + it('switches the command and remembers the choice', () => { + render(); + pick('pnpm'); + expect(screen.getByRole('tab', { name: 'pnpm' })).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('pnpm add -D gsap'); + expect(window.localStorage.getItem('tweenui:package-manager')).toBe('pnpm'); + }); + + it('keeps every instance on the same manager', () => { + render( + <> + + + + ); + pick('bun'); + const panels = screen.getAllByRole('tabpanel'); + expect(panels[0]).toHaveTextContent('bun add gsap'); + expect(panels[1]).toHaveTextContent('bunx shadcn@latest init'); + }); + + it('moves with the arrow keys, Home and End', () => { + render(); + pick('npm'); + const npm = screen.getByRole('tab', { name: 'npm' }); + fireEvent.keyDown(npm, { key: 'ArrowLeft' }); + expect(screen.getByRole('tab', { name: 'bun' })).toHaveFocus(); + fireEvent.keyDown(screen.getByRole('tab', { name: 'bun' }), { key: 'Home' }); + expect(npm).toHaveAttribute('aria-selected', 'true'); + fireEvent.keyDown(npm, { key: 'End' }); + expect(screen.getByRole('tab', { name: 'bun' })).toHaveAttribute('tabindex', '0'); + expect(npm).toHaveAttribute('tabindex', '-1'); + }); + + it('copies the current command', async () => { + const onCopy = vi.fn(); + render(); + pick('yarn'); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Copy command' })); + }); + expect(writeText).toHaveBeenCalledWith('yarn add gsap'); + expect(onCopy).toHaveBeenCalledWith('yarn add gsap'); + expect(screen.getByRole('status')).toHaveTextContent('Copied to clipboard'); + }); + + it('falls back to the first listed manager', () => { + render(); + pick('bun'); + render(); + expect(screen.getAllByRole('tabpanel')[1]).toHaveTextContent('npm install gsap'); + }); + + it('flips only the tool when the verb stays the same', () => { + setReducedMotion(false); + const { container } = render(); + pick('yarn'); + pick('bun'); + const changed = Array.from( + container.querySelectorAll('[data-in][data-changed]'), + (cell) => cell.textContent + ).join(''); + expect(changed).toBe('bun'); + }); + + it('animates the flip without breaking the text', () => { + setReducedMotion(false); + render(); + pick('pnpm'); + pick('yarn'); + expect(screen.getByRole('tabpanel')).toHaveTextContent('yarn add gsap'); + }); +});