PreviewCard
A card that previews what a link leads to while the link is hovered or focused.
The principles of good typography remain the same in a digital interface.
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")
)
)
)
)
})
})
Installation
Set up the project
Once per project: the packages, Tailwind CSS, the theme tokens and the
cnhelper. Follow Installation.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))Import it
import { PreviewCardLink, PreviewCardPositioner, PreviewCardPopup, PreviewCardArrow, PreviewCardViewport, PreviewCardMeta } from "#ui/preview-card"
Usage
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.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { PreviewCard } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { PreviewCardLink, PreviewCardMeta, PreviewCardPopup, PreviewCardPositioner } from "#ui/preview-card"
const PreviewCardUserMessage = UiSchema.TaggedEnum({
RequestedOpenPreviewCard: {},
RequestedClosePreviewCard: {},
ClickedFollow: {}
})
export const PreviewCardUser = Html.component({
name: "PreviewCardUser",
model: Schema.Struct({ open: Schema.Boolean, following: Schema.Boolean }),
message: PreviewCardUserMessage
}).make({
init: () => ({ open: false, following: false }),
update: {
RequestedOpenPreviewCard: ($) => $.evolve({ open: true }),
RequestedClosePreviewCard: ($) => $.evolve({ open: false }),
ClickedFollow: ($) => $.evolve({ following: (following) => !following })
},
view: (h, model) =>
PreviewCard(h, {
props: { open: model.open, sideOffset: 8, align: "start" },
onEmit: {
RequestedOpen: () => PreviewCardUserMessage.RequestedOpenPreviewCard(),
RequestedClose: () => PreviewCardUserMessage.RequestedClosePreviewCard(),
Settled: () => undefined
},
view: (previewCard) =>
h.div(
h.p.class("m-0 max-w-sm text-sm leading-relaxed text-muted-foreground").children(
"Reviewed by ",
PreviewCardLink(h, previewCard, { href: "https://github.com/effect-ts", delay: 300 }).children("@effect-ts"),
" two days ago."
),
previewCard.portal(h.div)?.children(
PreviewCardPositioner(h, previewCard).children(
PreviewCardPopup(h, previewCard).children(
h.div.class("mb-1 flex items-start justify-between").children(
h.span
.class("grid size-11 place-items-center rounded-full bg-brand text-lg font-semibold text-brand-foreground")
.attr("aria-hidden", "true")
.children("E"),
// The pointer can move onto the card, so it can hold a control.
h.button.class(buttonVariants({ size: "sm", variant: model.following ? "outline" : "default" }))
.on("click", PreviewCardUserMessage.ClickedFollow())
.children(model.following ? "Following" : "Follow")
),
h.strong.class("text-sm").children("Effect"),
PreviewCardMeta(h).children("@effect-ts"),
h.p("The missing standard library for TypeScript: typed errors, concurrency and resources."),
PreviewCardMeta(h).children(
h.strong.class("text-foreground").children(model.following ? "12 401" : "12 400"),
" followers · joined March 2021"
)
)
)
)
)
})
})
Sides, with an arrow
The side prop places the card, and it flips when it doesn't fit.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { PreviewCard, PreviewCardSide } from "@effect/ui-kit"
import { Schema } from "effect"
import { PreviewCardArrow, PreviewCardLink, PreviewCardPopup, PreviewCardPositioner } from "#ui/preview-card"
const PreviewCardSidesMessage = UiSchema.TaggedEnum({
RequestedOpenPreviewCard: { side: PreviewCardSide },
RequestedClosePreviewCard: { side: PreviewCardSide }
})
const sides = ["left", "top", "bottom", "right"] as const
export const PreviewCardSides = Html.component({
name: "PreviewCardSides",
model: Schema.Struct({ open: Schema.NullOr(PreviewCardSide) }),
message: PreviewCardSidesMessage
}).make({
init: () => ({ open: null }),
update: {
RequestedOpenPreviewCard: ($, { side }) => $.evolve({ open: side }),
RequestedClosePreviewCard: ($, { side }) => $.model.open === side ? $.evolve({ open: null }) : $.model
},
view: (h, model) =>
h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
...sides.map((side) =>
PreviewCard(h, {
key: side,
props: { open: model.open === side, side, sideOffset: 10 },
onEmit: {
RequestedOpen: () => PreviewCardSidesMessage.RequestedOpenPreviewCard({ side }),
RequestedClose: () => PreviewCardSidesMessage.RequestedClosePreviewCard({ side }),
Settled: () => undefined
},
view: (previewCard) =>
h.span(
PreviewCardLink(h, previewCard, { href: `#${side}`, delay: 200, closeDelay: 100 }).children(side),
previewCard.portal(h.div)?.children(
PreviewCardPositioner(h, previewCard).children(
PreviewCardPopup(h, previewCard, { size: "sm" }).children(
PreviewCardArrow(h, previewCard),
h.strong(`side: "${side}"`),
// previewCard.side is where the card ended up, after it flipped to fit.
h.p(previewCard.side === side ? "Placed where it was asked to be." : `Flipped to the ${previewCard.side} to fit.`)
)
)
)
)
})
)
)
})
Several links, one card
The card moves from link to link, and its viewport cross-fades the content.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { PreviewCard } from "@effect/ui-kit"
import { Schema } from "effect"
import { PreviewCardLink, PreviewCardPopup, PreviewCardPositioner, PreviewCardViewport } from "#ui/preview-card"
const PreviewCardTriggersMessage = UiSchema.TaggedEnum({
RequestedOpenPreviewCard: { triggerId: Schema.NullOr(Schema.String) },
RequestedClosePreviewCard: {}
})
const issues = [
{ id: "issue-412", number: 412, title: "Popover flips to the wrong side in RTL", state: "Open", text: "With dir=rtl, inline-start resolves to the left edge. Opened by ada 3 days ago." },
{ id: "issue-398", number: 398, title: "Drawer snap points ignore rem units", state: "Closed", text: "Fixed by reading the root font size when a snap point ends in rem. Closed by grace last week." },
{ id: "issue-377", number: 377, title: "Tooltip stays open after Escape", state: "Closed", text: "Escape now closes a tooltip whatever holds it open. Closed by alan last month." }
] as const
const badgeClasses = {
Open: "self-start rounded-full bg-brand px-2 py-0.5 text-[11px] font-medium text-brand-foreground",
Closed: "self-start rounded-full border px-2 py-0.5 text-[11px] font-medium text-muted-foreground"
} as const
export const PreviewCardTriggers = Html.component({
name: "PreviewCardTriggers",
model: Schema.Struct({ open: Schema.Boolean, triggerId: Schema.NullOr(Schema.String) }),
message: PreviewCardTriggersMessage
}).make({
init: () => ({ open: false, triggerId: null }),
update: {
RequestedOpenPreviewCard: ($, { triggerId }) => $.evolve({ open: true, triggerId }),
RequestedClosePreviewCard: ($) => $.evolve({ open: false })
},
view: (h, model) =>
// One card for every link: it is placed against the trigger named by triggerId,
// and moves at once when the pointer goes from one link to the next.
PreviewCard(h, {
props: { open: model.open, triggerId: model.triggerId, sideOffset: 8, align: "start" },
onEmit: {
RequestedOpen: ({ triggerId }) => PreviewCardTriggersMessage.RequestedOpenPreviewCard({ triggerId }),
RequestedClose: () => PreviewCardTriggersMessage.RequestedClosePreviewCard(),
Settled: () => undefined
},
view: (previewCard) => {
const issue = issues.find(({ id }) => id === model.triggerId) ?? issues[0]
return h.div(
h.p.class("m-0 max-w-sm text-sm leading-relaxed text-muted-foreground").children(
"This release fixes ",
...issues.flatMap(({ id, number }, index) => [
index === 0 ? "" : index === issues.length - 1 ? " and " : ", ",
PreviewCardLink(h, previewCard, { id, href: `#${number}`, delay: 250 }).children(`#${number}`)
]),
"."
),
previewCard.portal(h.div)?.children(
PreviewCardPositioner(h, previewCard).children(
PreviewCardPopup(h, previewCard).children(
PreviewCardViewport(h, previewCard).children(
h.span.class(badgeClasses[issue.state]).children(issue.state),
h.strong(issue.title),
h.p(issue.text)
)
)
)
)
)
}
})
})
Delays
Each trigger has its own delay and closeDelay.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { PreviewCard } from "@effect/ui-kit"
import { Schema } from "effect"
import { PreviewCardLink, PreviewCardPopup, PreviewCardPositioner } from "#ui/preview-card"
const Speed = Schema.Literals(["instant", "default", "patient"])
const PreviewCardDelayMessage = UiSchema.TaggedEnum({
RequestedOpenPreviewCard: { speed: Speed },
RequestedClosePreviewCard: { speed: Speed }
})
const speeds = [
{ speed: "instant", label: "Instant", delay: 0, closeDelay: 0 },
{ speed: "default", label: "Default", delay: 600, closeDelay: 300 },
{ speed: "patient", label: "Patient", delay: 1000, closeDelay: 800 }
] as const
export const PreviewCardDelay = Html.component({
name: "PreviewCardDelay",
model: Schema.Struct({ open: Schema.Array(Speed) }),
message: PreviewCardDelayMessage
}).make({
init: () => ({ open: [] }),
update: {
RequestedOpenPreviewCard: ($, { speed }) =>
$.evolve({ open: (open) => open.includes(speed) ? open : [...open, speed] }),
RequestedClosePreviewCard: ($, { speed }) => $.evolve({ open: (open) => open.filter((other) => other !== speed) })
},
view: (h, model) =>
h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
...speeds.map(({ closeDelay, delay, label, speed }) =>
PreviewCard(h, {
key: speed,
props: { open: model.open.includes(speed), sideOffset: 8 },
onEmit: {
RequestedOpen: () => PreviewCardDelayMessage.RequestedOpenPreviewCard({ speed }),
RequestedClose: () => PreviewCardDelayMessage.RequestedClosePreviewCard({ speed }),
Settled: () => undefined
},
view: (previewCard) =>
h.span(
// The delays belong to the trigger, so two links to one card can differ.
PreviewCardLink(h, previewCard, { href: `#${speed}`, delay, closeDelay }).children(label),
previewCard.portal(h.div)?.children(
PreviewCardPositioner(h, previewCard).children(
PreviewCardPopup(h, previewCard, { size: "sm" }).children(
h.strong(label),
h.p(`Opens after ${delay} ms and closes ${closeDelay} ms after the pointer leaves.`)
)
)
)
)
})
)
)
})
Anatomy
The parts the view closure receives. Apply each one to an element of your own.
| Part | Description |
|---|---|
trigger | The <a> the card previews. Takes { element, delay, closeDelay }. |
portal | A <div> in the top layer, around the parts below. undefined while closed, unless keepMounted. |
backdrop | A <div> that covers the page. It takes no presses. Optional. |
positioner | A <div> placed next to the trigger. sideOffset is its padding. |
popup | A <div> with the card's content. |
viewport | A <div> around content that changes with the trigger. Optional. |
arrow | A <div> that points at the trigger. Optional. |
API reference
Props
| Prop | Type | Description |
|---|---|---|
open | boolean | Whether the card shows. Required: the consumer owns it. |
triggerId | string | null | The 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. |
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 card is closed. |
Events
| Event | Description |
|---|---|
RequestedOpen | Carries the trigger's id and the reason: hover or keyboard focus. |
RequestedClose | Carries the reason, such as the pointer leaving, focus leaving, Escape or a press outside. |
Settled | The transitions of an open or a close finished. |
Data attributes
| Attribute | Description |
|---|---|
data-popup-open | On the trigger while the card is open for it. |
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
The components this page's file and examples import.
- Button: A native button that can stay focusable while disabled.