{"slug":"bounce-sidebar","name":"Bounce Sidebar","description":"A vertical sidebar whose active dot jumps between destinations on a curved, spring-loaded path.","category":"motion","source_url":"https://beui.dev/r/bounce-sidebar/raw","detail_url":"https://beui.dev/r/bounce-sidebar","raw_url":"https://beui.dev/r/bounce-sidebar/raw","page_url":"https://beui.dev/components/motion/bounce-sidebar","markdown_url":"https://beui.dev/components/motion/bounce-sidebar.md","published_at":"2026-07-22","updated_at":"2026-11-10","dependencies":["clsx","motion","react","tailwind-merge"],"internal":["@/components/motion/bounce-sidebar","@/lib/i18n","@/lib/utils"],"install_slugs":["bounce-sidebar"],"requires_theme":false,"props":[{"displayName":"BounceSidebar","props":[{"name":"items","type":"BounceSidebarItem[]","required":true,"defaultValue":null,"description":"Links or buttons listed in the sidebar, in order."},{"name":"value","type":"string","required":false,"defaultValue":null,"description":"Id of the active item, for controlled use."},{"name":"defaultValue","type":"string","required":false,"defaultValue":null,"description":"The initial active item id when uncontrolled. Defaults to the first item."},{"name":"onValueChange","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the item id when an item is picked."},{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the nav. Default: \"Sidebar navigation\""},{"name":"labels","type":"Partial<{ label: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root nav element."},{"name":"listClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the list element."},{"name":"itemClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto each item's link or button."},{"name":"indicatorClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the bouncing dot."}]}],"types":[{"name":"BounceSidebarItem","file":"components/motion/bounce-sidebar.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key, used as the sidebar's active value."},{"name":"label","type":"ReactNode","required":true,"description":"Text shown in the row."},{"name":"href","type":"string","required":false,"description":"Link address. Renders a link instead of a button when set."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon shown before the label. Omitted when not set."},{"name":"disabled","type":"boolean","required":false,"description":"Dims the row and blocks selection."},{"name":"target","type":"\"_blank\" | \"_self\" | \"_parent\" | \"_top\"","required":false,"description":"Where the link opens. Only used with `href`."},{"name":"rel","type":"string","required":false,"description":"Link `rel`. Default: \"noreferrer noopener\" when `target` is \"_blank\""}]}],"files":[{"path":"components/motion/bounce-sidebar.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/bounce-sidebar\n\nimport { arc, useAnimate, useReducedMotion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface BounceSidebarItem {\n  /** Unique key, used as the sidebar's active value. */\n  id: string;\n  /** Text shown in the row. */\n  label: ReactNode;\n  /** Link address. Renders a link instead of a button when set. */\n  href?: string;\n  /** Icon shown before the label. Omitted when not set. */\n  icon?: ReactNode;\n  /** Dims the row and blocks selection. */\n  disabled?: boolean;\n  /** Where the link opens. Only used with `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link `rel`. Default: \"noreferrer noopener\" when `target` is \"_blank\" */\n  rel?: string;\n}\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const bounceSidebarMessages = {\n  label: \"Sidebar navigation\",\n};\n\nexport type BounceSidebarMessages = typeof bounceSidebarMessages;\n\nexport interface BounceSidebarProps {\n  /** Links or buttons listed in the sidebar, in order. */\n  items: BounceSidebarItem[];\n  /** Id of the active item, for controlled use. */\n  value?: string;\n  /** The initial active item id when uncontrolled. Defaults to the first item. */\n  defaultValue?: string;\n  /** Called with the item id when an item is picked. */\n  onValueChange?: (value: string) => void;\n  /** Accessible name for the nav. Default: \"Sidebar navigation\" */\n  ariaLabel?: string;\n  /** Override any built-in string. */\n  labels?: Partial<BounceSidebarMessages>;\n  /** Classes merged onto the root nav element. */\n  className?: string;\n  /** Classes merged onto the list element. */\n  listClassName?: string;\n  /** Classes merged onto each item's link or button. */\n  itemClassName?: string;\n  /** Classes merged onto the bouncing dot. */\n  indicatorClassName?: string;\n}\n\nconst DOT_SIZE = 6;\n\n// A compact, lightly underdamped spring gives the dot a quick landing without\n// turning the sidebar into a playful toy. The sideways arc carries the bounce.\nconst BOUNCE_SPRING = {\n  type: \"spring\",\n  stiffness: 280,\n  damping: 18,\n  mass: 0.3,\n} as const;\n\n// The dot hops sideways, away from the labels. arc() bends proportionally to\n// the distance travelled, so cap it: adjacent rows get a ~5px hop and a long\n// jump peaks near 20px instead of swinging out of the sidebar.\nconst ARC_MAX_STRENGTH = 0.26;\nconst ARC_MAX_BULGE = 40;\n\nexport function BounceSidebar({\n  items,\n  value,\n  defaultValue,\n  onValueChange,\n  ariaLabel,\n  labels,\n  className,\n  listClassName,\n  itemClassName,\n  indicatorClassName,\n}: BounceSidebarProps) {\n  const reduce = useReducedMotion();\n  const t = useMessages(\"bounceSidebar\", bounceSidebarMessages, labels);\n  const [internalValue, setInternalValue] = useState(\n    defaultValue ?? items[0]?.id ?? \"\",\n  );\n  const requestedValue = value ?? internalValue;\n  const selectedValue = items.some((item) => item.id === requestedValue)\n    ? requestedValue\n    : (items[0]?.id ?? \"\");\n  const selectedIndex = items.findIndex((item) => item.id === selectedValue);\n  const listRef = useRef<HTMLUListElement>(null);\n  const itemRefs = useRef(new Map<string, HTMLLIElement>());\n  const selectedValueRef = useRef(selectedValue);\n  const previousIndexRef = useRef(selectedIndex);\n  const hasPositionRef = useRef(false);\n  const dotYRef = useRef(0);\n  const [dot, animateDot] = useAnimate<HTMLSpanElement>();\n  selectedValueRef.current = selectedValue;\n\n  const placeDot = useCallback(\n    (destinationY: number) => {\n      if (!dot.current) return;\n      animateDot(dot.current, { x: 0, y: destinationY }, { duration: 0 });\n      dotYRef.current = destinationY;\n      hasPositionRef.current = true;\n    },\n    [animateDot, dot],\n  );\n\n  const snapIndicator = useCallback(() => {\n    const selectedItem = itemRefs.current.get(selectedValueRef.current);\n    if (!selectedItem) return;\n    placeDot(\n      selectedItem.offsetTop + (selectedItem.offsetHeight - DOT_SIZE) / 2,\n    );\n  }, [placeDot]);\n\n  const positionIndicator = useCallback(\n    (shouldAnimate: boolean) => {\n      const selectedItem = itemRefs.current.get(selectedValue);\n      if (!selectedItem) return;\n\n      const destinationY =\n        selectedItem.offsetTop + (selectedItem.offsetHeight - DOT_SIZE) / 2;\n\n      if (!hasPositionRef.current || reduce || !shouldAnimate || !dot.current) {\n        placeDot(destinationY);\n        previousIndexRef.current = selectedIndex;\n        return;\n      }\n\n      const distance = destinationY - dotYRef.current;\n      const travel = Math.abs(distance);\n      const longJumpProgress = Math.min(1, Math.max(0, (travel - 48) / 120));\n      dotYRef.current = destinationY;\n\n      animateDot(\n        dot.current,\n        { x: 0, y: destinationY },\n        {\n          ...BOUNCE_SPRING,\n          stiffness: BOUNCE_SPRING.stiffness - 60 * longJumpProgress,\n          damping: BOUNCE_SPRING.damping + longJumpProgress,\n          mass: BOUNCE_SPRING.mass + 0.15 * longJumpProgress,\n          path: arc({\n            strength: Math.min(ARC_MAX_STRENGTH, ARC_MAX_BULGE / travel),\n            // Relative to the direction of travel, so both directions\n            // bulge to the screen left, away from the labels.\n            direction: distance > 0 ? \"ccw\" : \"cw\",\n          }),\n        },\n      );\n\n      previousIndexRef.current = selectedIndex;\n    },\n    [animateDot, dot, placeDot, reduce, selectedIndex, selectedValue],\n  );\n\n  useLayoutEffect(() => {\n    const shouldAnimate =\n      hasPositionRef.current && previousIndexRef.current !== selectedIndex;\n    positionIndicator(shouldAnimate);\n  }, [positionIndicator, selectedIndex]);\n\n  useLayoutEffect(() => {\n    const list = listRef.current;\n    if (!list || typeof ResizeObserver === \"undefined\") return;\n\n    const observer = new ResizeObserver(snapIndicator);\n    observer.observe(list);\n    return () => observer.disconnect();\n  }, [snapIndicator]);\n\n  const selectItem = (id: string) => {\n    if (value === undefined) setInternalValue(id);\n    onValueChange?.(id);\n  };\n\n  return (\n    <nav aria-label={ariaLabel ?? t(\"label\")} className={cn(\"relative\", className)}>\n      <ul\n        ref={listRef}\n        className={cn(\"relative flex list-none flex-col gap-1.5 pl-6\", listClassName)}\n      >\n        {selectedIndex >= 0 ? (\n          <li\n            aria-hidden=\"true\"\n            role=\"presentation\"\n            className=\"pointer-events-none absolute inset-0\"\n          >\n            <span\n              ref={dot}\n              className={cn(\n                \"absolute top-0 left-3 h-1.5 w-1.5 rounded-full bg-primary\",\n                indicatorClassName,\n              )}\n            />\n          </li>\n        ) : null}\n\n        {items.map((item) => {\n          const active = item.id === selectedValue;\n          const content = (\n            <>\n              {item.icon ? (\n                <span aria-hidden=\"true\" className=\"shrink-0\">\n                  {item.icon}\n                </span>\n              ) : null}\n              <span>{item.label}</span>\n            </>\n          );\n          const interactiveClasses = cn(\n            \"flex min-h-9 w-full items-center gap-2 rounded-lg px-2 text-left text-sm font-medium outline-none transition-colors\",\n            \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n            active\n              ? \"text-foreground\"\n              : \"text-muted-foreground hover:text-foreground\",\n            item.disabled ? \"cursor-not-allowed opacity-40\" : undefined,\n            itemClassName,\n          );\n\n          return (\n            <li\n              key={item.id}\n              ref={(node) => {\n                if (node) itemRefs.current.set(item.id, node);\n                else itemRefs.current.delete(item.id);\n              }}\n              className=\"relative\"\n            >\n              {item.href ? (\n                <a\n                  href={item.href}\n                  target={item.target}\n                  rel={\n                    item.rel ??\n                    (item.target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n                  }\n                  aria-current={active ? \"page\" : undefined}\n                  aria-disabled={item.disabled || undefined}\n                  data-active={active || undefined}\n                  tabIndex={item.disabled ? -1 : undefined}\n                  onClick={(event) => {\n                    if (item.disabled) {\n                      event.preventDefault();\n                      return;\n                    }\n                    selectItem(item.id);\n                  }}\n                  className={interactiveClasses}\n                >\n                  {content}\n                </a>\n              ) : (\n                <button\n                  type=\"button\"\n                  disabled={item.disabled}\n                  aria-current={active ? \"page\" : undefined}\n                  data-active={active || undefined}\n                  onClick={() => selectItem(item.id)}\n                  className={interactiveClasses}\n                >\n                  {content}\n                </button>\n              )}\n            </li>\n          );\n        })}\n      </ul>\n    </nav>\n  );\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/previews/motion/bounce-sidebar.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { useState } from \"react\";\nimport { BounceSidebar } from \"@/components/motion/bounce-sidebar\";\n\nconst destinations = [\n  { id: \"overview\", label: \"Overview\" },\n  { id: \"components\", label: \"Components\" },\n  { id: \"motion\", label: \"Motion\" },\n  { id: \"templates\", label: \"Templates\" },\n  { id: \"changelog\", label: \"Changelog\" },\n];\n\nexport function BounceSidebarPreview() {\n  const [active, setActive] = useState(\"components\");\n\n  return (\n    <div className=\"flex min-h-[360px] w-full items-center justify-center\">\n      <BounceSidebar\n        items={destinations}\n        value={active}\n        onValueChange={setActive}\n        ariaLabel=\"beUI sections\"\n        className=\"w-52\"\n        listClassName=\"w-full\"\n        itemClassName=\"text-base\"\n      />\n    </div>\n  );\n}\n"}]}