# Popover

A popup anchored to its trigger for content the user asks for, opened by a press or by hover.

- Page: https://www.effectcn.com/components/popover
- Kind: Headless component with parts
- File: `src/ui/popover.ts`
- Built on: `Popover` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/popover.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/popover.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { Popover } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What a `Popover`'s `view` closure receives. */
export type PopoverParts = Component.Headless.Parts<typeof Popover>

interface ClassOption {
  readonly class?: string | undefined
}

const sizes = {
  sm: "w-56",
  default: "w-72",
  auto: "w-auto"
} as const

export type PopoverSize = keyof typeof sizes

/** The box the kit places next to the trigger. The popover's `sideOffset` is its padding. */
export const PopoverPositioner = <Msg>(h: Html.H<Msg>, popover: PopoverParts, options: ClassOption = {}) =>
  popover.positioner(h.div.class(cn("z-50 outline-none", options.class)))

export const PopoverPopup = <Msg>(
  h: Html.H<Msg>,
  popover: PopoverParts,
  options: ClassOption & { readonly size?: PopoverSize | undefined } = {}
) =>
  popover.popup(
    h.div.class(cn(
      "relative flex origin-[var(--transform-origin)] flex-col gap-2 rounded-lg border bg-popover p-4 text-[13px]",
      "text-foreground shadow-float outline-none",
      "h-[var(--popup-height,auto)] transition-[opacity,scale,height] duration-150 ease-out",
      "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
      "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
      "data-[instant]:duration-0",
      sizes[options.size ?? "default"],
      options.class
    ))
  )

/** A small diamond on the popup's edge. The kit points it at the trigger: leave room with `sideOffset: 12`. */
export const PopoverArrow = <Msg>(h: Html.H<Msg>, popover: PopoverParts, options: ClassOption = {}) =>
  popover.arrow(
    h.div.class(cn(
      "size-[10px] rotate-45 bg-popover",
      "data-[side=bottom]:-top-[5.5px] data-[side=bottom]:border-t data-[side=bottom]:border-l",
      "data-[side=top]:-bottom-[5.5px] data-[side=top]:border-r data-[side=top]:border-b",
      "data-[side=right]:-left-[5.5px] data-[side=right]:border-b data-[side=right]:border-l",
      "data-[side=left]:-right-[5.5px] data-[side=left]:border-t data-[side=left]:border-r",
      options.class
    ))
  )

/**
 * Around content that changes with the trigger, in a popover with several triggers:
 * the content of the last trigger fades out as the new one fades in.
 */
export const PopoverViewport = <Msg>(h: Html.H<Msg>, popover: PopoverParts, options: ClassOption = {}) =>
  popover.viewport(
    h.div.class(cn(
      "relative",
      "[&>[data-current]]:flex [&>[data-current]]:flex-col [&>[data-current]]:gap-2",
      "[&>[data-previous]]:flex [&>[data-previous]]:flex-col [&>[data-previous]]:gap-2",
      "[&>[data-current]]:transition-opacity [&>[data-current]]:duration-200",
      "[&>[data-previous]]:transition-opacity [&>[data-previous]]:duration-200",
      "[&>[data-current][data-starting-style]]:opacity-0 [&>[data-previous][data-ending-style]]:opacity-0",
      options.class
    ))
  )

export const PopoverTitle = <Msg>(h: Html.H<Msg>, popover: PopoverParts, options: ClassOption = {}) =>
  popover.title(h.h2.class(cn("m-0 border-0 p-0 text-sm leading-snug font-semibold", options.class)))

export const PopoverDescription = <Msg>(h: Html.H<Msg>, popover: PopoverParts, options: ClassOption = {}) =>
  popover.description(h.p.class(cn("m-0 text-[13px] leading-normal text-muted-foreground", options.class)))

