# Preview Card

> A hover preview of a link destination for sighted pointer and keyboard users.

```tsx title="hero.tsx"
import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'
import {
  PreviewCard,
  PreviewCardContent,
  PreviewCardTrigger,
} from '@langgenius/dify-ui/preview-card'

const linkClassName =
  'rounded-xs font-medium text-text-accent underline decoration-text-accent/70 decoration-1 underline-offset-[0.2em] outline-offset-2 outline-state-accent-solid transition-colors hover:decoration-current hover:decoration-2 active:opacity-80 focus-visible:outline-2 focus-visible:outline-solid data-popup-open:decoration-current data-popup-open:decoration-2'

export function PreviewCardHeroDemo() {
  return (
    <p className="max-w-md system-sm-regular text-text-secondary">
      The latest workflow revision was published by{' '}
      <PreviewCard>
        <PreviewCardTrigger
          href="https://example.com/members/ada-lovelace"
          onClick={(event) => event.preventDefault()}
          className={linkClassName}
        >
          Ada Lovelace
        </PreviewCardTrigger>
        <PreviewCardContent className="flex w-72 max-w-[calc(100vw-2rem)] items-start gap-3 p-3">
          <Avatar size="lg" aria-hidden="true">
            <AvatarFallback>AL</AvatarFallback>
          </Avatar>
          <div className="flex min-w-0 flex-col gap-0.5">
            <span className="system-sm-semibold text-text-primary">Ada Lovelace</span>
            <span className="truncate system-xs-regular text-text-tertiary">ada@example.com</span>
            <span className="pt-1 system-xs-regular text-text-secondary">
              Admin · Joined March 2025
            </span>
          </div>
        </PreviewCardContent>
      </PreviewCard>{' '}
      two hours ago.
    </p>
  )
}
```

## Usage guidelines

- Use `PreviewCard` as a non-interactive enhancement for a link destination, such as a member profile or a cited document. Use `Popover` when opening the popup is the trigger's purpose or its content must be reachable on touch and with assistive technology.
- Keep the link as the only accessible interface. The popup is not reachable on touch or by screen readers, so everything it shows also exists at the linked destination.
- Keep the popup free of buttons, links and fields. Users cannot move focus into it.
- `PreviewCardTrigger` renders a real link. Give it an `href` and visible link text, which also names it.
- Several links can share one root through a handle from `createPreviewCardHandle`. Each trigger passes its item as `payload`, and the root's function child reads the payload of the hovered or focused link.
- The default delays suit links in prose. Shorten `delay` and `closeDelay` on the trigger for dense lists where users scan many links in a row.

## Anatomy

```tsx
import {
  PreviewCard,
  PreviewCardContent,
  PreviewCardTrigger,
} from '@langgenius/dify-ui/preview-card'
```

```tsx
<PreviewCard>
  <PreviewCardTrigger />
  <PreviewCardContent />
</PreviewCard>
```

`PreviewCardContent` bundles the portal, positioner and styled popup and takes `side`, `align` and their offsets. Compose `PreviewCardPortal`, `PreviewCardPositioner` and `PreviewCardPopup` directly, with `PreviewCardViewport`, only when a surface needs more than those options.

## Examples

### Links sharing one preview

Two citations in a sentence share one root through a handle. Each link passes its document as `payload`.

