{"$schema":"https:\/\/ui.particle.academy\/schema\/registry-item.json","name":"image-pill","type":"registry:ui","title":"ImagePill","description":"The composer's image attachment pill with a thumbnail preview on hover and keyboard focus - controlled open, src, file or a lazy loadThumbnail with loading and error states, so sent messages show the same pill.","package":"react-fancy","dependencies":["tailwind-merge"],"registryDependencies":["popover","portal"],"files":[{"path":"components\/fancy\/image-pill\/ImagePill.tsx","content":"import { forwardRef, useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"..\/lib\/utils\/cn\";\nimport { useControllableState } from \"..\/lib\/hooks\/use-controllable-state\";\nimport { Popover } from \"..\/popover\";\nimport type { ImagePillProps, ImagePillThumbnailState } from \".\/ImagePill.types\";\n\n\/*\n * The classes the composer's image pill has always had. ImagePill IS that pill\n * now (InlinePill draws it), so a change here is a change to every composer.\n *\/\nconst PILL_BASE =\n  \"inline-flex select-none items-center rounded-md px-2 py-0.5 text-xs leading-5 transition-colors\";\n\/*\n * rose-800 on rose-100: rose-600 was 3.77:1 at the pill's 12px (axe\n * `color-contrast`, every-component brief K26). rose-300 on the dark tint\n * clears AA on the darkest surface under it.\n *\/\nconst IMAGE_PILL =\n  \"bg-rose-100 font-medium text-rose-800 dark:bg-rose-500\/20 dark:text-rose-300\";\n\/** Merged onto the Popover panel's own defaults: tighter padding for a preview. *\/\nconst PREVIEW_BASE = \"max-w-xs whitespace-pre-wrap break-all p-2 text-xs\";\n\nconst DEFAULT_LABELS = {\n  loading: \"Loading preview\u2026\",\n  error: \"Preview unavailable\",\n};\n\n\/**\n * The thumbnail, mounted only while the preview is open. A File's object URL is\n * made here and revoked on close, so a thread of a hundred sent images holds no\n * object URLs until one is looked at.\n *\n * If the image cannot be shown (a Content-Security-Policy without `blob:` in\n * `img-src` is the usual reason) the label is shown instead. A broken `<img>`\n * with an empty `alt` renders as nothing at all, which is how a preview ends up\n * as an empty box.\n *\/\nfunction Thumb({\n  src,\n  file,\n  label,\n  failed,\n  onFailed,\n}: {\n  src?: string;\n  file?: Blob | null;\n  label: string;\n  failed: boolean;\n  onFailed: () => void;\n}) {\n  const [objectUrl, setObjectUrl] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (src || !file || typeof URL.createObjectURL !== \"function\") return;\n    const made = URL.createObjectURL(file);\n    setObjectUrl(made);\n    return () => {\n      URL.revokeObjectURL(made);\n      setObjectUrl(null);\n    };\n  }, [src, file]);\n\n  const url = src ?? objectUrl;\n  return url && !failed ? (\n    <img src={url} alt={label} onError={onFailed} className=\"block max-h-40 max-w-[16rem] rounded\" \/>\n  ) : (\n    <span>{label}<\/span>\n  );\n}\n\n\/**\n * ImagePill: an image attachment as a compact pill, with its thumbnail in a hover\n * popover. The pill the composer (PromptInput, Composer) draws for a pasted\n * image, exported so a thread can show the same pill on a sent message.\n *\n * - The preview opens on hover AND on keyboard focus; blur and Escape close it.\n *   `open` \/ `onOpenChange` control it.\n * - The thumbnail comes from `src`, a `file`, or `loadThumbnail()`, which is\n *   called once, on the first hover or focus, with loading and error states.\n * - Handles: `data-react-fancy-image-pill` with `data-state=\"open|closed\"` and\n *   `data-thumbnail` (see `ImagePillThumbnailState`) on the pill;\n *   `data-react-fancy-image-pill-preview` on the preview content. Any `data-*`\n *   you pass lands on the pill.\n *\/\nexport const ImagePill = forwardRef<HTMLSpanElement, ImagePillProps>(function ImagePill(\n  {\n    label,\n    src,\n    file,\n    loadThumbnail,\n    open: controlledOpen,\n    defaultOpen = false,\n    onOpenChange,\n    placement = \"top\",\n    preview,\n    previewClassName,\n    previewProps,\n    labels: labelsProp,\n    className,\n    onFocus,\n    onBlur,\n    ...rest\n  },\n  ref,\n) {\n  const labels = { ...DEFAULT_LABELS, ...labelsProp };\n  const [open, setOpenState] = useControllableState(controlledOpen, defaultOpen, onOpenChange);\n\n  const [loaded, setLoaded] = useState<{ status: \"idle\" | \"loading\" | \"ready\" | \"error\"; url?: string }>({\n    status: \"idle\",\n  });\n  const [imgFailed, setImgFailed] = useState(false);\n  const requested = useRef(false);\n  const loaderRef = useRef(loadThumbnail);\n  loaderRef.current = loadThumbnail;\n  const alive = useRef(true);\n  useEffect(() => {\n    alive.current = true;\n    return () => {\n      alive.current = false;\n    };\n  }, []);\n\n  \/** Ask for the thumbnail, once for the life of the pill. *\/\n  const ensureLoad = useCallback(() => {\n    const load = loaderRef.current;\n    if (!load || requested.current) return;\n    requested.current = true;\n    setLoaded({ status: \"loading\" });\n    let pending: Promise<string>;\n    try {\n      pending = Promise.resolve(load());\n    } catch (error) {\n      pending = Promise.reject(error);\n    }\n    pending.then(\n      (url) => {\n        if (!alive.current) return;\n        setLoaded(typeof url === \"string\" && url ? { status: \"ready\", url } : { status: \"error\" });\n      },\n      () => {\n        if (alive.current) setLoaded({ status: \"error\" });\n      },\n    );\n  }, []);\n\n  \/** Every request to open, from hover or focus, also asks for the thumbnail. *\/\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next) ensureLoad();\n      setOpenState(next);\n    },\n    [ensureLoad, setOpenState],\n  );\n\n  \/\/ A host that opens it through `open` gets the thumbnail too.\n  useEffect(() => {\n    if (open) ensureLoad();\n  }, [open, ensureLoad]);\n\n  \/\/ A new image source is a new chance to load.\n  useEffect(() => setImgFailed(false), [src, file, loaded.url]);\n\n  const usesLoader = !src && loadThumbnail !== undefined;\n  const thumbUrl = src ?? (usesLoader ? loaded.url : undefined);\n  const thumbnail: ImagePillThumbnailState =\n    imgFailed\n      ? \"error\"\n      : src\n        ? \"ready\"\n        : usesLoader\n          ? loaded.status\n          : file\n            ? \"ready\"\n            : \"none\";\n\n  let content;\n  if (preview !== undefined) {\n    content = preview;\n  } else if (usesLoader && loaded.status === \"loading\") {\n    content = <span data-react-fancy-image-pill-loading=\"\">{labels.loading}<\/span>;\n  } else if (usesLoader && loaded.status === \"error\") {\n    content = <span data-react-fancy-image-pill-error=\"\">{labels.error}<\/span>;\n  } else {\n    content = (\n      <Thumb\n        src={thumbUrl}\n        file={usesLoader ? undefined : file}\n        label={label}\n        failed={imgFailed}\n        onFailed={() => setImgFailed(true)}\n      \/>\n    );\n  }\n\n  return (\n    <Popover hover open={open} onOpenChange={setOpen} placement={placement}>\n      <Popover.Trigger>\n        <span\n          {...rest}\n          ref={ref}\n          data-react-fancy-image-pill=\"\"\n          data-state={open ? \"open\" : \"closed\"}\n          data-thumbnail={thumbnail}\n          role=\"img\"\n          tabIndex={0}\n          aria-label={label}\n          onFocus={(e) => {\n            onFocus?.(e);\n            setOpen(true);\n          }}\n          onBlur={(e) => {\n            onBlur?.(e);\n            setOpen(false);\n          }}\n          className={cn(PILL_BASE, IMAGE_PILL, className)}\n        >\n          {label}\n        <\/span>\n      <\/Popover.Trigger>\n      <Popover.Content className={cn(PREVIEW_BASE, previewClassName)}>\n        <span\n          {...previewProps}\n          data-react-fancy-image-pill-preview=\"\"\n          aria-busy={thumbnail === \"loading\" || undefined}\n        >\n          {content}\n        <\/span>\n      <\/Popover.Content>\n    <\/Popover>\n  );\n});\n\nImagePill.displayName = \"ImagePill\";\n","type":"registry:ui","target":"components\/fancy\/image-pill\/ImagePill.tsx"},{"path":"components\/fancy\/image-pill\/ImagePill.types.ts","content":"import type { HTMLAttributes, ReactNode } from \"react\";\nimport type { Placement } from \"..\/lib\/utils\/types\";\n\n\/** Every word ImagePill shows, for translation. *\/\nexport interface ImagePillLabels {\n  \/** Shown in the preview while `loadThumbnail` is pending. @default \"Loading preview\u2026\" *\/\n  loading?: string;\n  \/** Shown in the preview when `loadThumbnail` rejects. @default \"Preview unavailable\" *\/\n  error?: string;\n}\n\n\/**\n * Where the thumbnail stands, on the pill as `data-thumbnail`:\n * `none` (no source), `idle` (a `loadThumbnail` not called yet), `loading`,\n * `ready`, `error` (the loader rejected or the image failed to load).\n *\/\nexport type ImagePillThumbnailState = \"none\" | \"idle\" | \"loading\" | \"ready\" | \"error\";\n\nexport interface ImagePillProps extends Omit<HTMLAttributes<HTMLSpanElement>, \"children\"> {\n  \/** The pill's text, the thumbnail's `alt` and the accessible name. *\/\n  label: string;\n  \/** A thumbnail URL. Wins over `file` and `loadThumbnail`. *\/\n  src?: string;\n  \/** A File or Blob to preview. Its object URL exists only while the preview is open. *\/\n  file?: Blob | null;\n  \/**\n   * Fetch the thumbnail URL lazily: called ONCE, on the first hover or focus,\n   * never on render or on the server. Pending shows a loading state; a\n   * rejection shows the error state and is not retried.\n   *\/\n  loadThumbnail?: () => Promise<string>;\n  \/** Whether the preview is open, controlled. *\/\n  open?: boolean;\n  \/** The starting open state, uncontrolled. @default false *\/\n  defaultOpen?: boolean;\n  \/** Called when hover, focus, blur or Escape asks to open or close the preview. *\/\n  onOpenChange?: (open: boolean) => void;\n  \/** Where the preview opens. Flips when there is no room. @default \"top\" *\/\n  placement?: Placement;\n  \/** Replaces the preview's content (the thumbnail). *\/\n  preview?: ReactNode;\n  \/** Merged onto the preview panel's classes. *\/\n  previewClassName?: string;\n  \/** Attributes for the preview content's wrapper, e.g. a `data-*` handle of your own. *\/\n  previewProps?: HTMLAttributes<HTMLSpanElement> & { [data: `data-${string}`]: string | undefined };\n  \/** Words, for translation. *\/\n  labels?: ImagePillLabels;\n}\n","type":"registry:ui","target":"components\/fancy\/image-pill\/ImagePill.types.ts"},{"path":"components\/fancy\/image-pill\/index.ts","content":"export { ImagePill } from \".\/ImagePill\";\nexport type { ImagePillProps, ImagePillLabels, ImagePillThumbnailState } from \".\/ImagePill.types\";\n","type":"registry:ui","target":"components\/fancy\/image-pill\/index.ts"},{"path":"components\/fancy\/lib\/utils\/cn.ts","content":"import { twMerge } from \"tailwind-merge\";\n\n\/**\n * A class value: a string, a number, a conditional map, an array of any of\n * those, or nothing. Mirrors what `clsx` accepted, because every component in\n * this package already passes these shapes.\n *\/\nexport type ClassValue =\n  | string\n  | number\n  | bigint\n  | null\n  | undefined\n  | false\n  | ClassDictionary\n  | ClassValue[];\n\ntype ClassDictionary = Record<string, unknown>;\n\n\/**\n * Flatten class values into a space-separated string.\n *\n * This was `clsx` until 2026-08-19. It is roughly twenty lines of logic, it\n * shipped as a RUNTIME dependency to every consumer of this package, and its\n * last commit was 801 days old \u2014 so it fell to the rule that third-party code\n * must be both approved and actively maintained. Owning it costs less than\n * carrying it.\n *\n * `tailwind-merge` deliberately stays: deciding which of two conflicting\n * Tailwind utilities wins requires modelling the entire utility space, which is\n * emphatically not twenty lines, and it is actively maintained.\n *\n * Falsy values are dropped \u2014 including `0` and `\"\"`, which is what `clsx` did\n * and what `tests\/cn.test.ts` pins. A truthy number is kept, because digits are\n * legal class names. `bigint` is admitted because clsx's signature did and\n * the compiler proved it reachable from two call sites here.\n *\/\nfunction flatten(value: ClassValue): string {\n  if (!value) return \"\";\n\n  if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\") {\n    return String(value);\n  }\n\n  if (Array.isArray(value)) {\n    let out = \"\";\n    for (const item of value) {\n      const part = flatten(item);\n      if (part) out = out ? `${out} ${part}` : part;\n    }\n    return out;\n  }\n\n  let out = \"\";\n  for (const key in value) {\n    if (value[key]) out = out ? `${out} ${key}` : key;\n  }\n  return out;\n}\n\nexport function cn(...inputs: ClassValue[]): string {\n  return twMerge(flatten(inputs));\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/cn.ts"},{"path":"components\/fancy\/lib\/hooks\/use-controllable-state.ts","content":"import { useCallback, useRef, useState } from \"react\";\n\n\/**\n * One state slot that works controlled or uncontrolled.\n *\n * ---------------------------------------------------------------------------\n * Why the value is tracked in a ref (fixed 5.32.0)\n * ---------------------------------------------------------------------------\n *\n * This resolved a functional update against the RENDER CLOSURE's `value` and then\n * handed React an already-computed value:\n *\n *     const nextValue = typeof next === \"function\" ? next(value) : next;\n *     setUncontrolledValue(nextValue);\n *\n * So `setValue(fn)` twice in one batch had both calls compute from the same stale\n * `value`, and **the first update was silently lost.** React's own `setState`\n * updater form does not have that problem precisely because React resolves it\n * against the latest state; passing a pre-computed value gives that up.\n *\n * Found by a hook test that paste-held two items inside one `act()` and got one.\n * It is not an exotic case \u2014 any caller that loops, or handles two events in a\n * batch, hits it, and the symptom is a dropped update with nothing to indicate one\n * happened.\n *\n * The fix cannot be \"pass the updater to React\", because `onChange` has to be\n * called with the resulting value and an updater must stay pure \u2014 React may invoke\n * it twice (StrictMode), which would fire `onChange` twice. So the previous value\n * comes from a ref that is re-synced from the authoritative `value` on every render\n * and advanced on every set. Within a batch the ref carries intent; after a render\n * the real value wins.\n *\n * A side effect worth having: `setValue` no longer depends on `value`, so it is\n * stable for the life of the component.\n *\/\nexport function useControllableState<T>(\n  controlledValue: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n): [T, (value: T | ((prev: T) => T)) => void] {\n  const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);\n  const isControlled = controlledValue !== undefined;\n  const value = isControlled ? controlledValue : uncontrolledValue;\n\n  const onChangeRef = useRef(onChange);\n  onChangeRef.current = onChange;\n\n  \/\/ Re-synced every render from whichever side owns the value. A controlled parent\n  \/\/ that ignores `onChange` therefore wins on the next render rather than being\n  \/\/ overridden by what this hook optimistically recorded.\n  const valueRef = useRef(value);\n  valueRef.current = value;\n\n  const isControlledRef = useRef(isControlled);\n  isControlledRef.current = isControlled;\n\n  const setValue = useCallback((next: T | ((prev: T) => T)) => {\n    const nextValue =\n      typeof next === \"function\"\n        ? (next as (prev: T) => T)(valueRef.current)\n        : next;\n\n    \/\/ Advance the ref BEFORE notifying, so a second call in the same batch builds\n    \/\/ on this one instead of on what the last render saw.\n    valueRef.current = nextValue;\n\n    if (!isControlledRef.current) {\n      setUncontrolledValue(nextValue);\n    }\n\n    onChangeRef.current?.(nextValue);\n  }, []);\n\n  return [value, setValue];\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/hooks\/use-controllable-state.ts"},{"path":"components\/fancy\/lib\/utils\/types.ts","content":"import type { ElementType } from \"react\";\n\nexport type Size = \"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\";\n\n\/**\n * What a navigation primitive owes a router.\n *\n * Every nav surface here \u2014 `Navbar.Item`, `Sidebar.Item`, `Menu.Item`,\n * `MobileMenu.Item`, `Breadcrumbs.Item` \u2014 used to hardcode a plain `<a href>`.\n * That is a FULL PAGE LOAD in every client-routed app, and the only way around\n * it was to nest a router `<Link>` inside the item: an anchor inside an anchor,\n * which is invalid HTML and the same nested-anchor shape that already cost this\n * suite an SSR hydration bug.\n *\n * `as` is the seam {@link ButtonProps.as} already had. It is router-agnostic on\n * purpose \u2014 one prop serves Inertia, TanStack Router, React Router and Next\n * rather than a package per router:\n *\n * ```tsx\n * \/\/ href-based routers (Inertia, Next)\n * <Navbar.Item as={Link} href=\"\/dashboard\">Dashboard<\/Navbar.Item>\n *\n * \/\/ to-based routers (TanStack Router, React Router) \u2014 `to` reaches the Link\n * \/\/ through the forwarded rest props\n * <Navbar.Item as={Link} to=\"\/dashboard\">Dashboard<\/Navbar.Item>\n * ```\n *\n * Link mode engages on `href` OR `as`, because a `to`-based router never passes\n * an `href` and would otherwise silently render the non-interactive fallback.\n *\/\nexport interface NavigableProps {\n  \/** Target URL. Renders link mode with a plain `<a>` unless `as` is given. *\/\n  href?: string;\n  \/**\n   * Link-mode element override \u2014 the component to render INSTEAD of the plain\n   * `<a>`, e.g. a router's `<Link>` so navigation happens client-side. Receives\n   * `className`, the item's `data-*` handles, and every unrecognized prop, so\n   * router-specific props (`to`, `params`, `preload`, `search`) pass straight\n   * through. Ignored in button mode.\n   *\/\n  as?: ElementType;\n}\n\n\/**\n * The full Tailwind v4 named color palette \u2014 every default hue, including all\n * five gray families \u2014 plus `brand`, the host's own colour. Components that\n * accept a `color` should type it as this so the whole palette is available.\n *\n * `brand` is not a hue. It resolves through three CSS variables the host sets\n * once, rather than through a Tailwind scale:\n *\n *   `--color-brand`, `--color-brand-contrast`, `--color-brand-hover`\n *\n * Three rather than one because a generated hover assumes \"same hue, darker\",\n * and a brand palette need not work that way \u2014 navy whose hover is gold cannot\n * be derived from navy by any amount of arithmetic. The host states it.\n *\/\nexport type Color =\n  \/\/ the host's own colour, resolved from CSS variables (see styles.css)\n  | \"brand\"\n  \/\/ grays\n  | \"slate\"\n  | \"gray\"\n  | \"zinc\"\n  | \"neutral\"\n  | \"stone\"\n  \/\/ hues\n  | \"red\"\n  | \"orange\"\n  | \"amber\"\n  | \"yellow\"\n  | \"lime\"\n  | \"green\"\n  | \"emerald\"\n  | \"teal\"\n  | \"cyan\"\n  | \"sky\"\n  | \"blue\"\n  | \"indigo\"\n  | \"violet\"\n  | \"purple\"\n  | \"fuchsia\"\n  | \"pink\"\n  | \"rose\";\n\n\/** Every value of {@link Color}, for building exhaustive class maps. *\/\nexport const COLORS = [\n  \"brand\",\n  \"slate\", \"gray\", \"zinc\", \"neutral\", \"stone\",\n  \"red\", \"orange\", \"amber\", \"yellow\", \"lime\", \"green\", \"emerald\", \"teal\",\n  \"cyan\", \"sky\", \"blue\", \"indigo\", \"violet\", \"purple\", \"fuchsia\", \"pink\", \"rose\",\n] as const satisfies readonly Color[];\n\nexport type Variant = \"solid\" | \"outline\" | \"ghost\" | \"soft\";\n\n\/** Button accepts the full Tailwind v4 palette (alias of {@link Color}). *\/\nexport type ButtonColor = Color;\n\n\/**\n * @deprecated Renamed to {@link ButtonColor}. `ActionColor` remains as an alias\n * for backward compatibility and will be removed in a future major version.\n *\/\nexport type ActionColor = ButtonColor;\n\nexport type Placement =\n  | \"top\"\n  | \"bottom\"\n  | \"left\"\n  | \"right\"\n  | \"top-start\"\n  | \"top-end\"\n  | \"bottom-start\"\n  | \"bottom-end\";\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/types.ts"},{"path":"components\/fancy\/lib\/utils\/trigger-child.ts","content":"import {\n  cloneElement,\n  Fragment,\n  isValidElement,\n  useEffect,\n  useRef,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n} from \"react\";\nimport { cn } from \".\/cn\";\nimport { composeRefs } from \".\/compose-refs\";\n\n\/**\n * How a popup trigger (Dropdown.Trigger, Popover.Trigger) treats its child.\n *\n * The ARIA that says \"this opens a popup\" (`aria-haspopup`, `aria-expanded`,\n * `aria-controls`) belongs on the element a screen reader focuses. Before\n * 6.22.2 both triggers put it on a role-less wrapper `<span>`, where axe flags\n * it (`aria-allowed-attr`, critical) and no screen reader announces it.\n *\n * - `clone`: the child is one element that is, or renders, the focusable\n *   control. The trigger merges its props onto it (the asChild pattern) and\n *   renders no wrapper. `aria` is false when the child's explicit role cannot\n *   carry popup ARIA (a `role=\"img\"` preview pill); `role` is set when a\n *   focusable host element has no role of its own (`<span tabIndex={0}>`), so\n *   the ARIA lands on a `button` rather than on another role-less element.\n * - `wrap`: the child is text, several nodes, a fragment, or a host element\n *   nothing can focus. The trigger renders its own element around it.\n *\/\nexport type TriggerChild =\n  | { mode: \"clone\"; element: ReactElement<Record<string, unknown>>; aria: boolean; role?: \"button\" }\n  | { mode: \"wrap\" };\n\n\/** The `aria-haspopup` values that name a kind of popup (WAI-ARIA 1.2). *\/\nexport type PopupKind = \"menu\" | \"listbox\" | \"tree\" | \"grid\" | \"dialog\";\n\n\/**\n * The ARIA a popup trigger carries: what it opens, whether it is open, and,\n * while it is, the id of the popup (which exists in the DOM only then).\n *\/\nexport function popupTriggerAria(kind: PopupKind, open: boolean, popupId: string) {\n  return {\n    \"aria-haspopup\": kind,\n    ...disclosureAria(open, popupId),\n  };\n}\n\n\/**\n * The ARIA of a disclosure button: whether the region it shows is open and,\n * while it is, that region's id. No `aria-haspopup`, which would promise a\n * menu, listbox or dialog the region is not (a plain panel of links).\n *\/\nexport function disclosureAria(open: boolean, regionId: string) {\n  return {\n    \"aria-expanded\": open,\n    \"aria-controls\": open ? regionId : undefined,\n  };\n}\n\n\/** Roles that allow both `aria-expanded` and `aria-haspopup` (WAI-ARIA 1.2). *\/\nconst POPUP_ROLES = new Set([\n  \"button\",\n  \"combobox\",\n  \"gridcell\",\n  \"link\",\n  \"menuitem\",\n  \"menuitemcheckbox\",\n  \"menuitemradio\",\n  \"tab\",\n  \"treeitem\",\n]);\n\nconst BUTTON_INPUTS = new Set([\"button\", \"submit\", \"reset\", \"image\"]);\n\nexport function classifyTriggerChild(children: ReactNode): TriggerChild {\n  if (!isValidElement(children) || children.type === Fragment) return { mode: \"wrap\" };\n  const element = children as ReactElement<Record<string, unknown>>;\n  const props = element.props;\n  const role = typeof props.role === \"string\" ? props.role : undefined;\n\n  \/\/ A component (Button, a consumer's own): it renders the focusable control\n  \/\/ and is expected to forward its props and ref onto it.\n  if (typeof element.type !== \"string\") {\n    return { mode: \"clone\", element, aria: role === undefined || POPUP_ROLES.has(role) };\n  }\n\n  const tag = element.type;\n  const tabIndex = props.tabIndex === undefined ? undefined : Number(props.tabIndex);\n  let native: \"popup\" | \"other\" | null = null;\n  if (tag === \"button\" || tag === \"summary\" || tag === \"select\") native = \"popup\";\n  else if (tag === \"a\" && props.href !== undefined) native = \"popup\";\n  else if (tag === \"input\" && props.type !== \"hidden\") {\n    native = BUTTON_INPUTS.has(String(props.type)) ? \"popup\" : \"other\";\n  } else if (tag === \"textarea\") native = \"other\";\n\n  const focusable = native !== null || (tabIndex !== undefined && tabIndex >= 0);\n  if (!focusable) return { mode: \"wrap\" };\n\n  if (role !== undefined) return { mode: \"clone\", element, aria: POPUP_ROLES.has(role) };\n  if (native === \"popup\") return { mode: \"clone\", element, aria: true };\n  if (native === \"other\") return { mode: \"clone\", element, aria: false };\n  return { mode: \"clone\", element, aria: true, role: \"button\" };\n}\n\n\/** The child's own ref (React 19 passes it as a prop). *\/\nexport function triggerChildRef(target: TriggerChild): Ref<HTMLElement> | undefined {\n  return target.mode === \"clone\" ? (target.element.props.ref as Ref<HTMLElement> | undefined) : undefined;\n}\n\n\/**\n * Merge a trigger's props onto its child.\n *\n * `owned` always applies: the popup's ARIA, its stable handle, its handlers.\n * A handler the child already has runs first, then the trigger's, so a child\n * that calls `preventDefault()` still opts out. `fallback` (props forwarded to\n * the trigger by its caller) fills only what the child leaves unset, except\n * `className`, which is joined. `ref` should already include the child's own.\n *\/\nexport function cloneTriggerChild(\n  element: ReactElement<Record<string, unknown>>,\n  {\n    owned,\n    fallback = {},\n    ref,\n  }: { owned: Record<string, unknown>; fallback?: Record<string, unknown>; ref: Ref<HTMLElement> },\n): ReactElement {\n  const own = element.props;\n  const merged: Record<string, unknown> = {};\n\n  for (const [k, v] of Object.entries(fallback)) {\n    if (k === \"className\") continue;\n    if (own[k] === undefined) merged[k] = v;\n  }\n  if (fallback.className !== undefined) {\n    \/\/ A child whose `className` styles something other than the element it\n    \/\/ renders (Tooltip: the bubble) names the prop that reaches that element.\n    const key = triggerClassNameProp(element.type) ?? \"className\";\n    merged[key] = cn(fallback.className as string, own[key] as string | undefined);\n  }\n\n  for (const [k, v] of Object.entries(owned)) {\n    const mine = own[k] ?? merged[k];\n    if (\/^on[A-Z]\/.test(k) && typeof v === \"function\" && typeof mine === \"function\") {\n      merged[k] = (...args: unknown[]) => {\n        (mine as (...a: unknown[]) => void)(...args);\n        (v as (...a: unknown[]) => void)(...args);\n      };\n    } else {\n      merged[k] = v;\n    }\n  }\n\n  merged.ref = ref;\n  return cloneElement(element, merged);\n}\n\n\/**\n * Static a component sets when its `className` does NOT style the element it\n * renders, naming the prop that does. Tooltip sets it to `\"triggerClassName\"`:\n * its `className` styles the bubble, so a trigger's classes go to its child.\n *\/\nexport const TRIGGER_CLASS_NAME_PROP = Symbol.for(\"react-fancy.triggerClassNameProp\");\n\nfunction triggerClassNameProp(type: unknown): string | undefined {\n  if ((typeof type !== \"function\" && typeof type !== \"object\") || type === null) return undefined;\n  const value = (type as Record<symbol, unknown>)[TRIGGER_CLASS_NAME_PROP];\n  return typeof value === \"string\" ? value : undefined;\n}\n\n\/\/ Bundlers replace `process.env.NODE_ENV` textually; without one, the\n\/\/ reference throws and we read that as production.\ndeclare const process: { env: Record<string, string | undefined> };\n\nfunction isDev(): boolean {\n  try {\n    return process.env.NODE_ENV !== \"production\";\n  } catch {\n    return false;\n  }\n}\n\n\/**\n * Development only: warn once when a trigger's `className` did not reach the\n * element the trigger anchors to. The trigger merges `className` onto its\n * child, and a child component decides where that goes; one that styles an\n * inner or portalled element with it (a bubble, a label) leaves the control\n * without the class, which fails silently. \"None of the classes are on the\n * element\" is the test, so a class that tailwind-merge drops in favour of the\n * child's own conflicting one does not trip it.\n *\/\nexport function useTriggerClassNameCheck(\n  anchorRef: RefObject<HTMLElement | null>,\n  className: string | undefined,\n  name: string,\n): void {\n  const warned = useRef(false);\n  useEffect(() => {\n    if (warned.current || !className || !isDev()) return;\n    const el = anchorRef.current;\n    if (!el) return;\n    const tokens = className.split(\/\\s+\/).filter(Boolean);\n    if (tokens.length === 0 || tokens.some((t) => el.classList.contains(t))) return;\n    warned.current = true;\n    console.warn(\n      `[react-fancy] ${name} className=\"${className}\" did not reach the element it anchors to ` +\n        `(<${el.tagName.toLowerCase()}>). The trigger merges className onto its child, and this child ` +\n        \"styles something else with it. Put the classes on the child's own element instead.\",\n    );\n  });\n}\n\nexport { composeRefs };\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/trigger-child.ts"},{"path":"components\/fancy\/lib\/hooks\/use-floating-position.ts","content":"import { useCallback, useEffect, useState, type RefObject } from \"react\";\nimport type { Placement } from \"..\/utils\/types\";\nimport { directionOf, type Direction } from \"..\/utils\/direction\";\n\ninterface FloatingPosition {\n  x: number;\n  y: number;\n  placement: Placement;\n  \/**\n   * The anchor's writing direction. Put it on the floating element as `dir`:\n   * a floating element is portalled to `<body>`, so without it a `dir` set on\n   * a wrapper (rather than on `<html>`) would not reach the popup.\n   *\/\n  dir: Direction;\n}\n\ninterface UseFloatingPositionOptions {\n  placement?: Placement;\n  offset?: number;\n  enabled?: boolean;\n}\n\nfunction getPosition(\n  anchor: DOMRect,\n  floating: DOMRect,\n  placement: Placement,\n  offset: number,\n  dir: Direction = \"ltr\",\n): FloatingPosition {\n  let x = 0;\n  let y = 0;\n  const base = placement.split(\"-\")[0] as \"top\" | \"bottom\" | \"left\" | \"right\";\n  const align = placement.split(\"-\")[1] as \"start\" | \"end\" | undefined;\n\n  switch (base) {\n    case \"top\":\n      x = anchor.left + anchor.width \/ 2 - floating.width \/ 2;\n      y = anchor.top - floating.height - offset;\n      break;\n    case \"bottom\":\n      x = anchor.left + anchor.width \/ 2 - floating.width \/ 2;\n      y = anchor.bottom + offset;\n      break;\n    case \"left\":\n      x = anchor.left - floating.width - offset;\n      y = anchor.top + anchor.height \/ 2 - floating.height \/ 2;\n      break;\n    case \"right\":\n      x = anchor.right + offset;\n      y = anchor.top + anchor.height \/ 2 - floating.height \/ 2;\n      break;\n  }\n\n  \/\/ `start` \/ `end` are LOGICAL: `bottom-start` lines the popup up with the\n  \/\/ anchor's inline-start edge, which is its RIGHT edge in RTL. The base side\n  \/\/ (`left` \/ `right`) stays physical, as the names say.\n  if (base === \"top\" || base === \"bottom\") {\n    const startEdge = dir === \"rtl\" ? anchor.right - floating.width : anchor.left;\n    const endEdge = dir === \"rtl\" ? anchor.left : anchor.right - floating.width;\n    if (align === \"start\") x = startEdge;\n    else if (align === \"end\") x = endEdge;\n  }\n\n  if (base === \"left\" || base === \"right\") {\n    if (align === \"start\") y = anchor.top;\n    else if (align === \"end\") y = anchor.bottom - floating.height;\n  }\n\n  \/\/ Viewport clamping\n  let finalPlacement = placement;\n  const vw = window.innerWidth;\n  const vh = window.innerHeight;\n\n  if (base === \"bottom\" && y + floating.height > vh) {\n    y = anchor.top - floating.height - offset;\n    finalPlacement = placement.replace(\"bottom\", \"top\") as Placement;\n  } else if (base === \"top\" && y < 0) {\n    y = anchor.bottom + offset;\n    finalPlacement = placement.replace(\"top\", \"bottom\") as Placement;\n  } else if (base === \"left\" && x < 0) {\n    \/\/ The sides flip too, so a `left` \/ `right` popup is not clamped back on\n    \/\/ top of its own anchor when the viewport edge is close.\n    x = anchor.right + offset;\n    finalPlacement = placement.replace(\"left\", \"right\") as Placement;\n  } else if (base === \"right\" && x + floating.width > vw) {\n    x = anchor.left - floating.width - offset;\n    finalPlacement = placement.replace(\"right\", \"left\") as Placement;\n  }\n\n  x = Math.max(4, Math.min(x, vw - floating.width - 4));\n  y = Math.max(4, Math.min(y, vh - floating.height - 4));\n\n  return { x, y, placement: finalPlacement, dir };\n}\n\nexport function useFloatingPosition(\n  anchorRef: RefObject<HTMLElement | null>,\n  floatingRef: RefObject<HTMLElement | null>,\n  options: UseFloatingPositionOptions = {},\n): FloatingPosition {\n  const { placement = \"bottom\", offset = 8, enabled = true } = options;\n  const [position, setPosition] = useState<FloatingPosition>({\n    x: -9999,\n    y: -9999,\n    placement,\n    dir: \"ltr\",\n  });\n\n  const update = useCallback(() => {\n    const anchor = anchorRef.current;\n    const floating = floatingRef.current;\n    if (!anchor || !floating) return;\n\n    const anchorRect = anchor.getBoundingClientRect();\n    \/\/ The popup's SIZE comes from layout, not from its transformed box: popups\n    \/\/ open with `fancy-scale-in` (scale 0.95 to 1) and are measured during it, so\n    \/\/ the box is 5% small, and nothing re-measures when the animation ends. That\n    \/\/ left an RTL `bottom-start` (and an LTR `bottom-end`) popup off the anchor's\n    \/\/ edge for good. Layout size is 0 where nothing lays out (jsdom), so the box\n    \/\/ is the fallback.\n    const box = floating.getBoundingClientRect();\n    const floatingRect = {\n      width: floating.offsetWidth || box.width,\n      height: floating.offsetHeight || box.height,\n    } as DOMRect;\n    const next = getPosition(anchorRect, floatingRect, placement, offset, directionOf(anchor));\n    \/\/ Bail out when nothing changed so this can run after every commit\n    \/\/ (below) without causing an infinite render loop.\n    setPosition((prev) =>\n      prev.x === next.x && prev.y === next.y && prev.placement === next.placement && prev.dir === next.dir\n        ? prev\n        : next,\n    );\n  }, [anchorRef, floatingRef, placement, offset]);\n\n  \/\/ Re-measure after every commit while open.\n  \/\/\n  \/\/ The floating element mounts a frame or two AFTER `enabled` flips \u2014 its\n  \/\/ render is gated behind a state flip (e.g. useAnimation's `mounted`), so at\n  \/\/ the moment `enabled` turns true the floating ref is still null and a single\n  \/\/ measurement no-ops, leaving the popover parked at its off-screen sentinel.\n  \/\/\n  \/\/ A passive effect with no deps runs after *every* commit \u2014 including the one\n  \/\/ that finally mounts the floating element \u2014 and, crucially, keeps running in\n  \/\/ hidden\/background tabs where `requestAnimationFrame` is paused. The bail-out\n  \/\/ in `update` makes the steady-state calls free, so this both fixes the\n  \/\/ late-mount race and survives tab-visibility throttling.\n  useEffect(() => {\n    if (enabled) update();\n  });\n\n  \/\/ \u2026but the per-commit effect ISN'T enough when the floating element mounts\n  \/\/ through a <Portal> whose own mount gate (SSR-safe; renders nothing until its\n  \/\/ useEffect runs) attaches the node WITHOUT re-rendering this hook's component.\n  \/\/ Then no commit happens here, the measurement never runs, and the popover\n  \/\/ stays parked at its off-screen sentinel until an unrelated scroll\/resize\n  \/\/ fires `update()` \u2014 the \"menu only appears after I scroll\" bug. Poll with rAF\n  \/\/ until the node is actually in the DOM, measure it, then keep it observed for\n  \/\/ size changes (async content \/ lazily-loaded icons).\n  useEffect(() => {\n    if (!enabled) return;\n    let raf = 0;\n    let ro: ResizeObserver | null = null;\n    const tick = () => {\n      const el = floatingRef.current;\n      if (el) {\n        update();\n        if (typeof ResizeObserver !== \"undefined\") {\n          ro = new ResizeObserver(() => update());\n          ro.observe(el);\n        }\n      } else {\n        raf = requestAnimationFrame(tick);\n      }\n    };\n    raf = requestAnimationFrame(tick);\n    return () => {\n      cancelAnimationFrame(raf);\n      ro?.disconnect();\n    };\n  }, [enabled, update, floatingRef]);\n\n  \/\/ Park off-screen when closed so the next open re-measures from scratch.\n  useEffect(() => {\n    if (!enabled) {\n      setPosition((prev) =>\n        prev.x === -9999 ? prev : { x: -9999, y: -9999, placement, dir: prev.dir },\n      );\n    }\n  }, [enabled, placement]);\n\n  \/\/ Reposition on scroll\/resize while open.\n  useEffect(() => {\n    if (!enabled) return;\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n\n    return () => {\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [update, enabled]);\n\n  return position;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/hooks\/use-floating-position.ts"},{"path":"components\/fancy\/lib\/hooks\/use-outside-click.ts","content":"import { useEffect, type RefObject } from \"react\";\n\nexport function useOutsideClick(\n  ref: RefObject<HTMLElement | null>,\n  handler: (event: MouseEvent | TouchEvent) => void,\n  enabled: boolean = true,\n  ignoreRef?: RefObject<HTMLElement | null>,\n): void {\n  useEffect(() => {\n    if (!enabled) return;\n\n    const listener = (event: MouseEvent | TouchEvent) => {\n      const el = ref.current;\n      if (!el || el.contains(event.target as Node)) return;\n      \/\/ Ignore clicks on the trigger\/anchor element \u2014 the trigger's\n      \/\/ own onClick handler manages toggling.\n      if (ignoreRef?.current?.contains(event.target as Node)) return;\n      handler(event);\n    };\n\n    document.addEventListener(\"mousedown\", listener);\n    document.addEventListener(\"touchstart\", listener);\n\n    return () => {\n      document.removeEventListener(\"mousedown\", listener);\n      document.removeEventListener(\"touchstart\", listener);\n    };\n  }, [ref, handler, enabled, ignoreRef]);\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/hooks\/use-outside-click.ts"},{"path":"components\/fancy\/lib\/hooks\/use-escape-key.ts","content":"import { createContext, useContext, useEffect, useRef } from \"react\";\n\n\/**\n * Escape belongs to the innermost open layer.\n *\n * Every `useEscapeKey(handler, enabled)` call is a LAYER while `enabled`: a\n * Dropdown's menu, a Select's listbox, a Popover, a Modal, a Drawer, a Tooltip,\n * a full-screen surface. They all join one stack, one document listener reads\n * each Escape, and only one layer gets it.\n *\n * Why not one document listener per layer, as this hook used to do: every\n * open layer then received the same Escape. A Dropdown inside a Modal closed\n * the menu AND the dialog. Inside a full-screen surface it was worse: the\n * surface's own key handler runs during the event's trip through the surface,\n * before any document listener, so it could not tell that a menu wanted the\n * key. DeckEditor exited full screen with its Shape menu still open. Fixing\n * that by ordering listeners would only last until someone registers one in a\n * different place. So the decision is made from the stack instead.\n *\n * \"Innermost\" is decided in two steps:\n *\n * 1. The most recently opened layer is the candidate. Opening a menu from a\n *    dialog is the normal order of things.\n * 2. A full-screen surface knows its own descendants: layers rendered inside\n *    it register under it through `EscapeLayerContext`, and that context flows\n *    through portals. If the candidate is a surface with open layers inside,\n *    the most recent of those wins instead. Without this step, a menu opened\n *    BEFORE an agent put its surface full screen would lose the Escape to the\n *    surface.\n *\n * An Escape that something already handled (`event.defaultPrevented`, for\n * example a text field clearing itself) is left alone.\n *\/\n\ninterface LayerEntry {\n  handler: { current: () => void };\n  \/** The surface this layer was rendered inside, if any. *\/\n  parent: EscapeScope | null;\n  \/** Set when the layer IS a surface: layers inside it point here. *\/\n  scope: EscapeScope | null;\n}\n\n\/** Identity of a full-screen surface for the layers rendered inside it. *\/\nexport type EscapeScope = object;\n\nconst stack: LayerEntry[] = [];\n\n\/** The surface (if any) that layers rendered here belong to. *\/\nexport const EscapeLayerContext = createContext<EscapeScope | null>(null);\n\nfunction innermost(): LayerEntry | undefined {\n  let candidate = stack[stack.length - 1];\n  while (candidate?.scope) {\n    const scope = candidate.scope;\n    let inner: LayerEntry | undefined;\n    for (let i = stack.length - 1; i >= 0; i--) {\n      if (stack[i].parent === scope) {\n        inner = stack[i];\n        break;\n      }\n    }\n    if (!inner) break;\n    candidate = inner;\n  }\n  return candidate;\n}\n\nfunction onDocumentKeyDown(event: KeyboardEvent) {\n  if (event.key !== \"Escape\" || event.defaultPrevented) return;\n  const target = innermost();\n  if (!target) return;\n  event.preventDefault();\n  target.handler.current();\n}\n\nfunction push(entry: LayerEntry): () => void {\n  if (stack.length === 0) document.addEventListener(\"keydown\", onDocumentKeyDown);\n  stack.push(entry);\n  return () => {\n    const i = stack.indexOf(entry);\n    if (i >= 0) stack.splice(i, 1);\n    if (stack.length === 0) document.removeEventListener(\"keydown\", onDocumentKeyDown);\n  };\n}\n\n\/**\n * Register a layer that closes on Escape while `enabled`. Pass `scope` only for\n * a surface that other layers can open inside (a full-screen surface).\n *\n * Returns `isInnermost()`, for a layer that also handles Escape in its own key\n * handler and must not act when a layer above it owns the key.\n *\n * @internal Exported for full-screen surfaces in sibling packages; ordinary\n * layers call `useEscapeKey`.\n *\/\nexport function useEscapeLayer(\n  handler: () => void,\n  enabled: boolean,\n  scope: EscapeScope | null = null,\n): { isInnermost: () => boolean } {\n  const parent = useContext(EscapeLayerContext);\n  const handlerRef = useRef(handler);\n  handlerRef.current = handler;\n  const entryRef = useRef<LayerEntry | null>(null);\n\n  \/\/ Depends on `enabled` (and identity), NOT on `handler`: callers pass inline\n  \/\/ callbacks, and re-registering on every render would move a dialog above\n  \/\/ the menu it had just opened.\n  useEffect(() => {\n    if (!enabled) return;\n    const entry: LayerEntry = { handler: handlerRef, parent, scope };\n    entryRef.current = entry;\n    const pop = push(entry);\n    return () => {\n      pop();\n      if (entryRef.current === entry) entryRef.current = null;\n    };\n  }, [enabled, parent, scope]);\n\n  const isInnermostRef = useRef(() => entryRef.current !== null && innermost() === entryRef.current);\n  return { isInnermost: isInnermostRef.current };\n}\n\nexport function useEscapeKey(handler: () => void, enabled: boolean = true): void {\n  useEscapeLayer(handler, enabled);\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/hooks\/use-escape-key.ts"},{"path":"components\/fancy\/lib\/utils\/compose-refs.ts","content":"import type { Ref, RefCallback } from \"react\";\n\n\/**\n * One ref callback that feeds every ref it is given.\n *\n * For a component that needs its own handle on an element AND has to honour a\n * ref someone else put there \u2014 a Tooltip anchoring to its trigger, a control\n * measuring itself while a caller holds a ref to it. Assigning one ref over the\n * other silently breaks whichever side lost.\n *\/\nexport function composeRefs<T>(...refs: Array<Ref<T> | undefined | null>): RefCallback<T> {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) (ref as { current: T | null }).current = node;\n    }\n  };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/compose-refs.ts"},{"path":"components\/fancy\/lib\/utils\/direction.ts","content":"\/**\n * Writing direction, read from the DOM rather than passed as a prop.\n *\n * Components follow the `dir` the browser already resolved for them, inherited\n * from the nearest ancestor that sets one (usually `<html dir=\"rtl\">`). Reading\n * the computed `direction` means a `dir` on any wrapper works, with nothing to\n * thread through props or context, and SSR renders the same markup for both\n * directions: layout is logical CSS, and only code that measures or maps keys\n * asks this question, always in an effect or an event handler.\n *\/\nexport type Direction = \"ltr\" | \"rtl\";\n\nexport function directionOf(el: Element | null | undefined): Direction {\n  if (!el || typeof window === \"undefined\" || typeof getComputedStyle !== \"function\") return \"ltr\";\n  return getComputedStyle(el).direction === \"rtl\" ? \"rtl\" : \"ltr\";\n}\n\nexport function isRtl(el: Element | null | undefined): boolean {\n  return directionOf(el) === \"rtl\";\n}\n\n\/**\n * The LOGICAL step a horizontal arrow key means: +1 toward the inline end\n * (\"next\"), -1 toward the inline start (\"previous\"), 0 for any other key.\n *\n * ArrowRight moves visually right in both directions, and visually right is\n * the inline END in LTR but the inline START in RTL.\n *\/\nexport function inlineStep(key: string, el: Element | null | undefined): -1 | 0 | 1 {\n  if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n  const forward = key === \"ArrowRight\" ? 1 : -1;\n  return (isRtl(el) ? -forward : forward) as -1 | 1;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/utils\/direction.ts"}]}