export const PopoverFooter = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("mt-1 flex flex-wrap items-center justify-end gap-2", options.class))
```

```ts
import { PopoverPositioner, PopoverPopup, PopoverArrow, PopoverViewport, PopoverTitle, PopoverDescription, PopoverFooter } from "#ui/popover"
```

## Usage

Opens below its trigger, takes focus, and closes on Escape, a press outside or focus leaving.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PopoverDescription, PopoverFooter, PopoverPopup, PopoverPositioner, PopoverTitle } from "#ui/popover"

const PopoverBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: {},
  RequestedClosePopover: {}
})

export const PopoverBasic = Html.component({
  name: "PopoverBasic",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: PopoverBasicMessage
}).make({
  init: () => ({ open: false }),
  update: {
    RequestedOpenPopover: ($) => $.evolve({ open: true }),
    RequestedClosePopover: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    Popover(h, {
      props: { open: model.open, sideOffset: 8 },
      onEmit: {
        RequestedOpen: () => PopoverBasicMessage.RequestedOpenPopover(),
        RequestedClose: () => PopoverBasicMessage.RequestedClosePopover(),
        Settled: () => undefined
      },
      view: (popover) =>
        h.div(
          popover.trigger({ element: h.button.class(buttonVariants({ variant: "outline" })) }).children(
            "Notifications"
          ),
          popover.portal(h.dialog)?.children(
            PopoverPositioner(h, popover).children(
              PopoverPopup(h, popover).children(
                PopoverTitle(h, popover).children("You're all caught up"),
                PopoverDescription(h, popover).children(
                  "New mentions and review requests show up here as they arrive."
                ),
                PopoverFooter(h).children(
                  popover.close(h.button.class(buttonVariants({ variant: "outline", size: "sm" })))
                    .children("Close")
                )
              )
            )
          )
        )
    })
})
```

## Examples

### With a form

Fields in a popover write straight to the Model.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PopoverDescription, PopoverPopup, PopoverPositioner, PopoverTitle } from "#ui/popover"

const Dimension = Schema.Literals(["width", "maxWidth", "height"])

const PopoverFormMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: {},
  RequestedClosePopover: {},
  UpdatedDimension: { name: Dimension, value: Schema.String }
})

const fields = [
  { name: "width", label: "Width" },
  { name: "maxWidth", label: "Max. width" },
  { name: "height", label: "Height" }
] as const

const labelClass = "grid grid-cols-[5.5rem_1fr] items-center gap-3 text-[13px] font-medium"
const inputClass =
  "h-8.5 w-full rounded-md border border-input bg-background px-2.5 text-[13px] font-normal shadow-sm outline-none " +
  "transition-[border-color,box-shadow] duration-150 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/20"

