Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/positioning.ts
    import { Mount } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import { Positioning } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    type ClassOption = { readonly class?: string | undefined }
    
    /**
     * The element `Positioning.TrackPosition` places against its anchor: a
     * popover in the top layer, or an ordinary element when the args say
     * `topLayer: false`. It carries the mount while `open`, the inline style the
     * mount needs, and `data-side`, `data-align` and `data-anchor-hidden` from
     * the last `Placement`, which the caller keeps in its Model:
     *
     * `Positioner(h, { args, open: model.open, placement: model.placement, onPlacement: (placement) => Message.ChangedPlacement({ placement }) })`
     *
     * It hides itself while the anchor is scrolled or clipped out of view.
     */
    export const Positioner = <Msg>(
      h: Html.H<Msg>,
      options: ClassOption & {
        /** From `Positioning.trackArgs(props, { side, anchorSelector })`. */
        readonly args: Positioning.TrackPositionArgs
        readonly open: boolean
        /** The last placement the mount reported, or `null` before the first. */
        readonly placement: Positioning.Placement | null
        readonly onPlacement: (placement: Positioning.Placement) => Msg
        /** `"auto"` lets the browser close it on Escape or a press outside: follow its `toggle`. */
        readonly popover?: "manual" | "auto" | undefined
      }
    ) => {
      const { args, open, placement } = options
      const element = h.div
        .class(cn("z-50 w-max max-w-[var(--available-width)] data-[anchor-hidden]:invisible", options.class))
        .attrs({
          style: Positioning.positionerStyle(args.positionMethod),
          hidden: args.topLayer === false && !open ? "" : undefined,
          "data-side": placement?.side ?? args.options.side,
          "data-align": placement?.align ?? args.options.align,
          "data-anchor-hidden": placement?.anchorHidden === true ? "" : undefined
        })
      const layered = args.topLayer === false ? element : element.popover(options.popover ?? "manual", open)
      // The positioner has to be laid out while the mount runs.
      return open ? layered.onMount(Positioning.TrackPosition(args).pipe(Mount.map(options.onPlacement))) : layered
    }
    
    const sizes = {
      default: "p-3.5",
      sm: "px-2.5 py-1.5 text-xs"
    } as const
    
    /** The surface inside a `Positioner`. It fades and grows from the anchor when it first shows. */
    export const PositionerPopup = <Msg>(
      h: Html.H<Msg>,
      options: ClassOption & { readonly size?: keyof typeof sizes | undefined } = {}
    ) =>
      h.div.class(cn(
        "relative origin-[var(--transform-origin)] rounded-lg border bg-popover text-[13px] text-foreground shadow-float",
        "transition-[opacity,scale] duration-150 starting:scale-95 starting:opacity-0",
        sizes[options.size ?? "default"],
        options.class
      ))
    
    const arrowSides: Record<Positioning.Side, string> = {
      top: "-bottom-[5px] border-t-0 border-l-0",
      bottom: "-top-[5px] border-r-0 border-b-0",
      left: "-right-[5px] border-b-0 border-l-0",
      right: "-left-[5px] border-t-0 border-r-0",
      "inline-start": "-end-[5px] border-b-0 border-s-0 rtl:-rotate-45",
      "inline-end": "-start-[5px] border-t-0 border-e-0 rtl:-rotate-45"
    }
    
    /**
     * An arrow inside a `PositionerPopup`, pointing at the anchor. Pass its `id`
     * to `trackArgs` as `arrowId`, so the mount measures it, and the side from
     * the placement. It fades when it can't point at the anchor's middle.
     */
    export const PositionerArrow = <Msg>(
      h: Html.H<Msg>,
      options: ClassOption & {
        readonly id: string
        readonly side: Positioning.Side
        readonly uncentered?: boolean | undefined
      }
    ) =>
      h.span
        .id(options.id)
        .class(cn(
          "size-2.5 rotate-45 border bg-popover data-[uncentered]:opacity-0",
          arrowSides[options.side],
          options.class
        ))
        .attrs({
          style: Positioning.arrowStyle(options.side),
          "data-side": options.side,
          "data-uncentered": options.uncentered === true ? "" : undefined,
          "aria-hidden": "true"
        })
    
  3. Import it

    import { Positioner, PositionerPopup, PositionerArrow } from "#ui/positioning"
    

Usage

A hand-built popup.ts
import { UiSchema, UiStruct } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Positioning } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { Positioner, PositionerPopup } from "#ui/positioning"

const PositioningBasicMessage = UiSchema.TaggedEnum({
  PressedShare: {},
  PressedDone: {},
  ChangedPlacement: { placement: Positioning.Placement }
})

