{"slug":"bloom-menu","name":"Bloom Menu","description":"A button that morphs open into a menu and blooms iris-out from the center, the grid revealing in every direction with radially staggered items.","category":"blocks","source_url":"https://beui.dev/r/bloom-menu/raw","detail_url":"https://beui.dev/r/bloom-menu","raw_url":"https://beui.dev/r/bloom-menu/raw","page_url":"https://beui.dev/components/blocks/bloom-menu","markdown_url":"https://beui.dev/components/blocks/bloom-menu.md","published_at":"2026-06-26","updated_at":"2026-11-28","dependencies":["clsx","lucide-react","motion","react","tailwind-merge"],"internal":["@/components/motion/bloom-menu","@/lib/ease","@/lib/hooks/use-dismiss","@/lib/hooks/use-on-open","@/lib/hooks/use-row-cursor","@/lib/i18n","@/lib/layers","@/lib/utils"],"install_slugs":["bloom-menu"],"requires_theme":false,"props":[{"displayName":"BloomMenu","props":[{"name":"items","type":"MenuItem[]","required":false,"defaultValue":"[\n  { label: \"Doc\", icon: FileText },\n  { label: \"Board\", icon: LayoutGrid },\n  { label: \"Table\", icon: Table },\n  { label: \"Folder\", icon: FolderClosed },\n  { label: \"Reminder\", icon: Bell },\n  { label: \"Link\", icon: Link },\n]","description":"Grid items, each with a label and icon. Defaults to 6 create actions."},{"name":"onSelect","type":"((label: string) => void)","required":false,"defaultValue":null,"description":"Called with the item's label when an item is picked. The menu then closes."},{"name":"labels","type":"Partial<{ create: string; close: string; doc: string; board: string; table: string; folder: string; reminder: string; link: 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 element."}]}],"types":[{"name":"MenuItem","file":"components/motion/bloom-menu.tsx","fields":[{"name":"label","type":"string","required":true,"description":"Text under the icon. Also the item's key and the value sent to `onSelect`."},{"name":"icon","type":"ComponentType<{ className?: string }>","required":true,"description":"Icon component drawn above the label."}]}],"files":[{"path":"components/motion/bloom-menu.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/blocks/bloom-menu\n\nimport {\n  Bell,\n  FileText,\n  FolderClosed,\n  LayoutGrid,\n  Link,\n  Plus,\n  Table,\n  X,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentType,\n  type KeyboardEvent,\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useOnOpen } from \"@/lib/hooks/use-on-open\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\ntype MenuItem = {\n  /** Text under the icon. Also the item's key and the value sent to `onSelect`. */\n  label: string;\n  /** Icon component drawn above the label. */\n  icon: ComponentType<{ className?: string }>;\n};\n\nconst ITEMS: MenuItem[] = [\n  { label: \"Doc\", icon: FileText },\n  { label: \"Board\", icon: LayoutGrid },\n  { label: \"Table\", icon: Table },\n  { label: \"Folder\", icon: FolderClosed },\n  { label: \"Reminder\", icon: Bell },\n  { label: \"Link\", icon: Link },\n];\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const bloomMenuMessages = {\n  create: \"Create\",\n  close: \"Close menu\",\n  doc: \"Doc\",\n  board: \"Board\",\n  table: \"Table\",\n  folder: \"Folder\",\n  reminder: \"Reminder\",\n  link: \"Link\",\n};\n\nexport type BloomMenuMessages = typeof bloomMenuMessages;\n\n// Default items keep their English label as the id and `onSelect` value;\n// only the visible text is translated.\nconst ITEM_MESSAGE: Record<string, keyof BloomMenuMessages> = {\n  Doc: \"doc\",\n  Board: \"board\",\n  Table: \"table\",\n  Folder: \"folder\",\n  Reminder: \"reminder\",\n  Link: \"link\",\n};\n\n// Folder-open feel: a touch of overshoot as the panel expands, kept subtle.\nconst SPRING_FOLDER = {\n  type: \"spring\",\n  stiffness: 300,\n  damping: 32,\n  mass: 0.9,\n} as const;\n\nexport interface BloomMenuProps {\n  /** Grid items, each with a label and icon. Defaults to 6 create actions. */\n  items?: MenuItem[];\n  /** Called with the item's label when an item is picked. The menu then closes. */\n  onSelect?: (label: string) => void;\n  /** Override any built-in string. */\n  labels?: Partial<BloomMenuMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport function BloomMenu({\n  items = ITEMS,\n  onSelect,\n  labels,\n  className,\n}: BloomMenuProps) {\n  const t = useMessages(\"bloomMenu\", bloomMenuMessages, labels);\n  const [open, setOpen] = useState(false);\n  const reduce = useReducedMotion();\n  const layoutId = useId();\n  const menuId = useId();\n  const ref = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const itemRefs = useRef(new Map<string, HTMLButtonElement>());\n  // Set when the menu closes holding focus: the trigger is unmounted while\n  // open, so focus can only go back once it has mounted again.\n  const restoreFocus = useRef(false);\n\n  // The roving tab stop, resolved during render. Opening starts on the first\n  // item; arrow keys walk the grid from there.\n  const rows = useMemo(\n    () => items.map((item) => ({ id: item.label })),\n    [items],\n  );\n  const { activeIndex, moveTo } = useRowCursor(rows, \"\");\n  useOnOpen(open, () => moveTo(null));\n  const activeId = rows[activeIndex]?.id;\n\n  const close = useCallback((returnFocus: boolean) => {\n    if (returnFocus && ref.current?.contains(document.activeElement))\n      restoreFocus.current = true;\n    setOpen(false);\n  }, []);\n\n  useEffect(() => {\n    if (open) {\n      if (activeId !== undefined)\n        itemRefs.current.get(activeId)?.focus({ preventScroll: true });\n      return;\n    }\n    if (!restoreFocus.current) return;\n    restoreFocus.current = false;\n    triggerRef.current?.focus();\n  }, [open, activeId]);\n\n  const COLS = 3;\n  const onGridKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const last = rows.length - 1;\n    const step: Record<string, number> = {\n      ArrowRight: 1,\n      ArrowLeft: -1,\n      ArrowDown: COLS,\n      ArrowUp: -COLS,\n    };\n    let next: number | null = null;\n    if (event.key in step) {\n      const target = activeIndex + step[event.key];\n      next = target < 0 || target > last ? activeIndex : target;\n    } else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = last;\n    if (next === null) return;\n    event.preventDefault();\n    moveTo(rows[next].id);\n  };\n\n  const dismiss = useCallback(\n    (reason: DismissReason) => (reason === \"escape\" ? close(true) : setOpen(false)),\n    [close],\n  );\n  useDismiss(open, dismiss, ref);\n\n  const morph = reduce ? { duration: 0.15 } : SPRING_FOLDER;\n\n  return (\n    <div ref={ref} className={cn(\"relative inline-flex\", className)}>\n      {/* spacer fixes the anchor to the trigger size */}\n      <div className=\"h-11 w-36\" aria-hidden />\n\n      {/* Centering box sized to the OPEN panel and centered on the trigger.\n          place-items-center only centers an item that fits its cell, so the cell\n          must be as wide as the panel - otherwise the overflow left-anchors and\n          the panel expands rightward. The box is a fixed size per viewport (vw\n          doesn't change mid-animation), so its -translate centering never drifts\n          the way a content-sized wrapper would. Both states share its center, so\n          the morph grows from the middle outward in every direction. */}\n      <div className=\"pointer-events-none absolute left-1/2 top-1/2 z-30 grid h-[300px] w-[min(86vw,420px)] -translate-x-1/2 -translate-y-1/2 place-items-center [&>*]:pointer-events-auto\">\n        {/* popLayout pulls the exiting trigger out of grid flow at once, so the\n            grid never briefly holds two rows and shoves the panel off-center */}\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          {open ? (\n            <motion.div\n              key=\"panel\"\n              layoutId={layoutId}\n              transition={morph}\n              // Focus leaving the open menu closes it, as a click outside does.\n              onBlur={(event) => {\n                const next = event.relatedTarget;\n                if (next instanceof Node && !ref.current?.contains(next))\n                  close(false);\n              }}\n              style={{ borderRadius: 24 }}\n              className=\"w-[min(86vw,420px)] overflow-hidden border border-border bg-card\"\n            >\n              <motion.div\n                // `layout` lets framer undo the box's morph scaling so this\n                // content stays crisp instead of stretching with the resize.\n                layout\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                transition={{ delay: reduce ? 0 : 0.12, duration: 0.2 }}\n              >\n                {/* header */}\n                <div className=\"flex items-center justify-between border-b border-border px-4 py-3\">\n                  <span\n                    id={`${menuId}-label`}\n                    className=\"text-sm font-medium text-muted-foreground\"\n                  >\n                    {t(\"create\")}\n                  </span>\n                  <button\n                    type=\"button\"\n                    onClick={() => close(true)}\n                    aria-label={t(\"close\")}\n                    className=\"rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                  >\n                    <X className=\"h-4 w-4\" />\n                  </button>\n                </div>\n\n                {/* grid */}\n                <motion.div\n                  // Iris reveal: start as a small box at the grid center and open\n                  // outward to all four corners, so the menu grows from the middle\n                  // in every direction instead of wiping top-down.\n                  initial={\n                    reduce ? false : { clipPath: \"inset(45% 34% 45% 34%)\" }\n                  }\n                  animate={{ clipPath: \"inset(0% 0% 0% 0%)\" }}\n                  transition={{\n                    delay: reduce ? 0 : 0.08,\n                    duration: 0.45,\n                    ease: EASE_OUT,\n                  }}\n                  id={menuId}\n                  role=\"menu\"\n                  aria-labelledby={`${menuId}-label`}\n                  onKeyDown={onGridKeyDown}\n                  className=\"grid grid-cols-3\"\n                >\n                  {items.map((item, i) => {\n                    // Radial stagger: delay each item by its distance from the\n                    // grid center so the four corners animate together and the\n                    // open reads as center-out, not corner-by-corner.\n                    const cols = 3;\n                    const rows = Math.ceil(items.length / cols);\n                    const col = i % cols;\n                    const row = Math.floor(i / cols);\n                    const dist = Math.hypot(\n                      col - (cols - 1) / 2,\n                      row - (rows - 1) / 2,\n                    );\n                    return (\n                      <button\n                        key={item.label}\n                        ref={(node) => {\n                          if (node) itemRefs.current.set(item.label, node);\n                          else itemRefs.current.delete(item.label);\n                        }}\n                        type=\"button\"\n                        role=\"menuitem\"\n                        tabIndex={item.label === activeId ? 0 : -1}\n                        onFocus={() => moveTo(item.label)}\n                        onClick={() => {\n                          onSelect?.(item.label);\n                          close(true);\n                        }}\n                      // Static cell with hairline borders (no animated fill) so\n                      // the grid lines never flicker as items stagger in. Only the\n                      // inner content animates.\n                      className={cn(\n                        \"flex items-center justify-center px-3 py-6 text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:bg-muted/60 focus-visible:text-foreground\",\n                        col !== cols - 1 && \"border-r border-border\",\n                        row < rows - 1 && \"border-b border-border\",\n                      )}\n                    >\n                      <motion.span\n                        initial={\n                          reduce\n                            ? { opacity: 0 }\n                            : { opacity: 0, scale: 0.85, filter: \"blur(6px)\" }\n                        }\n                        animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                        transition={{\n                          ...SPRING_SWAP,\n                          delay: reduce ? 0 : 0.1 + dist * 0.07,\n                        }}\n                        className=\"flex flex-col items-center gap-2\"\n                      >\n                        <item.icon className=\"h-5 w-5\" />\n                        <span className=\"text-sm font-medium\">\n                          {items === ITEMS ? t(ITEM_MESSAGE[item.label]) : item.label}\n                        </span>\n                      </motion.span>\n                    </button>\n                    );\n                  })}\n                </motion.div>\n              </motion.div>\n            </motion.div>\n          ) : (\n            <motion.button\n              key=\"trigger\"\n              ref={triggerRef}\n              type=\"button\"\n              layoutId={layoutId}\n              transition={morph}\n              style={{ borderRadius: 22 }}\n              onClick={() => setOpen(true)}\n              aria-haspopup=\"menu\"\n              aria-expanded={open}\n              onKeyDown={(event) => {\n                if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n                  event.preventDefault();\n                  setOpen(true);\n                }\n              }}\n              whileTap={reduce ? undefined : { scale: 0.97 }}\n              className=\"inline-flex h-11 w-36 items-center justify-center border border-border bg-card text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              {/* own `layout` counter-scales the label so it stays crisp while the\n                  button box morphs, instead of stretching with it */}\n              <motion.span\n                layout\n                className=\"inline-flex items-center gap-2 whitespace-nowrap\"\n              >\n                {t(\"create\")}\n                <Plus className=\"h-4 w-4\" />\n              </motion.span>\n            </motion.button>\n          )}\n        </AnimatePresence>\n      </div>\n    </div>\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/hooks/use-on-open.ts","type":"util","content":"\"use client\";\n\nimport { useState } from \"react\";\n\n/**\n * Runs `start` during the render in which `open` becomes true.\n *\n * Opening a list starts a fresh session - an empty query, the highlight back at\n * the top - and that is a resolution, not a side effect: a passive effect runs\n * after the commit, so the new session would carry the last one's state for a\n * window in which a key press can land.\n *\n * `start` may only set state belonging to the calling component. Anything that\n * reaches outside it - a consumer's callback, a DOM write, moving focus - is a\n * side effect, and React rejects a callback that sets another component's state\n * during this one's render. Put those in an effect keyed to `open`.\n */\nexport function useOnOpen(open: boolean, start: () => void) {\n  const [wasOpen, setWasOpen] = useState(open);\n  if (open !== wasOpen) {\n    setWasOpen(open);\n    if (open) start();\n  }\n}\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\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/bloom-menu.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { BloomMenu } from \"@/components/motion/bloom-menu\";\n\nexport function BloomMenuPreview() {\n  return (\n    <div className=\"flex min-h-[420px] w-full items-start justify-center pt-24\">\n      <BloomMenu />\n    </div>\n  );\n}\n"}]}