export const PopoverForm = Html.component({
  name: "PopoverForm",
  model: Schema.Struct({
    open: Schema.Boolean,
    width: Schema.String,
    maxWidth: Schema.String,
    height: Schema.String
  }),
  message: PopoverFormMessage
}).make({
  init: () => ({ open: false, width: "100%", maxWidth: "300px", height: "25px" }),
  update: {
    RequestedOpenPopover: ($) => $.evolve({ open: true }),
    RequestedClosePopover: ($) => $.evolve({ open: false }),
    UpdatedDimension: ($, { name, value }) => $.evolve({ [name]: value })
  },
  view: (h, model) =>
    Popover(h, {
      props: { open: model.open, sideOffset: 8, align: "start" },
      onEmit: {
        RequestedOpen: () => PopoverFormMessage.RequestedOpenPopover(),
        RequestedClose: () => PopoverFormMessage.RequestedClosePopover(),
        Settled: () => undefined
      },
      view: (popover) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          popover.trigger({ element: h.button.class(buttonVariants({ variant: "outline" })) }).children(
            "Dimensions"
          ),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(`${model.width} × ${model.height}, at most ${model.maxWidth}`),
          popover.portal(h.dialog)?.children(
            PopoverPositioner(h, popover).children(
              PopoverPopup(h, popover).children(
                PopoverTitle(h, popover).children("Dimensions"),
                PopoverDescription(h, popover).children("Set the size of the layer."),
                h.div.class("mt-1 flex flex-col gap-2").children(
                  ...fields.map(({ label, name }) =>
                    h.label.class(labelClass).children(
                      label,
                      h.input.class(inputClass)
                        .value(model[name])
                        .on("input", ({ value }) => PopoverFormMessage.UpdatedDimension({ name, value }))
                    )
                  )
                )
              )
            )
          )
        )
    })
})
```

### Sides and alignment

The side and align props place the popup. It flips when it doesn't fit.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover, PopoverAlign, PopoverSide } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PopoverDescription, PopoverPopup, PopoverPositioner, PopoverTitle } from "#ui/popover"

const PopoverPlacementMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: { side: PopoverSide },
  RequestedClosePopover: {},
  PickedAlign: { align: PopoverAlign }
})

const sides = ["top", "right", "bottom", "left"] as const
const aligns = ["start", "center", "end"] as const

export const PopoverPlacement = Html.component({
  name: "PopoverPlacement",
  model: Schema.Struct({ open: Schema.NullOr(PopoverSide), align: PopoverAlign }),
  message: PopoverPlacementMessage
}).make({
  init: () => ({ open: null, align: "center" }),
  update: {
    RequestedOpenPopover: ($, { side }) => $.evolve({ open: side }),
    RequestedClosePopover: ($) => $.evolve({ open: null }),
    PickedAlign: ($, { align }) => $.evolve({ align })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      h.div.class("flex flex-wrap items-center justify-center gap-1")
        .attrs({ role: "group", "aria-label": "Alignment" })
        .children(
        ...aligns.map((align) =>
          h.button
            .class(buttonVariants({ size: "sm", variant: model.align === align ? "secondary" : "ghost" }))
            .attr("aria-pressed", String(model.align === align))
            .on("click", PopoverPlacementMessage.PickedAlign({ align }))
            .children(`align: ${align}`)
        )
      ),
      h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
        ...sides.map((side) =>
          Popover(h, {
            key: side,
            props: { open: model.open === side, side, align: model.align, sideOffset: 8 },
            onEmit: {
              RequestedOpen: () => PopoverPlacementMessage.RequestedOpenPopover({ side }),
              RequestedClose: () => PopoverPlacementMessage.RequestedClosePopover(),
              Settled: () => undefined
            },
            view: (popover) =>
              h.div(
                popover.trigger({ element: h.button.class(buttonVariants({ variant: "outline" })) }).children(side),
                popover.portal(h.dialog)?.children(
                  PopoverPositioner(h, popover).children(
                    PopoverPopup(h, popover, { size: "sm" }).children(
                      PopoverTitle(h, popover).children(`${popover.side}, ${popover.align}`),
                      // popover.side is where the popup ended up, after it flipped to fit.
                      PopoverDescription(h, popover).children(
                        popover.side === side ? "Placed where it was asked to be." : `Flipped from ${side} to fit.`
                      )
                    )
                  )
                )
              )
          })
        )
      )
    )
})
```

### With an arrow

The kit points the arrow at the trigger. The styles give it a size and a side.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PopoverArrow, PopoverDescription, PopoverPopup, PopoverPositioner, PopoverTitle } from "#ui/popover"

const PopoverWithArrowMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: {},
  RequestedClosePopover: {},
  ClickedCopy: {}
})

const inputClass =
  "h-8.5 w-full rounded-md border border-input bg-background px-2.5 text-[13px] font-normal shadow-sm outline-none " +
  "transition-[border-color,box-shadow] duration-150 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/20"