```tsx title="detached-triggers.tsx"
import {
  createPreviewCardHandle,
  PreviewCard,
  PreviewCardContent,
  PreviewCardTrigger,
} from '@langgenius/dify-ui/preview-card'
import * as React from 'react'

type DocumentPreview = {
  title: string
  excerpt: string
  meta: string
}

const refundPolicy: DocumentPreview = {
  title: 'Refund policy.pdf',
  excerpt: 'Customers can request a full refund within 30 days of purchase by contacting support.',
  meta: '12 pages · 48 chunks · Updated yesterday',
}

const shippingGuide: DocumentPreview = {
  title: 'Shipping guide.md',
  excerpt: 'Orders placed before 2 p.m. ship the same business day from the nearest warehouse.',
  meta: '4 pages · 15 chunks · Updated last week',
}

const linkClassName =
  'rounded-xs font-medium text-text-accent underline decoration-text-accent/70 decoration-1 underline-offset-[0.2em] outline-offset-2 outline-state-accent-solid transition-colors hover:decoration-current hover:decoration-2 active:opacity-80 focus-visible:outline-2 focus-visible:outline-solid data-popup-open:decoration-current data-popup-open:decoration-2'

export function PreviewCardDetachedTriggersDemo() {
  const [handle] = React.useState(() => createPreviewCardHandle<DocumentPreview>())

  return (
    <React.Fragment>
      <p className="max-w-md system-sm-regular text-text-secondary">
        The answer cites{' '}
        <PreviewCardTrigger
          handle={handle}
          payload={refundPolicy}
          href="https://example.com/documents/refund-policy"
          onClick={(event) => event.preventDefault()}
          className={linkClassName}
        >
          Refund policy.pdf
        </PreviewCardTrigger>{' '}
        and{' '}
        <PreviewCardTrigger
          handle={handle}
          payload={shippingGuide}
          href="https://example.com/documents/shipping-guide"
          onClick={(event) => event.preventDefault()}
          className={linkClassName}
        >
          Shipping guide.md
        </PreviewCardTrigger>{' '}
        from the Customer support knowledge base.
      </p>
      <PreviewCard handle={handle}>
        {({ payload }) => (
          <PreviewCardContent className="flex w-72 max-w-[calc(100vw-2rem)] flex-col gap-1.5 p-3">
            <div className="flex items-center gap-1.5">
              <span
                aria-hidden="true"
                className="i-ri-file-text-line size-4 shrink-0 text-text-tertiary"
              />
              <span className="truncate system-sm-semibold text-text-primary">
                {payload?.title}
              </span>
            </div>
            <p className="system-xs-regular text-text-secondary">{payload?.excerpt}</p>
            <span className="system-xs-regular text-text-tertiary">{payload?.meta}</span>
          </PreviewCardContent>
        )}
      </PreviewCard>
    </React.Fragment>
  )
}
```

### Shorter delays in a list

A member list shares one root through a handle and sets shorter `delay` and `closeDelay` values on each trigger, so a single preview follows the pointer smoothly while scanning down the list.

