The principles of good typography remain the same in a digital interface.

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/preview-card.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { PreviewCard } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    /** What a `PreviewCard`'s `view` closure receives. */
    export type PreviewCardParts = Component.Headless.Parts<typeof PreviewCard>
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    const sizes = {
      sm: "w-52",
      default: "w-72"
    } as const
    
    export type PreviewCardSize = keyof typeof sizes
    
    /** The link the card previews, underlined. Each link has its own `delay` and `closeDelay`, and an `id` when there are several. */
    export const PreviewCardLink = <Msg>(
      h: Html.H<Msg>,
      previewCard: PreviewCardParts,
      options: ClassOption & {
        readonly href: string
        readonly id?: string | undefined
        readonly delay?: number | undefined
        readonly closeDelay?: number | undefined
      }
    ) =>
      previewCard.trigger({
        element: h.a
          .class(cn(
            "rounded-xs font-medium text-foreground underline decoration-muted-foreground/50 underline-offset-4",
            "transition-colors duration-150 hover:decoration-foreground data-[popup-open]:decoration-foreground",
            options.class
          ))
          .attrs({ href: options.href, id: options.id }),
        delay: options.delay,
        closeDelay: options.closeDelay
      })
    
    /** The box the kit places next to the link. The card's `sideOffset` is its padding. */
    export const PreviewCardPositioner = <Msg>(h: Html.H<Msg>, previewCard: PreviewCardParts, options: ClassOption = {}) =>
      previewCard.positioner(h.div.class(cn("z-50", options.class)))
    
    export const PreviewCardPopup = <Msg>(
      h: Html.H<Msg>,
      previewCard: PreviewCardParts,
      options: ClassOption & { readonly size?: PreviewCardSize | undefined } = {}
    ) =>
      previewCard.popup(
        h.div.class(cn(
          "relative flex origin-[var(--transform-origin)] flex-col gap-1.5 rounded-lg border bg-popover p-4 text-[13px]",
          "leading-normal 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",
          "[&_p]:m-0 [&_p]:text-muted-foreground",
          sizes[options.size ?? "default"],
          options.class
        ))
      )
    
    /** A small diamond on the card's edge. The kit points it at the link: leave room with `sideOffset: 10`. */
    export const PreviewCardArrow = <Msg>(h: Html.H<Msg>, previewCard: PreviewCardParts, options: ClassOption = {}) =>
      previewCard.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 link, in a card with several links:
     * the content of the last link fades out as the new one fades in.
     */
    export const PreviewCardViewport = <Msg>(h: Html.H<Msg>, previewCard: PreviewCardParts, options: ClassOption = {}) =>
      previewCard.viewport(
        h.div.class(cn(
          "relative",
          "[&>[data-current]]:flex [&>[data-current]]:flex-col [&>[data-current]]:gap-1.5",
          "[&>[data-previous]]:flex [&>[data-previous]]:flex-col [&>[data-previous]]:gap-1.5",
          "[&>[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
        ))
      )
    
    /** Small muted text in a card: a domain, a handle, a count. */
    export const PreviewCardMeta = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.span.class(cn("text-xs text-muted-foreground", options.class))
    
  3. Import it

    import { PreviewCardLink, PreviewCardPositioner, PreviewCardPopup, PreviewCardArrow, PreviewCardViewport, PreviewCardMeta } from "#ui/preview-card"
    

Usage

Link preview.ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { PreviewCard } from "@effect/ui-kit"
import { Schema } from "effect"
import { PreviewCardLink, PreviewCardMeta, PreviewCardPopup, PreviewCardPositioner } from "#ui/preview-card"

const PreviewCardBasicMessage = UiSchema.TaggedEnum({
  RequestedOpenPreviewCard: {},
  RequestedClosePreviewCard: {}
})