export const PopoverWithArrow = Html.component({
  name: "PopoverWithArrow",
  model: Schema.Struct({ open: Schema.Boolean, copied: Schema.Boolean }),
  message: PopoverWithArrowMessage
}).make({
  init: () => ({ open: false, copied: false }),
  update: {
    RequestedOpenPopover: ($) => $.evolve({ open: true, copied: false }),
    RequestedClosePopover: ($) => $.evolve({ open: false }),
    ClickedCopy: ($) => $.evolve({ copied: true })
  },
  view: (h, model) =>
    Popover(h, {
      // The arrow sits in the gap, so leave room for it.
      props: { open: model.open, sideOffset: 12 },
      onEmit: {
        RequestedOpen: () => PopoverWithArrowMessage.RequestedOpenPopover(),
        RequestedClose: () => PopoverWithArrowMessage.RequestedClosePopover(),
        Settled: () => undefined
      },
      view: (popover) =>
        h.div(
          popover.trigger({ element: h.button.class(buttonVariants({ variant: "outline" })) }).children("Share"),
          popover.portal(h.dialog)?.children(
            PopoverPositioner(h, popover).children(
              PopoverPopup(h, popover).children(
                // The kit gives the arrow its place along the edge; the styles give it its size.
                PopoverArrow(h, popover),
                PopoverTitle(h, popover).children("Share link"),
                PopoverDescription(h, popover).children(
                  "Anyone with this link can view the document."
                ),
                h.div.class("mt-1 flex items-center gap-2").children(
                  h.input.class(inputClass).attrs({ readonly: "", "aria-label": "Link" }).value("https://example.com/d/4f2a9c"),
                  h.button.class(buttonVariants({ size: "sm" }))
                    .on("click", PopoverWithArrowMessage.ClickedCopy())
                    .children(model.copied ? "Copied" : "Copy")
                )
              )
            )
          )
        )
    })
})
```

### Opened by hover

openOnHover on the trigger, with its own delay and closeDelay.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PopoverDescription, PopoverFooter, PopoverPopup, PopoverPositioner, PopoverTitle } from "#ui/popover"

const PopoverHoverMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: {},
  RequestedClosePopover: {}
})

export const PopoverHover = Html.component({
  name: "PopoverHover",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: PopoverHoverMessage
}).make({
  init: () => ({ open: false }),
  update: {
    RequestedOpenPopover: ($) => $.evolve({ open: true }),
    RequestedClosePopover: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    Popover(h, {
      props: { open: model.open, sideOffset: 8, side: "top" },
      onEmit: {
        RequestedOpen: () => PopoverHoverMessage.RequestedOpenPopover(),
        RequestedClose: () => PopoverHoverMessage.RequestedClosePopover(),
        Settled: () => undefined
      },
      view: (popover) =>
        h.div(
          // Opened by hover it takes no focus. A press within half a second keeps it open like a pressed one.
          popover.trigger({
            element: h.button.class(buttonVariants({ variant: "outline" })),
            openOnHover: true,
            delay: 150,
            closeDelay: 200
          }).children("Build #2841"),
          popover.portal(h.dialog)?.children(
            PopoverPositioner(h, popover).children(
              PopoverPopup(h, popover).children(
                PopoverTitle(h, popover).children("Build #2841 passed"),
                PopoverDescription(h, popover).children(
                  "main · 3 min 12 s · 418 tests. Opened by ",
                  h.strong(popover.openReason === "trigger-hover" ? "hover" : "a press"),
                  "."
                ),
                PopoverFooter(h).children(
                  h.a.class(buttonVariants({ variant: "outline", size: "sm" })).attrs({ href: "#hover" })
                    .children("View logs")
                )
              )
            )
          )
        )
    })
})
```

### Several triggers

One popover moves between three triggers, and its viewport cross-fades the content.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Popover } from "@effect/ui-kit"
import { Schema } from "effect"
import { PopoverDescription, PopoverPopup, PopoverPositioner, PopoverTitle, PopoverViewport } from "#ui/popover"

const PopoverTriggersMessage = UiSchema.TaggedEnum({
  RequestedOpenPopover: { triggerId: Schema.NullOr(Schema.String) },
  RequestedClosePopover: {}
})

const members = [
  { id: "member-ada", initials: "AL", name: "Ada Lovelace", role: "Engineering · Owner", note: "Reviews pull requests on weekday mornings." },
  { id: "member-grace", initials: "GH", name: "Grace Hopper", role: "Compilers · Admin", note: "On call this week. Page her for anything that blocks a release." },
  { id: "member-alan", initials: "AT", name: "Alan Turing", role: "Research · Member", note: "Away until Monday." }
] as const

const avatarClass =
  "grid size-10 place-items-center rounded-full border bg-muted text-xs font-semibold transition-colors duration-150 " +
  "hover:bg-accent data-[popup-open]:border-brand data-[popup-open]:bg-brand-wash"

