# Expandable Card
A card that expands into its own detail view.
Source page: https://dinachi.dev/docs/components/expandable-card

## Installation
```bash
npx @dinachi/cli@latest add expandable-card
```
Adds to your project:
- `components/ui/expandable-card/expandable-card.tsx`
- `components/ui/expandable-card/index.ts`
Installs:
- `motion` ^12.23.6

## Usage
```tsx
import {
  ExpandableCard,
  ExpandableCardBody,
  ExpandableCardPanel,
  ExpandableCardShared,
  ExpandableCardTrigger,
} from "@/components/ui/expandable-card"

export function Story() {
  return (
    <ExpandableCard>
      <ExpandableCardTrigger>
        <ExpandableCardShared part="art" className="h-24 bg-muted" />
        <ExpandableCardShared part="title" className="p-4 text-sm font-medium">
          Shared layout
        </ExpandableCardShared>
      </ExpandableCardTrigger>

      <ExpandableCardPanel title="Shared layout">
        <ExpandableCardShared part="art" className="h-40 bg-muted" />
        <ExpandableCardShared part="title" className="px-5 pt-4 text-lg font-medium">
          Shared layout
        </ExpandableCardShared>
        <ExpandableCardBody className="px-5 pb-5">
          Content that only exists in the panel.
        </ExpandableCardBody>
      </ExpandableCardPanel>
    </ExpandableCard>
  )
}
```

## Anatomy
```tsx
<ExpandableCard>
  <ExpandableCardTrigger>
    <ExpandableCardShared />
  </ExpandableCardTrigger>
  <ExpandableCardPanel>
    <ExpandableCardShared />
    <ExpandableCardBody />
  </ExpandableCardPanel>
</ExpandableCard>
```
- `ExpandableCard`: Holds open state; scopes shared ids.
- `ExpandableCardTrigger`: The card itself, a button.
- `ExpandableCardPanel`: The opened card, portalled, mounted while open.
- `ExpandableCardShared`: An element that travels between both sides.
- `ExpandableCardBody`: Panel-only content, fades in after landing.

## Examples

### Default
Focus lands inside, Escape closes, focus comes back.
```tsx
import {
  ExpandableCard,
  ExpandableCardTrigger,
  ExpandableCardPanel,
  ExpandableCardShared,
  ExpandableCardBody,
} from '@/components/ui/expandable-card';

export function Example() {
  return (
    <ExpandableCard>
      <ExpandableCardTrigger>
        <ExpandableCardShared part="art" className="h-24 bg-muted" />
        <ExpandableCardShared part="title" className="p-4 text-sm font-medium">
          The card travels
        </ExpandableCardShared>
      </ExpandableCardTrigger>

      <ExpandableCardPanel title="The card travels">
        <ExpandableCardShared part="art" className="h-40 bg-muted" />
        <ExpandableCardShared part="title" className="px-5 pt-4 text-lg font-medium">
          The card travels
        </ExpandableCardShared>
        <ExpandableCardBody className="px-5 pb-5">
          Content that only exists in the panel arrives after the landing.
        </ExpandableCardBody>
      </ExpandableCardPanel>
    </ExpandableCard>
  );
}
```

### Controlled
You hold the open state and the close control.
```tsx
const [open, setOpen] = useState(false);

// showClose={false} hands the close control over too, which only works if
// something you own can still set open back to false.
<ExpandableCard open={open} onOpenChange={setOpen}>
  <ExpandableCardTrigger>{/* ... */}</ExpandableCardTrigger>
  <ExpandableCardPanel title="Own the open state" showClose={false}>
    {/* ... */}
    <button type="button" onClick={() => setOpen(false)}>Done reading</button>
  </ExpandableCardPanel>
</ExpandableCard>
```

### Full screen
The same travel, landing on all four edges.
```tsx
// The card travels the same way; it just lands on the whole viewport. Content
// taller than the screen scrolls, and the close button stays put while it does.
<ExpandableCardPanel fullscreen title="The road that ends at the water">
  <ExpandableCardShared part="art" className="h-56 bg-muted sm:h-72" />
  <div className="mx-auto max-w-2xl space-y-3 px-6 py-8">
    <ExpandableCardShared part="title" className="text-2xl font-medium">
      The road that ends at the water
    </ExpandableCardShared>
    <ExpandableCardBody className="space-y-4 text-base">
      {paragraphs.map((p) => <p key={p}>{p}</p>)}
    </ExpandableCardBody>
  </div>
</ExpandableCardPanel>
```