```tsx title="delay.tsx"
import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'
import {
  createPreviewCardHandle,
  PreviewCard,
  PreviewCardContent,
  PreviewCardTrigger,
} from '@langgenius/dify-ui/preview-card'
import * as React from 'react'

type Member = {
  id: string
  name: string
  initials: string
  role: string
  email: string
}

const members: Member[] = [
  { id: 'ada', name: 'Ada Lovelace', initials: 'AL', role: 'Admin', email: 'ada@example.com' },
  { id: 'alan', name: 'Alan Turing', initials: 'AT', role: 'Editor', email: 'alan@example.com' },
  { id: 'grace', name: 'Grace Hopper', initials: 'GH', role: 'Editor', email: 'grace@example.com' },
  {
    id: 'margaret',
    name: 'Margaret Hamilton',
    initials: 'MH',
    role: 'Member',
    email: 'margaret@example.com',
  },
]

const linkClassName =
  'min-w-0 truncate rounded-xs py-0.5 system-sm-medium text-text-accent underline decoration-text-accent/70 decoration-1 underline-offset-2 outline-offset-2 outline-state-accent-solid transition-colors hover:decoration-current hover:decoration-2 active:opacity-80 focus-visible:outline-2 focus-visible:outline-solid data-popup-open:decoration-current data-popup-open:decoration-2'

export function PreviewCardDelayDemo() {
  const [handle] = React.useState(() => createPreviewCardHandle<Member>())

  return (
    <React.Fragment>
      <ul className="flex w-full max-w-64 flex-col divide-y divide-divider-subtle">
        {members.map((member) => (
          <li key={member.id} className="flex items-center gap-2.5 py-2.5">
            <Avatar size="sm" aria-hidden="true">
              <AvatarFallback>{member.initials}</AvatarFallback>
            </Avatar>
            <PreviewCardTrigger
              handle={handle}
              payload={member}
              delay={200}
              closeDelay={100}
              href={`https://example.com/members/${member.id}`}
              onClick={(event) => event.preventDefault()}
              className={linkClassName}
            >
              {member.name}
            </PreviewCardTrigger>
          </li>
        ))}
      </ul>
      <PreviewCard handle={handle}>
        {({ payload }) => (
          <PreviewCardContent
            side="inline-end"
            className="flex w-64 max-w-[calc(100vw-2rem)] items-center gap-3 p-3"
          >
            <Avatar size="lg" aria-hidden="true">
              <AvatarFallback>{payload?.initials}</AvatarFallback>
            </Avatar>
            <div className="flex min-w-0 flex-col gap-0.5">
              <span className="truncate system-sm-semibold text-text-primary">{payload?.name}</span>
              <span className="truncate system-xs-regular text-text-tertiary">
                {payload?.email}
              </span>
              <span className="system-xs-regular text-text-secondary">{payload?.role}</span>
            </div>
          </PreviewCardContent>
        )}
      </PreviewCard>
    </React.Fragment>
  )
}
```

## Keyboard

| Key      | Action                                                                                        |
| -------- | --------------------------------------------------------------------------------------------- |
| `Tab`    | Focusing the link opens the preview after the trigger's `delay`. Moving focus away closes it. |
| `Escape` | Closes the preview. Focus stays on the link.                                                  |

## API reference

### PreviewCard

Groups all parts of a hover- and focus-triggered preview card for a link. Doesn't render its own HTML element.

Keep the preview non-interactive and duplicate any essential content at the linked destination, since touch and screen-reader users cannot reach it. Use `Popover` when opening the popup is the trigger's purpose or when its content must be accessible across input modes.

Inherits `defaultOpen`, `open`, `onOpenChange`, `onOpenChangeComplete`, `actionsRef`, `handle`, `children`, `triggerId`, `defaultTriggerId` from [Base UI PreviewCard.Root](https://base-ui.com/react/components/preview-card#root).

### PreviewCardContent

A styled preview card surface bundled with a portal and positioner. Renders a `<div>` element.

**Props**

| Prop          | Type                       | Default | Description                                                                                             |
| ------------- | -------------------------- | ------- | ------------------------------------------------------------------------------------------------------- |
| `sideOffset?` | `number \| OffsetFunction` | `8`     | Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance. |
| `children`    | `React.ReactNode`          | —       | The preview card content.                                                                               |

Inherits `className`, `render`, `style`, `side`, `align`, `alignOffset` from [Base UI PreviewCard.Popup](https://base-ui.com/react/components/preview-card#popup).

**Data attributes**

| Attribute             | Description                                                           |
| --------------------- | --------------------------------------------------------------------- |
| `data-open`           | Present when the preview card is open.                                |
| `data-closed`         | Present when the preview card is closed.                              |
| `data-starting-style` | Present when the preview card begins animating in.                    |
| `data-ending-style`   | Present when the preview card is animating out.                       |
| `data-side`           | Indicates which side the popup is positioned relative to the trigger. |
| `data-align`          | Indicates how the popup is aligned relative to specified side.        |

**CSS variables**

| Variable              | Type     | Description                                                                                                                        |
| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `--available-width`   | `number` | The available width between the trigger and the edge of the viewport.                                                              |
| `--available-height`  | `number` | The available height between the trigger and the edge of the viewport.                                                             |
| `--anchor-width`      | `number` | The anchor's width.                                                                                                                |
| `--anchor-height`     | `number` | The anchor's height.                                                                                                               |
| `--transform-origin`  | `string` | The coordinates that this element is anchored to. Used for animations and transitions.                                             |
| `--positioner-width`  | `number` | The width of the preview card's positioner. It is important to set `width` to this value when using CSS to animate size changes.   |
| `--positioner-height` | `number` | The height of the preview card's positioner. It is important to set `height` to this value when using CSS to animate size changes. |

### PreviewCardPopup

A container for the preview card contents. Renders a `<div>` element.

Inherits `className`, `render`, `style` from [Base UI PreviewCard.Popup](https://base-ui.com/react/components/preview-card#popup).

**Data attributes**

| Attribute             | Description                                                           |
| --------------------- | --------------------------------------------------------------------- |
| `data-open`           | Present when the preview card is open.                                |
| `data-closed`         | Present when the preview card is closed.                              |
| `data-starting-style` | Present when the preview card begins animating in.                    |
| `data-ending-style`   | Present when the preview card is animating out.                       |
| `data-side`           | Indicates which side the popup is positioned relative to the trigger. |
| `data-align`          | Indicates how the popup is aligned relative to specified side.        |

### PreviewCardPortal

A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to `<body>`. Renders a `<div>` element.

Inherits `keepMounted`, `container`, `className`, `render`, `style` from [Base UI PreviewCard.Portal](https://base-ui.com/react/components/preview-card#portal).

### PreviewCardPositioner

Positions the popup against the trigger. Renders a `<div>` element.

**Props**

| Prop          | Type                       | Default | Description                                                                                             |
| ------------- | -------------------------- | ------- | ------------------------------------------------------------------------------------------------------- |
| `sideOffset?` | `number \| OffsetFunction` | `8`     | Distance between the anchor and the popup in pixels. Also accepts a function that returns the distance. |

Inherits `className`, `render`, `style`, `anchor`, `positionMethod`, `side`, `align`, `alignOffset`, `collisionBoundary`, `collisionPadding`, `sticky`, `arrowPadding`, `disableAnchorTracking`, `collisionAvoidance` from [Base UI PreviewCard.Positioner](https://base-ui.com/react/components/preview-card#positioner).

**Data attributes**

| Attribute            | Description                                                           |
| -------------------- | --------------------------------------------------------------------- |
| `data-open`          | Present when the preview card is open.                                |
| `data-closed`        | Present when the preview card is closed.                              |
| `data-anchor-hidden` | Present when the anchor is hidden.                                    |
| `data-side`          | Indicates which side the popup is positioned relative to the trigger. |
| `data-align`         | Indicates how the popup is aligned relative to specified side.        |

**CSS variables**

| Variable              | Type     | Description                                                                                                                        |
| --------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `--available-width`   | `number` | The available width between the trigger and the edge of the viewport.                                                              |
| `--available-height`  | `number` | The available height between the trigger and the edge of the viewport.                                                             |
| `--anchor-width`      | `number` | The anchor's width.                                                                                                                |
| `--anchor-height`     | `number` | The anchor's height.                                                                                                               |
| `--transform-origin`  | `string` | The coordinates that this element is anchored to. Used for animations and transitions.                                             |
| `--positioner-width`  | `number` | The width of the preview card's positioner. It is important to set `width` to this value when using CSS to animate size changes.   |
| `--positioner-height` | `number` | The height of the preview card's positioner. It is important to set `height` to this value when using CSS to animate size changes. |

### PreviewCardTrigger

A link that opens the preview card. Renders an `<a>` element.

Inherits `handle`, `payload`, `delay`, `closeDelay`, `className`, `render`, `style` from [Base UI PreviewCard.Trigger](https://base-ui.com/react/components/preview-card#trigger).

**Data attributes**

| Attribute         | Description                                          |
| ----------------- | ---------------------------------------------------- |
| `data-popup-open` | Present when the corresponding preview card is open. |

### PreviewCardViewport

A viewport for displaying content transitions. This component is only required if one popup can be opened by multiple triggers, its content changes based on the trigger, and switching between them is animated. Renders a `<div>` element.

Inherits `children`, `className`, `render`, `style` from [Base UI PreviewCard.Viewport](https://base-ui.com/react/components/preview-card#viewport).

**Data attributes**

| Attribute                   | Description                                                                                                                                                                                                                |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data-current`              | Applied to the direct child of the viewport when no transitions are present or the new content when it's entering.                                                                                                         |
| `data-previous`             | Applied to the direct child of the viewport that contains the exiting content when transitions are present.                                                                                                                |
| `data-activation-direction` | Indicates the direction from which the popup was activated. This can be used to create directional animations based on how the popup was triggered. Contains space-separated values for both horizontal and vertical axes. |
| `data-transitioning`        | Indicates that the viewport is currently transitioning between old and new content.                                                                                                                                        |
| `data-instant`              | Present if animations should be instant.                                                                                                                                                                                   |