export const PositioningBasic = Html.component({
  name: "PositioningBasic",
  model: Schema.Struct({ open: Schema.Boolean, placement: Schema.NullOr(Positioning.Placement) }),
  message: PositioningBasicMessage,
  // A placement is a measurement: after Back the mount reports it again.
  restore: (model) => UiStruct.evolve(model, { placement: null })
}).make({
  init: () => ({ open: false, placement: null }),
  update: {
    PressedShare: ($) => $.evolve({ open: (open) => !open }),
    PressedDone: ($) => $.evolve({ open: false }),
    ChangedPlacement: ($, { placement }) => $.evolve({ placement })
  },
  view: (h, model) => {
    const anchorId = h.id("anchor")
    const args = Positioning.trackArgs(
      { align: "start", sideOffset: 8 },
      { side: "bottom", anchorSelector: `[id="${anchorId}"]` }
    )
    return h.div.children(
      Button(h, { variant: "outline", onPress: PositioningBasicMessage.PressedShare() })
        .id(anchorId)
        .attr("aria-expanded", String(model.open))
        .children("Share"),
      Positioner(h, {
        args,
        open: model.open,
        placement: model.placement,
        onPlacement: (placement) => PositioningBasicMessage.ChangedPlacement({ placement })
      }).children(
        PositionerPopup(h, { class: "grid w-64 gap-1" }).attrs({ role: "dialog", "aria-label": "Share" }).children(
          h.strong.class("font-semibold").children("Share this page"),
          h.p.class("mb-2 text-muted-foreground").children("Anyone with the link can view it."),
          Button(h, { size: "sm", class: "justify-self-start", onPress: PositioningBasicMessage.PressedDone() })
            .children("Done")
        )
      )
    )
  }
})

Examples

Side and align

Six sides, three alignments and an offset. The popup is drawn in place with topLayer: false.

Anchor
top · center

Collisions

Scroll the box: the popup flips to the other side, slides over the anchor, or stays and is clipped.

Scroll me
side: bottom

Moves to the opposite side when it would leave the box.

With an arrow

The mount measures the arrow by its id and arrowStyle puts it at the anchor's middle.

?
The arrow points at the middle of the anchor.

At the pointer

The anchor is a rectangle instead of an element: a menu where the right-click landed.

Right-click anywhere in here

Nothing picked yet.

place()

The pure function under the mount: rectangles and options in, a position out, with no DOM.

anchor
bottom · center
place() → { x: 110, y: 94, side: "bottom", align: "center" }

Anatomy

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

PartDescription
place(input)Pure: anchor, popup, arrow and boundary rectangles and options in, a position, side and align out.
TrackPosition(args)A stream mount for the positioner. It writes left and top inline and reports a Placement when it changes.
trackArgs(props, popup)Builds the mount's args from positioning props and the popup's own defaults and anchor selector.
resolveOptions(props, defaults)Fills in the defaults of the positioning props, for place.
positionerStyle(method)The inline style a positioner needs before the mount places it.
arrowStyle(side)The inline style that puts an arrow where the mount measured it.
PositionerFieldsThe positioning props as Schema fields, to spread into a component's props.
PlacementSchema of what the mount reports: side, align, anchorHidden, arrowUncentered.

API reference

Props

PropTypeDescription
side"top" | "bottom" | "left" | "right" | "inline-start" | "inline-end"The side of the anchor the popup shows on.
align"start" | "center" | "end"How the popup lines up with the anchor along that side. "center" by default.
sideOffsetnumberThe gap between the anchor and the popup, in pixels.
alignOffsetnumberPixels the popup moves along the side.
collisionAvoidance{ side?, align?, fallbackAxisSide? }What happens when the popup doesn't fit: "flip", "shift" or "none" for each.
collisionBoundary"clipping-ancestors" | { id } | RectThe area the popup keeps inside. The viewport by default.
collisionPaddingnumber | { top?, right?, bottom?, left? }Pixels kept from the boundary's edges. 5 by default.
stickybooleanThe popup stays in view when the anchor scrolls out of it.
arrowPaddingnumberPixels kept between the arrow and the popup's corners. 5 by default.
positionMethod"absolute" | "fixed"The CSS position of the positioner.
anchorstring | RectThe id of an element, or a rectangle in the viewport, to place against instead.
topLayerbooleanfalse draws the positioner in place, so an ancestor's overflow and stacking apply.
disableAnchorTrackingbooleanPlace the popup only when it opens, the window resizes or its size changes.

Events

EventDescription
PlacementReported by TrackPosition when it starts, then whenever side, align, anchorHidden or arrowUncentered changes.

Data attributes

AttributeDescription
left / topWritten inline on the positioner: the position.
--anchor-width / --anchor-heightThe anchor's size.
--available-width / --available-heightThe space between the anchor and the boundary's edge, for a max-height.
--transform-originThe point on the anchor the popup grows from.
data-side / data-alignWritten by you from the Placement the mount reports (the Positioner helper does it).
data-anchor-hiddenLikewise, while the anchor is scrolled or clipped out of view.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.