{"slug":"expandable-tabs","name":"Expandable Tabs","description":"Icon tab bar where the active tab expands to a labelled pill, with a panel above that morphs height and slides content direction-aware on switch.","category":"blocks","source_url":"https://beui.dev/r/expandable-tabs/raw","detail_url":"https://beui.dev/r/expandable-tabs","raw_url":"https://beui.dev/r/expandable-tabs/raw","page_url":"https://beui.dev/components/blocks/expandable-tabs","markdown_url":"https://beui.dev/components/blocks/expandable-tabs.md","published_at":"2026-06-14","updated_at":"2026-11-28","dependencies":["clsx","lucide-react","motion","react","tailwind-merge"],"internal":["@/components/motion/expandable-tabs","@/lib/ease","@/lib/hooks/use-dismiss","@/lib/i18n","@/lib/layers","@/lib/utils"],"install_slugs":["expandable-tabs"],"requires_theme":false,"props":[{"displayName":"ExpandableTabs","props":[{"name":"items","type":"ExpandableTabsItem[]","required":true,"defaultValue":null,"description":"Tabs in the bar, each with an icon, label and panel content."},{"name":"value","type":"string | null","required":false,"defaultValue":null,"description":"Active tab id, or null/undefined for the closed (bar-only) state."},{"name":"defaultValue","type":"string | null","required":false,"defaultValue":"null","description":"The tab open at first when uncontrolled. Default: null"},{"name":"onValueChange","type":"((id: string | null) => void)","required":false,"defaultValue":null,"description":"Called with the tab id when one opens, or null when the panel closes."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"classNames","type":"ExpandableTabsClassNames","required":false,"defaultValue":null,"description":"Classes for inner parts: root, panel, bar, tab, activeTab, icon, label, pill."},{"name":"labels","type":"Partial<{ label: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]}],"types":[{"name":"ExpandableTabsItem","file":"components/motion/expandable-tabs.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the tab, used in `value`."},{"name":"label","type":"string","required":true,"description":"String label - shown inside the active tab and used as the button's accessible name."},{"name":"icon","type":"ReactNode","required":true,"description":"Icon shown in the tab button, open or closed."},{"name":"content","type":"ReactNode","required":true,"description":"Panel shown above the bar when this tab is active."}]},{"name":"ExpandableTabsClassNames","file":"components/motion/expandable-tabs.tsx","fields":[{"name":"root","type":"string","required":false,"description":"Classes for the outer shell that grows to fit the panel."},{"name":"panel","type":"string","required":false,"description":"Classes for the panel area above the bar."},{"name":"bar","type":"string","required":false,"description":"Classes for the tab bar along the bottom."},{"name":"tab","type":"string","required":false,"description":"Classes for each tab button."},{"name":"activeTab","type":"string","required":false,"description":"Classes added to the active tab button."},{"name":"icon","type":"string","required":false,"description":"Classes for the wrapper around each tab icon."},{"name":"label","type":"string","required":false,"description":"Classes for the active tab's label."},{"name":"pill","type":"string","required":false,"description":"Classes for the highlight behind the active tab."}]}],"files":[{"path":"components/motion/expandable-tabs.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/blocks/expandable-tabs\n\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ReactNode,\n} from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const expandableTabsMessages = {\n  label: \"Navigation tabs\",\n};\n\nexport type ExpandableTabsMessages = typeof expandableTabsMessages;\n\nexport type ExpandableTabsItem = {\n  /** Unique key for the tab, used in `value`. */\n  id: string;\n  /** String label - shown inside the active tab and used as the button's accessible name. */\n  label: string;\n  /** Icon shown in the tab button, open or closed. */\n  icon: ReactNode;\n  /** Panel shown above the bar when this tab is active. */\n  content: ReactNode;\n};\n\nexport type ExpandableTabsClassNames = {\n  /** Classes for the outer shell that grows to fit the panel. */\n  root?: string;\n  /** Classes for the panel area above the bar. */\n  panel?: string;\n  /** Classes for the tab bar along the bottom. */\n  bar?: string;\n  /** Classes for each tab button. */\n  tab?: string;\n  /** Classes added to the active tab button. */\n  activeTab?: string;\n  /** Classes for the wrapper around each tab icon. */\n  icon?: string;\n  /** Classes for the active tab's label. */\n  label?: string;\n  /** Classes for the highlight behind the active tab. */\n  pill?: string;\n};\n\nexport interface ExpandableTabsProps {\n  /** Tabs in the bar, each with an icon, label and panel content. */\n  items: ExpandableTabsItem[];\n  /** Active tab id, or null/undefined for the closed (bar-only) state. */\n  value?: string | null;\n  /** The tab open at first when uncontrolled. Default: null */\n  defaultValue?: string | null;\n  /** Called with the tab id when one opens, or null when the panel closes. */\n  onValueChange?: (id: string | null) => void;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes for inner parts: root, panel, bar, tab, activeTab, icon, label, pill. */\n  classNames?: ExpandableTabsClassNames;\n  /** Override any built-in string. */\n  labels?: Partial<ExpandableTabsMessages>;\n}\n\ntype Size = { width: number; height: number };\n\n// DynamicIsland-style real width/height motion, tuned tighter here so the tab\n// bar feels controlled instead of elastic.\nconst SHELL_SPRING = { type: \"spring\", duration: 0.58, bounce: 0.06 } as const;\n\n// Position-only tab layout motion keeps switching loose without stretching\n// icons or letting the label linger.\nconst TAB_CHANGE_SPRING = {\n  type: \"spring\",\n  duration: 0.46,\n  bounce: 0.04,\n} as const;\nconst LABEL_OPEN = { type: \"spring\", duration: 0.38, bounce: 0.03 } as const;\nconst LABEL_CLOSE = { duration: 0.16, ease: EASE_OUT } as const;\n\n// Fixed bar height keeps the content panel's bottom reserve static so the open\n// height is right on the first frame. p-2 (16) + h-9 button (36).\nconst BAR_H = 52;\nconst TAB_W = 32;\nconst BAR_X = 16;\nconst BAR_GAP = 4;\nconst ROOT_BORDER = 2;\nconst ICON_W = 16;\nconst ACTIVE_LEFT_PAD = 10;\nconst ACTIVE_RIGHT_PAD = 16;\nconst LABEL_GAP = 7;\nconst PANEL_DOCK_GAP = 4;\n\n// Content is clipped above the dock so rows never pass through the icon bar.\n// It enters from slightly above instead of from the dock line.\nconst CONTENT_VARIANTS: Variants = {\n  enter: { y: -8, scale: 0.98, opacity: 0, filter: \"blur(4px)\" },\n  center: { y: 0, scale: 1, opacity: 1, filter: \"blur(0px)\" },\n  exit: {\n    y: -6,\n    scale: 0.98,\n    opacity: 0,\n    filter: \"blur(4px)\",\n    transition: { duration: 0.08, ease: EASE_OUT },\n  },\n};\n\nconst REDUCED_CONTENT_VARIANTS: Variants = {\n  enter: { opacity: 0, filter: \"blur(0px)\" },\n  center: { opacity: 1, filter: \"blur(0px)\" },\n  exit: {\n    opacity: 0,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.08, ease: EASE_OUT },\n  },\n};\n\nconst CONTENT_SPRING = { type: \"spring\", duration: 0.46, bounce: 0.08 } as const;\n\nfunction sameSize(a: Size | null | undefined, b: Size | null | undefined) {\n  return a?.width === b?.width && a?.height === b?.height;\n}\n\nfunction sameWidths(a: Record<string, number>, b: Record<string, number>) {\n  const aKeys = Object.keys(a);\n  const bKeys = Object.keys(b);\n\n  if (aKeys.length !== bKeys.length) {\n    return false;\n  }\n\n  return aKeys.every((key) => a[key] === b[key]);\n}\n\nfunction useContentSize() {\n  const ref = useRef<HTMLDivElement | null>(null);\n  const [size, setSize] = useState<Size | null>(null);\n\n  const measure = useCallback(() => {\n    const el = ref.current;\n    if (!el) return;\n    const next = { width: el.offsetWidth, height: el.offsetHeight };\n    setSize((current) => (sameSize(current, next) ? current : next));\n  }, []);\n\n  useLayoutEffect(() => {\n    measure();\n  }, [measure]);\n\n  useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, [measure]);\n\n  return [ref, size] as const;\n}\n\nfunction useLabelWidths(items: ExpandableTabsItem[]) {\n  const refs = useRef<Record<string, HTMLSpanElement | null>>({});\n  const [widths, setWidths] = useState<Record<string, number>>({});\n\n  const setLabelMeasureRef = useCallback(\n    (id: string) => (node: HTMLSpanElement | null) => {\n      refs.current[id] = node;\n    },\n    [],\n  );\n\n  const measure = useCallback(() => {\n    const next: Record<string, number> = {};\n\n    for (const item of items) {\n      const node = refs.current[item.id];\n\n      if (node) {\n        next[item.id] = Math.ceil(node.offsetWidth);\n      }\n    }\n\n    setWidths((current) => (sameWidths(current, next) ? current : next));\n  }, [items]);\n\n  useLayoutEffect(() => {\n    measure();\n  }, [measure]);\n\n  useEffect(() => {\n    if (typeof ResizeObserver === \"undefined\") {\n      return;\n    }\n\n    const observer = new ResizeObserver(measure);\n\n    for (const item of items) {\n      const node = refs.current[item.id];\n\n      if (node) {\n        observer.observe(node);\n      }\n    }\n\n    return () => observer.disconnect();\n  }, [items, measure]);\n\n  return { setLabelMeasureRef, widths };\n}\n\nexport function ExpandableTabs({\n  items,\n  value,\n  defaultValue = null,\n  onValueChange,\n  className,\n  classNames,\n  labels,\n}: ExpandableTabsProps) {\n  const t = useMessages(\"expandableTabs\", expandableTabsMessages, labels);\n  const reduce = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [sizerRef, size] = useContentSize();\n  const { setLabelMeasureRef, widths: labelWidths } = useLabelWidths(items);\n\n  const controlled = value !== undefined;\n  const [internal, setInternal] = useState<string | null>(defaultValue);\n  const activeId = controlled ? value : internal;\n  const active = items.find((item) => item.id === activeId) ?? null;\n  const visualActiveId = active?.id ?? null;\n\n  const setActive = useCallback(\n    (next: string | null) => {\n      if (!controlled) setInternal(next);\n      onValueChange?.(next);\n    },\n    [controlled, onValueChange],\n  );\n\n  // Outside click / Escape closes - it behaves like an open menu.\n  const collapse = useCallback(() => setActive(null), [setActive]);\n  useDismiss(visualActiveId !== null, collapse, rootRef);\n\n  const closedSize = {\n    width:\n      items.length * TAB_W +\n      Math.max(0, items.length - 1) * BAR_GAP +\n      BAR_X +\n      ROOT_BORDER,\n    height: BAR_H + ROOT_BORDER,\n  };\n  const openSize = size\n    ? {\n        width: Math.max(size.width + ROOT_BORDER, closedSize.width),\n        height: Math.max(size.height + ROOT_BORDER, closedSize.height),\n      }\n    : closedSize;\n  const targetSize = active ? openSize : closedSize;\n\n  const getActiveTabWidth = useCallback(\n    (item: ExpandableTabsItem) =>\n      Math.max(\n        TAB_W,\n        ACTIVE_LEFT_PAD +\n          ICON_W +\n          LABEL_GAP +\n          (labelWidths[item.id] ?? 0) +\n          ACTIVE_RIGHT_PAD,\n      ),\n    [labelWidths],\n  );\n\n  return (\n    <>\n      <motion.div\n        ref={rootRef}\n        initial={false}\n        animate={\n          targetSize\n            ? { width: targetSize.width, height: targetSize.height }\n            : undefined\n        }\n        transition={reduce ? { duration: 0 } : SHELL_SPRING}\n        style={{ transformOrigin: \"bottom center\" }}\n        className={cn(\n          \"relative overflow-hidden rounded-[26px] border border-border bg-card\",\n          className,\n          classNames?.root,\n        )}\n      >\n        <div\n          ref={sizerRef}\n          aria-hidden\n          className={cn(\n            \"pointer-events-none invisible absolute left-0 top-0 grid w-max px-2 pt-2\",\n            classNames?.panel,\n          )}\n          style={{ paddingBottom: BAR_H + PANEL_DOCK_GAP }}\n        >\n          {items.map((item) => (\n            <div key={item.id} className=\"col-start-1 row-start-1 w-max\">\n              {item.content}\n            </div>\n          ))}\n        </div>\n\n        <div\n          className={cn(\n            \"absolute left-0 right-0 top-0 z-10 overflow-hidden px-2 pt-2\",\n            classNames?.panel,\n          )}\n          style={{ bottom: BAR_H + PANEL_DOCK_GAP }}\n        >\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {active ? (\n              <motion.div\n                key={active.id}\n                variants={reduce ? REDUCED_CONTENT_VARIANTS : CONTENT_VARIANTS}\n                initial=\"enter\"\n                animate=\"center\"\n                exit=\"exit\"\n                transition={\n                  reduce ? { duration: 0.15, ease: EASE_OUT } : CONTENT_SPRING\n                }\n                className=\"w-max\"\n                style={{\n                  transformOrigin: \"top center\",\n                  willChange: \"transform, opacity, filter\",\n                }}\n              >\n                {active.content}\n              </motion.div>\n            ) : null}\n          </AnimatePresence>\n        </div>\n\n        <div\n          role=\"tablist\"\n          aria-label={t(\"label\")}\n          aria-orientation=\"horizontal\"\n          className={cn(\n            \"absolute bottom-0 left-0 z-20 flex w-full items-center justify-between gap-1 p-2\",\n            classNames?.bar,\n          )}\n          style={{ height: BAR_H }}\n        >\n          {items.map((item) => {\n            const isActive = item.id === visualActiveId;\n            const activeTabWidth = getActiveTabWidth(item);\n            const labelWidth = labelWidths[item.id] ?? 0;\n\n            return (\n              <motion.button\n                key={item.id}\n                type=\"button\"\n                role=\"tab\"\n                aria-selected={isActive}\n                aria-label={item.label}\n                onClick={() => setActive(isActive ? null : item.id)}\n                layout={reduce ? false : \"position\"}\n                animate={{\n                  width: active && isActive ? activeTabWidth : TAB_W,\n                }}\n                transition={reduce ? { duration: 0 } : TAB_CHANGE_SPRING}\n                className={cn(\n                  \"relative isolate flex h-9 min-w-8 shrink-0 items-center justify-center overflow-hidden rounded-[18px] px-2 text-sm font-medium outline-none\",\n                  \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n                  active && isActive && \"min-w-0 justify-start pl-2.5 pr-4\",\n                  isActive\n                    ? \"text-foreground\"\n                    : \"text-muted-foreground hover:text-foreground\",\n                  classNames?.tab,\n                  isActive && classNames?.activeTab,\n                )}\n              >\n                {isActive ? (\n                  <span\n                    className={cn(\n                      \"absolute inset-0 -z-10 rounded-[18px] bg-foreground/10\",\n                      classNames?.pill,\n                    )}\n                  />\n                ) : null}\n                <span\n                  className={cn(\n                    \"grid shrink-0 place-items-center\",\n                    classNames?.icon,\n                  )}\n                >\n                  {item.icon}\n                </span>\n                <motion.span\n                  aria-hidden\n                  initial={false}\n                  animate={\n                    reduce\n                      ? {\n                          width: isActive ? labelWidth : 0,\n                          opacity: isActive ? 1 : 0,\n                          marginLeft: isActive ? LABEL_GAP : 0,\n                          filter: \"blur(0px)\",\n                        }\n                      : {\n                          width: isActive ? labelWidth : 0,\n                          opacity: isActive ? 1 : 0,\n                          marginLeft: isActive ? LABEL_GAP : 0,\n                          filter: isActive ? \"blur(0px)\" : \"blur(3px)\",\n                        }\n                  }\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : isActive\n                        ? LABEL_OPEN\n                        : LABEL_CLOSE\n                  }\n                  className={cn(\n                    \"inline-block overflow-hidden whitespace-nowrap\",\n                    classNames?.label,\n                  )}\n                >\n                  {item.label}\n                </motion.span>\n              </motion.button>\n            );\n          })}\n        </div>\n      </motion.div>\n      <div\n        aria-hidden=\"true\"\n        className=\"pointer-events-none fixed left-0 top-0 -z-10 flex opacity-0\"\n      >\n        {items.map((item) => (\n          <span\n            className={cn(\n              \"whitespace-nowrap text-sm font-medium leading-none\",\n              classNames?.label,\n            )}\n            key={item.id}\n            ref={setLabelMeasureRef(item.id)}\n          >\n            {item.label}\n          </span>\n        ))}\n      </div>\n    </>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\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":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"components/previews/blocks/expandable-tabs.preview.tsx","type":"preview","content":"\"use client\";\n\nimport {\n  BadgeCheck,\n  Brush,\n  CalendarClock,\n  ChartSpline,\n  ChevronRight,\n  ClipboardCheck,\n  CloudUpload,\n  FileText,\n  Gauge,\n  GitBranch,\n  Images,\n  Inbox,\n  type LucideIcon,\n  Megaphone,\n  MessageCircle,\n  PackageOpen,\n  RefreshCw,\n  Rocket,\n  Siren,\n  SwatchBook,\n  UploadCloud,\n  Users,\n  Webhook,\n  Workflow,\n} from \"lucide-react\";\nimport { ExpandableTabs } from \"@/components/motion/expandable-tabs\";\n\nfunction Row({ icon: Icon, label }: { icon: LucideIcon; label: string }) {\n  return (\n    <button\n      type=\"button\"\n      className=\"flex h-8 w-full items-center gap-3 rounded-full px-3 text-left text-sm font-medium text-foreground transition-colors hover:bg-muted\"\n    >\n      <Icon className=\"h-4 w-4 text-muted-foreground\" />\n      <span className=\"flex-1\">{label}</span>\n      <ChevronRight className=\"h-4 w-4 text-muted-foreground\" />\n    </button>\n  );\n}\n\nfunction Menu({ rows }: { rows: { icon: LucideIcon; label: string }[] }) {\n  return (\n    <div className=\"flex w-[17.125rem] flex-col gap-0.5\">\n      {rows.map((r) => (\n        <Row key={r.label} icon={r.icon} label={r.label} />\n      ))}\n    </div>\n  );\n}\n\nexport function ExpandableTabsPreview() {\n  return (\n    <div className=\"flex min-h-88 w-full items-end justify-center\">\n      <ExpandableTabs\n        items={[\n          {\n            id: \"launch\",\n            label: \"Launch\",\n            icon: <Rocket className=\"h-4 w-4\" />,\n            content: (\n              <Menu\n                rows={[\n                  { icon: FileText, label: \"Release Brief\" },\n                  { icon: ClipboardCheck, label: \"Launch Checklist\" },\n                  { icon: Megaphone, label: \"Campaign Notes\" },\n                  { icon: CalendarClock, label: \"Rollout Calendar\" },\n                  { icon: CloudUpload, label: \"Ship Build\" },\n                ]}\n              />\n            ),\n          },\n          {\n            id: \"inbox\",\n            label: \"Inbox\",\n            icon: <Inbox className=\"h-4 w-4\" />,\n            content: (\n              <Menu\n                rows={[\n                  { icon: MessageCircle, label: \"Client Feedback\" },\n                  { icon: Users, label: \"Team Requests\" },\n                  { icon: BadgeCheck, label: \"Approval Notes\" },\n                ]}\n              />\n            ),\n          },\n          {\n            id: \"flows\",\n            label: \"Flows\",\n            icon: <Workflow className=\"h-4 w-4\" />,\n            content: (\n              <Menu\n                rows={[\n                  { icon: GitBranch, label: \"Trigger Map\" },\n                  { icon: Webhook, label: \"Webhook Runs\" },\n                  { icon: RefreshCw, label: \"Retry Queue\" },\n                ]}\n              />\n            ),\n          },\n          {\n            id: \"assets\",\n            label: \"Assets\",\n            icon: <PackageOpen className=\"h-4 w-4\" />,\n            content: (\n              <Menu\n                rows={[\n                  { icon: SwatchBook, label: \"Brand Kit\" },\n                  { icon: Images, label: \"Mockup Library\" },\n                  { icon: Brush, label: \"Design Tokens\" },\n                  { icon: UploadCloud, label: \"Export Queue\" },\n                ]}\n              />\n            ),\n          },\n          {\n            id: \"status\",\n            label: \"Status\",\n            icon: <ChartSpline className=\"h-4 w-4\" />,\n            content: (\n              <Menu\n                rows={[\n                  { icon: Gauge, label: \"Activation\" },\n                  { icon: ChartSpline, label: \"Conversion\" },\n                  { icon: Siren, label: \"Incidents\" },\n                ]}\n              />\n            ),\n          },\n        ]}\n      />\n    </div>\n  );\n}\n"}]}