### Not only cards
A row expands the same way.
```tsx
// Nothing here is card-shaped. Name the parts that exist on both sides and they
// travel; everything else waits for the landing.
<ExpandableCard>
  <ExpandableCardTrigger className="rounded-lg px-4 py-3">
    <div className="flex items-center justify-between gap-4">
      <ExpandableCardShared part="title">Invoice 4021</ExpandableCardShared>
      <ExpandableCardShared part="meta">Paid · 12 Aug</ExpandableCardShared>
    </div>
  </ExpandableCardTrigger>

  <ExpandableCardPanel title="Invoice 4021" className="max-w-sm">
    {/* the same two parts, larger */}
  </ExpandableCardPanel>
</ExpandableCard>
```

## Notes

### Motion tier
Needs [motion](https://motion.dev). `add --all` skips it; install with `add --motion` or by name.

### When to use it
- A hero item, or a short list where opening one is a deliberate choice.
- Skip it on large grids, where the travel slows every glance.
- If the detail view shares nothing with the card, use a Dialog.

### Pairing parts
- Use each `part` once per side. A `part` used twice on one side makes the layout engine pick one.
- Put anything on only one side in `ExpandableCardBody`.
- Ids are scoped per card, so a grid of cards works.

### Controlled
Use `open` and `onOpenChange` to close the panel from your own control. With `showClose={false}`, your control must set `open` back to false.

### Full screen
- Centred: sized by content, never scrolls; rounded, bordered and shadowed.
- `fullscreen`: fills the screen, content scrolls inside, no radius, border or shadow.
- The close button stays fixed outside the scroller.

### Behaviour
- The travel is a 420ms spring; the backdrop a 200ms fade.
- Reduced motion cuts. An app-level `MotionConfig reducedMotion` is honoured.
- The panel portals to `document.body`. An ancestor with a transform, filter, backdrop-filter, perspective or paint containment breaks `position: fixed`; pass `container` to portal elsewhere.

## API reference
Props marked **agent** change what an agent reads or may do.

### ExpandableCard
Holds open state; scopes shared ids.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | - | Controlled open state. |
| `defaultOpen` | `boolean` | `false` | Starting open state when uncontrolled. |
| `onOpenChange` **agent** | `(open, details) => void` | - | Runs before open or close, for people and agents. `details.cancel()` refuses it. |

### ExpandableCardTrigger
The card itself, a button.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Card content. Its text is the agent's label while closed. |
| `onClick` | `(event) => void` | - | Runs first. `event.preventDefault()` stops the card opening. |

### ExpandableCardPanel
The opened card, portalled, mounted while open.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `title` **agent** | `string` | - | Dialog name, and the agent's label while open. |
| `showClose` | `boolean` | `true` | Set false to supply your own close control. |
| `fullscreen` | `boolean` | `false` | Fills the viewport; long content scrolls. |
| `closeLabel` | `string` | `"Close"` | Accessible name for the close button. |
| `backdropClassName` | `string` | - | Classes for the backdrop. |
| `container` | `Element \| null` | `document.body` | Where the overlay is portalled. |

### ExpandableCardShared
An element that travels between both sides.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `part` | `string` | - | Names the pair. Use it once on the card, once in the panel. |

### ExpandableCardBody
Panel-only content, fades in after landing.

Takes the props of the element it renders.

## Agent
Inside an `AgentProvider`, Expandable Card appears in `agent.snapshot()` as `disclosure`.
Reads:
- `label`: The card's text while closed. The panel's `title` while open.
- `open`: Whether the panel is showing.
Actions:
- `open()`: While closed. Opens the panel like a click on the card.
- `close()`: While open. Closes the panel.
An agent's open or close runs through `onOpenChange` with `details.reason` set to `imperative-action`. `isAgentChange(details)` is true for it; `details.cancel()` keeps the card as it was and tells the agent the app refused.
```ts
await agent.act({
  steps: [{ ref: "The card travels", action: "open" }],
})
```

## Accessibility
- The panel is a modal dialog with `aria-modal`, named by its `title`.
- Focus moves to the panel's first control on open and back to the card on close.
- The card is `inert` while open.
- Page scroll is locked, with scrollbar compensation so layout does not shift.
- The trigger is a button with `aria-haspopup="dialog"` and `aria-expanded`.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens the card |
| `Tab` / `Shift + Tab` | Cycles focus inside the open panel |
| `Esc` | Closes and returns focus to the card |

## Source
`components/ui/expandable-card/expandable-card.tsx`
```tsx
"use client"

import * as React from "react"
import { createPortal } from "react-dom"
import {
  AnimatePresence,
  motion,
  MotionConfigContext,
  useIsPresent,
  useReducedMotion,
  type Transition,
} from "motion/react"
import { cn } from "@/lib/utils"
import { type AgentOpenParts, useAgentOpen, useHasAgent, useMergedRef } from "@/components/ui/agent"

/** `useReducedMotion` reads the OS setting only, and only at mount. Also honour an
 *  app-level `<MotionConfig reducedMotion>`, so a user preference in the host app
 *  reaches this component. */
function useReducedMotionConfig() {
  const config = React.useContext(MotionConfigContext)
  const prefersReduced = useReducedMotion()
  if (config.reducedMotion === "always") return true
  if (config.reducedMotion === "never") return false
  return prefersReduced ?? false
}

const FOCUSABLE =
  'a[href], button:not([disabled]), textarea, input, select, [tabindex]:not([tabindex="-1"])'

export interface ExpandableCardChangeDetails {
  reason: "trigger-press" | "close-press" | "outside-press" | "escape-key" | "imperative-action"
  event: Event | undefined
  isCanceled: boolean
  cancel: () => void
}

type PersonReason = Exclude<ExpandableCardChangeDetails["reason"], "imperative-action">

function personChange(reason: PersonReason, event?: Event): ExpandableCardChangeDetails {
  const details: ExpandableCardChangeDetails = {
    reason,
    event,
    isCanceled: false,
    cancel: () => {
      details.isCanceled = true
    },
  }
  return details
}

interface ExpandableCardContextValue {
  open: boolean
  setOpen: (open: boolean, reason: PersonReason, event?: Event) => void
  /** Set inside an `AgentProvider`: the card and its panel are one control to the agent. */
  agent: AgentOpenParts | null
  /** Pairs an element in the card with its counterpart in the panel. */
  layoutId: (part: string) => string
  transition: Transition
  reducedMotion: boolean
}

const ExpandableCardContext =
  React.createContext<ExpandableCardContextValue | null>(null)

function useExpandableCard(component: string) {
  const context = React.useContext(ExpandableCardContext)
  if (!context) {
    throw new Error(`${component} must be used within an ExpandableCard`)
  }
  return context
}

export interface ExpandableCardProps extends React.ComponentProps<"div"> {
  open?: boolean
  defaultOpen?: boolean
  /** Called before the card opens or closes. `details.cancel()` keeps it as it is. */
  onOpenChange?: (open: boolean, details: ExpandableCardChangeDetails) => void
}

/**
 * A card that opens into its own detail view.
 *
 * This is the one interaction in the tier where the motion does something a cut cannot: it
 * establishes that the panel you are now reading *is* the card you tapped. Two elements
 * sharing a `layoutId` are one object to the layout engine, so the card does not fade out
 * while a dialog fades in — it travels, and the reader never loses track of what they are
 * looking at.
 *
 * It is also the easiest thing here to overuse. A shared transition on a grid of twelve
 * cards is twelve chances to sit through half a second of animation to read a paragraph. It
 * earns its place on a hero item, or on a list short enough that opening one is a decision
 * rather than a habit.
 *
 * The panel is a real modal, which is a larger commitment than it looks: `aria-modal` is a
 * promise that the rest of the page is unreachable, and a dialog that says it and does not
 * honour it is worse than one that never claimed to be modal. So the whole set is here —
 * Escape, a focus trap, focus restored to the card that opened it, the card made inert, and
 * the page held still underneath.
 */
const ExpandableCard = React.forwardRef<HTMLDivElement, ExpandableCardProps>(
  ({ open: openProp, defaultOpen = false, onOpenChange, className, ...props }, ref) => {
    const reducedMotion = useReducedMotionConfig()
    const [open, change, parts] = useAgentOpen("disclosure", openProp, defaultOpen, onOpenChange)
    const agent = useHasAgent() ? parts : null

    const setOpen = React.useCallback(
      (next: boolean, reason: PersonReason, event?: Event) => change(next, personChange(reason, event)),
      [change]
    )

    // Scopes the shared layout ids to this card, so a grid of them does not have every
    // card trying to travel to the same panel.
    const scope = React.useId()
    const layoutId = React.useCallback(
      (part: string) => `${scope}-${part}`,
      [scope]
    )

    // Longer than the tier's 300ms rule, deliberately: that rule is about elements moving a
    // short distance, and this object crosses most of the viewport. Land it too fast and
    // the travel reads as a cut.
    const transition = React.useMemo<Transition>(
      () =>
        reducedMotion
          ? { duration: 0 }
          : { type: "spring", bounce: 0.12, duration: 0.42 },
      [reducedMotion]
    )

    const context = React.useMemo(
      () => ({ open, setOpen, agent, layoutId, transition, reducedMotion }),
      [open, setOpen, agent, layoutId, transition, reducedMotion]
    )

    return (
      <ExpandableCardContext.Provider value={context}>
        <div ref={ref} className={cn("relative", className)} data-slot="expandable-card" {...props} />
      </ExpandableCardContext.Provider>
    )
  }
)
ExpandableCard.displayName = "ExpandableCard"

export type ExpandableCardTriggerProps = React.ComponentProps<typeof motion.button>

/** The card itself. It is the thing that travels, so it is a button, not a wrapper. */
const ExpandableCardTrigger = React.forwardRef<
  HTMLButtonElement,
  ExpandableCardTriggerProps
>(({ className, onClick, ...props }, ref) => {
  const { open, setOpen, agent, layoutId, transition } =
    useExpandableCard("ExpandableCardTrigger")

  return (
    <motion.button
      ref={useMergedRef(ref, agent?.trigger)}
      type="button"
      layoutId={layoutId("card")}
      transition={transition}
      aria-haspopup="dialog"
      aria-expanded={open}
      // Inert rather than merely covered. A dialog the reader can still tab into is not
      // modal, whatever the attribute says.
      inert={open || undefined}
      onClick={(event) => {
        onClick?.(event)
        if (event.defaultPrevented) return
        setOpen(true, "trigger-press", event.nativeEvent)
      }}
      className={cn(
        "block w-full overflow-hidden rounded-2xl border border-border bg-background text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
        className
      )}
      data-slot="expandable-card-trigger"
      {...props}
    />
  )
})
ExpandableCardTrigger.displayName = "ExpandableCardTrigger"

export interface ExpandableCardPanelProps
  extends Omit<React.ComponentProps<typeof motion.div>, "children"> {
  /** Accessible name for the dialog. It is the card's title, said once. */
  title: string
  /** Set false to supply your own close control inside the panel. */
  showClose?: boolean
  /**
   * Fill the viewport rather than sit in the middle of it.
   *
   * The card travels the same way; it just lands on all four edges. Content taller than the
   * screen scrolls, which a centred panel never has to do, since that one is sized by what
   * is in it.
   */
  fullscreen?: boolean
  closeLabel?: string
  backdropClassName?: string
  /** Where the overlay is portalled. Defaults to `document.body`. */
  container?: Element | null
  children?: React.ReactNode
}

/**
 * A centred panel is as tall as its contents, so it never scrolls. A full-screen one is as
 * tall as the screen, and the page underneath is locked, so without a scroller here
 * anything past the fold is unreachable.
 */
function PanelBody({
  fullscreen,
  children,
}: {
  fullscreen: boolean
  children: React.ReactNode
}) {
  if (!fullscreen) return <>{children}</>

  return (
    <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">{children}</div>
  )
}

/** Outside the scroller, so it holds its corner while the body moves under it. */
function PanelClose({
  fullscreen,
  label,
  onClick,
}: {
  fullscreen: boolean
  label: string
  onClick: (event: React.MouseEvent) => void
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-label={label}
      className={cn(
        "absolute rounded-full bg-background/70 p-1.5 text-foreground backdrop-blur transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
        fullscreen ? "right-4 top-4" : "right-3 top-3"
      )}
    >
      <CloseIcon />
    </button>
  )
}

/**
 * No radius, no border and no shadow when full screen: all three describe an edge, and a
 * panel on all four edges of the screen has none to describe.
 */
function panelSurface(fullscreen: boolean): string {
  return fullscreen
    ? "flex h-full w-full flex-col"
    : "w-full max-w-md rounded-2xl border border-border shadow-2xl"
}

/** The opened card. Mounted only while open, so the shared layout has somewhere to land. */
/** Marks the panel while it plays its exit, so it stops counting as an open modal. */
function ExitMark({ panel }: { panel: React.RefObject<HTMLDivElement | null> }) {
  const present = useIsPresent()
  React.useLayoutEffect(() => {
    panel.current?.toggleAttribute("data-ending-style", !present)
  }, [present, panel])
  return null
}

const ExpandableCardPanel = React.forwardRef<HTMLDivElement, ExpandableCardPanelProps>(
  (
    {
      title,
      showClose = true,
      fullscreen = false,
      closeLabel = "Close",
      backdropClassName,
      container,
      className,
      children,
      ...props
    },
    ref
  ) => {
    const { open, setOpen, agent, layoutId, transition } =
      useExpandableCard("ExpandableCardPanel")

    const panel = React.useRef<HTMLDivElement>(null)
    // The card goes inert while open, so the agent finds the control at the panel then.
    const panelRef = useMergedRef(ref, panel, agent?.popup)

    useModalBehaviour(open, panel, setOpen)

    const target = usePortalTarget(container)
    if (!target) return null

    return createPortal(
      <AnimatePresence>
        {open ? (
          <>
            <motion.div
              aria-hidden
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              onClick={(event) => setOpen(false, "outside-press", event.nativeEvent)}
              className={cn(
                "fixed inset-0 z-40 bg-background/80 backdrop-blur-sm",
                backdropClassName
              )}
            />
            {/* The centring frame does not intercept the backdrop's clicks; only the panel
                inside it takes pointer events. Its padding is what keeps a centred panel
                off the edges, so a full-screen one cannot have it. */}
            <div
              className={cn(
                "pointer-events-none fixed inset-0 z-50 flex items-center justify-center",
                !fullscreen && "p-4"
              )}
            >
              <motion.div
                ref={panelRef}
                layoutId={layoutId("card")}
                transition={transition}
                role="dialog"
                aria-modal="true"
                aria-label={title}
                className={cn(
                  "pointer-events-auto relative overflow-hidden bg-background",
                  panelSurface(fullscreen),
                  className
                )}
                data-slot="expandable-card-panel"
                {...props}
              >
                <ExitMark panel={panel} />
                <PanelBody fullscreen={fullscreen}>{children}</PanelBody>
                {showClose ? (
                  <PanelClose
                    fullscreen={fullscreen}
                    label={closeLabel}
                    onClick={(event) => setOpen(false, "close-press", event.nativeEvent)}
                  />
                ) : null}
              </motion.div>
            </div>
          </>
        ) : null}
      </AnimatePresence>,
      target
    )
  }
)
ExpandableCardPanel.displayName = "ExpandableCardPanel"

/**
 * Where the overlay is rendered, resolved on the client.
 *
 * The panel has to leave the card's subtree. `position: fixed` is only relative to the
 * viewport while no ancestor has a transform, a filter, a `backdrop-filter`, `perspective`
 * or paint containment — any one of those makes that ancestor the containing block instead,
 * and the overlay silently centres itself inside a page-height wrapper somewhere below the
 * fold. A consumer cannot be asked to audit their layout for that, so the panel does not
 * rely on the layout at all.
 *
 * Null on the server and while hydrating, because `document` does not exist on the server
 * and a portal cannot be part of the first paint.
 */
function usePortalTarget(container?: Element | null) {
  const client = React.useSyncExternalStore(subscribeNever, isClient, isServer)
  return client ? (container ?? document.body) : null
}

const subscribeNever = () => () => {}
const isClient = () => true
const isServer = () => false

export interface ExpandableCardSharedProps
  extends React.ComponentProps<typeof motion.div> {
  /** Names the pair. Use the same `part` on the card and in the panel, once each. */
  part: string
}

/**
 * An element that exists on both sides of the transition and should travel between them.
 *
 * Artwork, a title, a kicker. Pair them by `part`; a `part` used twice on the same side has
 * two elements claiming to be one object, and the layout engine picks one.
 */
const ExpandableCardShared = React.forwardRef<HTMLDivElement, ExpandableCardSharedProps>(
  ({ part, ...props }, ref) => {
    const { layoutId, transition } = useExpandableCard("ExpandableCardShared")

    return (
      <motion.div
        ref={ref}
        layoutId={layoutId(part)}
        transition={transition}
        data-slot="expandable-card-shared"
        {...props}
      />
    )
  }
)
ExpandableCardShared.displayName = "ExpandableCardShared"

export type ExpandableCardBodyProps = React.ComponentProps<typeof motion.div>

/**
 * Content that only exists in the panel.
 *
 * It has no counterpart on the card, so it arrives after the travel rather than trying to
 * share it. Anything that exists on only one side of a transition should wait for the
 * object to land.
 */
const ExpandableCardBody = React.forwardRef<HTMLDivElement, ExpandableCardBodyProps>(
  ({ className, ...props }, ref) => {
    const { reducedMotion } = useExpandableCard("ExpandableCardBody")

    return (
      <motion.div
        ref={ref}
        initial={{ opacity: 0, y: 6 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: reducedMotion ? 0 : 0.16, duration: 0.24 }}
        className={cn("text-sm leading-relaxed text-muted-foreground", className)}
        data-slot="expandable-card-body"
        {...props}
      />
    )
  }
)
ExpandableCardBody.displayName = "ExpandableCardBody"

/**
 * Everything `aria-modal="true"` is claiming.
 *
 * Escape closes, focus moves in on open and returns to whatever opened it on close, Tab
 * cycles inside, and the page underneath cannot scroll. The scroll lock compensates for the
 * width of the scrollbar it removes, because otherwise the whole layout shifts sideways at
 * the exact moment the card is mid-flight, and the shared-layout animation gets the blame.
 */
function useModalBehaviour(
  active: boolean,
  ref: React.RefObject<HTMLElement | null>,
  onClose: (open: false, reason: "escape-key", event: Event) => void
) {
  const onCloseRef = React.useRef(onClose)
  React.useEffect(() => {
    onCloseRef.current = onClose
  })

  React.useEffect(() => {
    if (!active) return

    const opener = document.activeElement as HTMLElement | null
    const body = document.body
    const previousOverflow = body.style.overflow
    const previousPadding = body.style.paddingRight
    const scrollbar = window.innerWidth - document.documentElement.clientWidth

    body.style.overflow = "hidden"
    if (scrollbar > 0) body.style.paddingRight = `${scrollbar}px`

    const focusable = () =>
      Array.from(ref.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []).filter(
        (node) => node.offsetParent !== null
      )

    // Focus the panel's own controls, not the page. `preventScroll` matters: the dialog is
    // mid-travel, and letting the browser scroll to the element it is focusing would move
    // the ground under the animation.
    focusable()[0]?.focus({ preventScroll: true })

    // Flagged on CRAP, which scores complexity against coverage that is estimated here
    // rather than measured — so the focus-trap tests cannot move the number.
    // fallow-ignore-next-line complexity
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault()
        onCloseRef.current(false, "escape-key", event)
        return
      }
      if (event.key !== "Tab") return

      const nodes = focusable()
      if (nodes.length === 0) {
        event.preventDefault()
        return
      }

      const first = nodes[0]
      const last = nodes[nodes.length - 1]
      const inside = ref.current?.contains(document.activeElement)

      if (event.shiftKey && (!inside || document.activeElement === first)) {
        event.preventDefault()
        last.focus()
      } else if (!event.shiftKey && (!inside || document.activeElement === last)) {
        event.preventDefault()
        first.focus()
      }
    }

    document.addEventListener("keydown", onKeyDown)

    return () => {
      document.removeEventListener("keydown", onKeyDown)
      body.style.overflow = previousOverflow
      body.style.paddingRight = previousPadding
      // By the time this runs the card is no longer inert, so it can take focus back.
      opener?.focus({ preventScroll: true })
    }
  }, [active, ref])
}

function CloseIcon() {
  return (
    <svg
      aria-hidden
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      className="h-4 w-4"
    >
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  )
}

export {
  ExpandableCard,
  ExpandableCardTrigger,
  ExpandableCardPanel,
  ExpandableCardShared,
  ExpandableCardBody,
}
```