export const PreviewCardBasic = Html.component({
  name: "PreviewCardBasic",
  model: Schema.Struct({ open: Schema.Boolean }),
  message: PreviewCardBasicMessage
}).make({
  init: () => ({ open: false }),
  update: {
    RequestedOpenPreviewCard: ($) => $.evolve({ open: true }),
    RequestedClosePreviewCard: ($) => $.evolve({ open: false })
  },
  view: (h, model) =>
    PreviewCard(h, {
      props: { open: model.open, sideOffset: 8 },
      onEmit: {
        RequestedOpen: () => PreviewCardBasicMessage.RequestedOpenPreviewCard(),
        RequestedClose: () => PreviewCardBasicMessage.RequestedClosePreviewCard(),
        Settled: () => undefined
      },
      view: (previewCard) =>
        h.div(
          h.p.class("m-0 max-w-sm text-sm leading-relaxed text-muted-foreground").children(
            "The principles of good ",
            PreviewCardLink(h, previewCard, { href: "https://en.wikipedia.org/wiki/Typography" }).children("typography"),
            " remain the same in a digital interface."
          ),
          // Drawn right after the link's paragraph, so the card's own links follow it in the tab order.
          previewCard.portal(h.div)?.children(
            PreviewCardPositioner(h, previewCard).children(
              PreviewCardPopup(h, previewCard).children(
                h.div
                  .class(
                    "mb-1.5 grid h-28 place-items-center rounded-md bg-brand-wash font-serif text-5xl text-brand select-none"
                  )
                  .attr("aria-hidden", "true")
                  .children("Aa"),
                h.strong.class("text-sm").children("Typography"),
                h.p("The art and technique of arranging type to make written language legible and appealing."),
                PreviewCardMeta(h).children("en.wikipedia.org")
              )
            )
          )
        )
    })
})

Examples

User card

The pointer can cross to the card, so it can hold a control.

Reviewed by @effect-ts two days ago.

Sides, with an arrow

The side prop places the card, and it flips when it doesn't fit.

Several links, one card

The card moves from link to link, and its viewport cross-fades the content.

This release fixes #412, #398 and #377.

Delays

Each trigger has its own delay and closeDelay.

Anatomy

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

PartDescription
triggerThe <a> the card previews. Takes { element, delay, closeDelay }.
portalA <div> in the top layer, around the parts below. undefined while closed, unless keepMounted.
backdropA <div> that covers the page. It takes no presses. Optional.
positionerA <div> placed next to the trigger. sideOffset is its padding.
popupA <div> with the card's content.
viewportA <div> around content that changes with the trigger. Optional.
arrowA <div> that points at the trigger. Optional.

API reference

Props

PropTypeDescription
openbooleanWhether the card shows. Required: the consumer owns it.
triggerIdstring | nullThe id of the trigger the card 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.
sideOffsetnumberThe gap between the trigger and the popup, in pixels.
alignOffsetnumberPixels the popup moves along the side.
collisionPaddingnumberPixels kept from the viewport's edges, 5 by default.
positionMethod"absolute" | "fixed""absolute" by default, which scrolls with the page.
keepMountedbooleanThe portal stays in the page, hidden, while the card is closed.

Events

EventDescription
RequestedOpenCarries the trigger's id and the reason: hover or keyboard focus.
RequestedCloseCarries the reason, such as the pointer leaving, focus leaving, Escape or a press outside.
SettledThe transitions of an open or a close finished.

Data attributes

AttributeDescription
data-popup-openOn the trigger while the card is open for it.
data-open / data-closedOn the backdrop, positioner, popup and arrow.
data-starting-style / data-ending-styleOn the backdrop and popup, to transition from and to.
data-side / data-alignOn the positioner, popup and arrow: where the popup ended up, after it flipped or shifted to fit.
data-instantOn the popup: a change that should skip its transition.
data-uncenteredOn the arrow while it can't point at the trigger's middle.
--transform-originOn the positioner: the point on the trigger the popup grows from.
--anchor-width / --available-heightOn the positioner: the trigger's size and the room left, for a width or max-height.

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.