**CSS variables**

| Variable         | Type | Description                                                                                                                                                                                                                                                   |
| ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--popup-width`  | —    | The width of the parent popup. This variable is placed on the 'previous' container and stores the width of the popup when the previous content was rendered. It can be used to freeze the dimensions of the popup when animating between different content.   |
| `--popup-height` | —    | The height of the parent popup. This variable is placed on the 'previous' container and stores the height of the popup when the previous content was rendered. It can be used to freeze the dimensions of the popup when animating between different content. |

### createPreviewCardHandle

Creates a new handle to connect a PreviewCard.Root with detached PreviewCard.Trigger components.

```ts
createPreviewCardHandle<Payload>(): BasePreviewCard.Handle<Payload>
```

**Returns:** `BasePreviewCard.Handle<Payload>`

**Return properties**

| Member   | Type                          | Description                                                                                                                                                             |
| -------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`   | `(triggerId: string) => void` | Opens the preview card and associates it with the trigger with the given id. This method should only be called in an event handler or an effect (not during rendering). |
| `close`  | `() => void`                  | Closes the preview card. This method should only be called in an event handler or an effect (not during rendering).                                                     |
| `isOpen` | `boolean`                     | Whether the preview card is currently open. Returns `false` while no root is attached to the handle.                                                                    |