export const PopoverTriggers = Html.component({
  name: "PopoverTriggers",
  model: Schema.Struct({ open: Schema.Boolean, triggerId: Schema.NullOr(Schema.String) }),
  message: PopoverTriggersMessage
}).make({
  init: () => ({ open: false, triggerId: null }),
  update: {
    // Also emitted while open, when another trigger asks for the popover.
    RequestedOpenPopover: ($, { triggerId }) => $.evolve({ open: true, triggerId }),
    RequestedClosePopover: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    Popover(h, {
      props: { open: model.open, triggerId: model.triggerId, sideOffset: 8 },
      onEmit: {
        RequestedOpen: ({ triggerId }) => PopoverTriggersMessage.RequestedOpenPopover({ triggerId }),
        RequestedClose: () => PopoverTriggersMessage.RequestedClosePopover(),
        Settled: () => undefined
      },
      view: (popover) => {
        const member = members.find(({ id }) => id === popover.triggerId) ?? members[0]
        return h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
          ...members.map(({ id, initials, name }) =>
            popover.trigger({
              element: h.button.class(avatarClass).attrs({ id, "aria-label": name }),
              openOnHover: true,
              delay: 100,
              closeDelay: 150
            }).children(initials)
          ),
          popover.portal(h.dialog)?.children(
            PopoverPositioner(h, popover).children(
              PopoverPopup(h, popover).children(
                // The viewport keeps the last trigger's content for a moment, so the two can cross-fade.
                PopoverViewport(h, popover).children(
                  PopoverTitle(h, popover).children(member.name),
                  PopoverDescription(h, popover).children(member.role),
                  h.p.class("m-0 border-t pt-2 text-[13px] leading-normal").children(member.note)
                )
              )
            )
          )
        )
      }
    })
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `trigger` | A <button> that opens the popover. Takes { element, openOnHover, delay, closeDelay, disabled }. |
| `portal` | The <dialog> in the top layer, around the parts below. |
| `backdrop` | A <div> that covers the page. Optional. |
| `positioner` | A <div> placed next to the trigger. sideOffset is its padding. |
| `popup` | A <div> with the popover's content. |
| `viewport` | A <div> around content that changes with the trigger. Optional. |
| `arrow` | A <div> that points at the trigger. Optional. |
| `title` | A heading that labels the popover. |
| `description` | A <p> that describes the popover. |
| `close` | A <button> that asks the popover to close. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `open` | `boolean` | Whether the popover shows. Required: the consumer owns it. |
| `modal` | `boolean \| "trap-focus"` | false by default. |
| `triggerId` | `string \| null` | The id of the trigger the popover is open for and placed against. |
| `side` | `"top" \| "bottom" \| "left" \| "right" \| "inline-start" \| "inline-end"` | The side of the trigger the popup shows on. |
| `align` | `"start" \| "center" \| "end"` | How the popup lines up with the trigger along that side. "center" by default. |
| `sideOffset` | `number` | The gap between the trigger and the popup, in pixels. |
| `alignOffset` | `number` | Pixels the popup moves along the side. |
| `collisionPadding` | `number` | Pixels kept from the viewport's edges, 5 by default. |
| `positionMethod` | `"absolute" \| "fixed"` | "absolute" by default, which scrolls with the page. |
| `keepMounted` | `boolean` | The portal stays in the page, hidden, while the popover is closed. |

### Events

| Event | Description |
| --- | --- |
| `RequestedOpen` | Carries the trigger's id and the reason: trigger-press or trigger-hover. Also emitted while open, when another trigger asks. |
| `RequestedClose` | Carries the reason: a Dialog's reasons, or trigger-hover. |
| `Settled` | The transitions of an open or a close finished. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-popup-open` | On the trigger while the popover is open for it. |
| `data-pressed` | On the trigger while the popover is open for it by a press. |
| `data-open / data-closed` | On the backdrop, positioner, popup and arrow. |
| `data-starting-style / data-ending-style` | On the backdrop and popup, to transition from and to. |
| `data-side / data-align` | On the positioner, popup and arrow: where the popup ended up, after it flipped or shifted to fit. |
| `data-instant` | On the popup: a change that should skip its transition. |
| `data-uncentered` | On the arrow while it can't point at the trigger's middle. |
| `--transform-origin` | On the positioner: the point on the trigger the popup grows from. |
| `--anchor-width / --available-height` | On the positioner: the trigger's size and the room left, for a width or max-height. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
