Tooltip
A short visual label shown while its trigger is hovered or focused with the keyboard.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { TooltipArrow, TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const TooltipBasicMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: {},
RequestedCloseTooltip: {}
})
export const TooltipBasic = Html.component({
name: "TooltipBasic",
model: Schema.Struct({ open: Schema.Boolean }),
message: TooltipBasicMessage
}).make({
init: () => ({ open: false }),
update: {
RequestedOpenTooltip: ($) => $.evolve({ open: true }),
RequestedCloseTooltip: ($) => $.evolve({ open: false })
},
view: (h, model) =>
Tooltip(h, {
props: { open: model.open, sideOffset: 8 },
onEmit: {
RequestedOpen: () => TooltipBasicMessage.RequestedOpenTooltip(),
RequestedClose: () => TooltipBasicMessage.RequestedCloseTooltip()
},
view: (tooltip) =>
h.div(
tooltip.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Hover me"),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(
TooltipArrow(h, tooltip),
"Add to library"
)
)
)
})
})
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/tooltip.ts import type { Component } from "@effect/ui" import type { Html } from "@effect/ui/html" import type { Tooltip } from "@effect/ui-kit" import { cn } from "#lib/cn" /** What a `Tooltip`'s `view` closure receives. */ export type TooltipParts = Component.Headless.Parts<typeof Tooltip> interface ClassOption { readonly class?: string | undefined } const variants = { default: "bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground", rich: "max-w-64 border bg-popover p-3 text-xs leading-relaxed text-foreground shadow-float" } as const export type TooltipVariant = keyof typeof variants /** * The box the kit places next to the trigger. The tooltip's `sideOffset` is its padding. * It stays displayed for the length of the popup's exit transition. */ export const TooltipPositioner = <Msg>(h: Html.H<Msg>, tooltip: TooltipParts, options: ClassOption = {}) => tooltip.positioner(h.div.class(cn("transition-[display,overlay] transition-discrete duration-150", options.class))) /** The bubble. `variant: "rich"` is a small card for more than a label. */ export const TooltipPopup = <Msg>( h: Html.H<Msg>, tooltip: TooltipParts, options: ClassOption & { readonly variant?: TooltipVariant | undefined } = {} ) => tooltip.popup( h.div.class(cn( "relative flex origin-[var(--transform-origin)] items-center gap-2 rounded-sm whitespace-nowrap", "transition-[opacity,scale] duration-150 ease-out", "data-[closed]:scale-95 data-[closed]:opacity-0 starting:scale-95 starting:opacity-0", "data-[instant]:duration-0", variants[options.variant ?? "default"], options.variant === "rich" && "flex-col items-stretch gap-1.5 rounded-lg whitespace-normal", options.class )) ) /** A small diamond on the popup's edge, in the default variant's colour. The kit points it at the trigger. */ export const TooltipArrow = <Msg>(h: Html.H<Msg>, tooltip: TooltipParts, options: ClassOption = {}) => tooltip.arrow( h.div.class(cn( "size-2 rotate-45 rounded-[1px] bg-primary", "data-[side=bottom]:-top-1 data-[side=left]:-right-1 data-[side=right]:-left-1 data-[side=top]:-bottom-1", options.class )) ) /** A keyboard shortcut inside a tooltip. */ export const TooltipShortcut = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) => h.kbd.class(cn("rounded-xs bg-primary-foreground/15 px-1 py-px font-mono text-[11px]", options.class))Import it
import { TooltipPositioner, TooltipPopup, TooltipArrow, TooltipShortcut } from "#ui/tooltip"
Usage
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { TooltipArrow, TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const TooltipBasicMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: {},
RequestedCloseTooltip: {}
})
export const TooltipBasic = Html.component({
name: "TooltipBasic",
model: Schema.Struct({ open: Schema.Boolean }),
message: TooltipBasicMessage
}).make({
init: () => ({ open: false }),
update: {
RequestedOpenTooltip: ($) => $.evolve({ open: true }),
RequestedCloseTooltip: ($) => $.evolve({ open: false })
},
view: (h, model) =>
Tooltip(h, {
props: { open: model.open, sideOffset: 8 },
onEmit: {
RequestedOpen: () => TooltipBasicMessage.RequestedOpenTooltip(),
RequestedClose: () => TooltipBasicMessage.RequestedCloseTooltip()
},
view: (tooltip) =>
h.div(
tooltip.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children("Hover me"),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(
TooltipArrow(h, tooltip),
"Add to library"
)
)
)
})
})
Examples
Sides
The side prop, with one Model field for which tooltip is open.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip, TooltipSide } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { TooltipArrow, TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const TooltipSidesMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: { side: TooltipSide },
RequestedCloseTooltip: { side: TooltipSide }
})
const sides = ["left", "top", "bottom", "right"] as const
export const TooltipSides = Html.component({
name: "TooltipSides",
// One field for which tooltip is open closes the last one as the next one opens.
model: Schema.Struct({ open: Schema.NullOr(TooltipSide) }),
message: TooltipSidesMessage
}).make({
init: () => ({ open: null }),
update: {
RequestedOpenTooltip: ($, { side }) => $.evolve({ open: side }),
RequestedCloseTooltip: ($, { 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) =>
Tooltip(h, {
key: side,
props: { open: model.open === side, side, sideOffset: 8, delay: 200 },
onEmit: {
RequestedOpen: () => TooltipSidesMessage.RequestedOpenTooltip({ side }),
RequestedClose: () => TooltipSidesMessage.RequestedCloseTooltip({ side })
},
view: (tooltip) =>
h.div(
tooltip.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children(side),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(
TooltipArrow(h, tooltip),
`On the ${tooltip.side}`
)
)
)
})
)
)
})
TooltipProvider
In a group, once one tooltip has shown, its neighbours open without their delay.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip, TooltipProvider } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { TooltipPopup, TooltipPositioner, TooltipShortcut } from "#ui/tooltip"
const Tool = Schema.Literals(["bold", "italic", "underline", "link"])
const TooltipProviderToolbarMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: { tool: Tool },
RequestedCloseTooltip: { tool: Tool },
ClickedTool: { tool: Tool }
})
const tools = [
{ tool: "bold", label: "Bold", shortcut: "⌘B", glyph: "B" },
{ tool: "italic", label: "Italic", shortcut: "⌘I", glyph: "I" },
{ tool: "underline", label: "Underline", shortcut: "⌘U", glyph: "U" },
{ tool: "link", label: "Insert link", shortcut: "⌘K", glyph: "↗" }
] as const
export const TooltipProviderToolbar = Html.component({
name: "TooltipProviderToolbar",
model: Schema.Struct({ tip: Schema.NullOr(Tool), active: Schema.Array(Tool) }),
message: TooltipProviderToolbarMessage
}).make({
init: () => ({ tip: null, active: ["bold"] }),
update: {
RequestedOpenTooltip: ($, { tool }) => $.evolve({ tip: tool }),
RequestedCloseTooltip: ($, { tool }) => $.model.tip === tool ? $.evolve({ tip: null }) : $.model,
ClickedTool: ($, { tool }) =>
$.evolve({
active: (active) => active.includes(tool) ? active.filter((other) => other !== tool) : [...active, tool]
})
},
view: (h, model) =>
// Once one tooltip of the group has shown, its neighbours open without their delay,
// until 600 ms after the last one closed.
TooltipProvider(h, {
props: { timeout: 600 },
view: () =>
h.div.class("flex items-center gap-0.5 rounded-lg border bg-background p-1 shadow-sm").attrs({ role: "toolbar", "aria-label": "Formatting" }).children(
...tools.map(({ glyph, label, shortcut, tool }) =>
Tooltip(h, {
key: tool,
props: { open: model.tip === tool, sideOffset: 8, delay: 700 },
onEmit: {
RequestedOpen: () => TooltipProviderToolbarMessage.RequestedOpenTooltip({ tool }),
RequestedClose: () => TooltipProviderToolbarMessage.RequestedCloseTooltip({ tool })
},
view: (tooltip) =>
h.div(
tooltip.trigger(
h.button.class(buttonVariants({ variant: model.active.includes(tool) ? "secondary" : "ghost", size: "icon" })).attrs({ "aria-label": label, "aria-pressed": String(model.active.includes(tool)) })
).on("click", TooltipProviderToolbarMessage.ClickedTool({ tool })).children(glyph),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(label, TooltipShortcut(h).children(shortcut))
)
)
})
)
)
})
})
Delays
delay before it opens and closeDelay before it closes.
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const Timing = Schema.Literals(["instant", "default", "slow", "lingering"])
const TooltipDelayMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: { timing: Timing },
RequestedCloseTooltip: { timing: Timing }
})
const timings = [
{ timing: "instant", label: "Instant", props: { delay: 0 }, text: "delay: 0" },
{ timing: "default", label: "Default", props: {}, text: "delay: 600, the default" },
{ timing: "slow", label: "Slow", props: { delay: 1200 }, text: "delay: 1200" },
{ timing: "lingering", label: "Lingering", props: { delay: 0, closeDelay: 800 }, text: "closeDelay: 800" }
] as const
export const TooltipDelay = Html.component({
name: "TooltipDelay",
model: Schema.Struct({ open: Schema.Array(Timing) }),
message: TooltipDelayMessage
}).make({
init: () => ({ open: [] }),
update: {
RequestedOpenTooltip: ($, { timing }) =>
$.evolve({ open: (open) => open.includes(timing) ? open : [...open, timing] }),
RequestedCloseTooltip: ($, { timing }) => $.evolve({ open: (open) => open.filter((other) => other !== timing) })
},
view: (h, model) =>
h.div.class("flex flex-wrap items-center justify-center gap-2.5").children(
...timings.map(({ label, props, text, timing }) =>
Tooltip(h, {
key: timing,
props: { open: model.open.includes(timing), sideOffset: 8, ...props },
onEmit: {
RequestedOpen: () => TooltipDelayMessage.RequestedOpenTooltip({ timing }),
RequestedClose: () => TooltipDelayMessage.RequestedCloseTooltip({ timing })
},
view: (tooltip) =>
h.div(
tooltip.trigger(h.button.class(buttonVariants({ variant: "outline" }))).children(label),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(text)
)
)
})
)
)
})
On a disabled button
A Button that stays focusable while disabled can still explain itself.
Published 0 times
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { TooltipArrow, TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const TooltipDisabledButtonMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: {},
RequestedCloseTooltip: {},
ToggledAgreement: { checked: Schema.Boolean },
PressedPublish: {}
})
export const TooltipDisabledButton = Html.component({
name: "TooltipDisabledButton",
model: Schema.Struct({ open: Schema.Boolean, agreed: Schema.Boolean, published: Schema.Number }),
message: TooltipDisabledButtonMessage
}).make({
init: () => ({ open: false, agreed: false, published: 0 }),
update: {
RequestedOpenTooltip: ($) => $.evolve({ open: true }),
RequestedCloseTooltip: ($) => $.evolve({ open: false }),
ToggledAgreement: ($, { checked }) => $.evolve({ agreed: checked, open: false }),
PressedPublish: ($) => $.evolve({ published: (published) => published + 1 })
},
view: (h, model) =>
h.div.class("flex flex-col items-center gap-3.5").children(
Tooltip(h, {
// The tooltip explains the disabled state, so it describes the trigger for screen readers too.
props: { open: model.open, sideOffset: 8, delay: 200, disabled: model.agreed, describesTrigger: true },
onEmit: {
RequestedOpen: () => TooltipDisabledButtonMessage.RequestedOpenTooltip(),
RequestedClose: () => TooltipDisabledButtonMessage.RequestedCloseTooltip()
},
view: (tooltip) =>
h.div(
// A natively disabled button takes no hover or focus. focusableWhenDisabled keeps both.
Button(h, {
element: tooltip.trigger(h.button),
props: { disabled: !model.agreed, focusableWhenDisabled: true },
onPress: TooltipDisabledButtonMessage.PressedPublish()
}).children("Publish"),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip).children(
TooltipArrow(h, tooltip),
"Accept the terms to publish"
)
)
)
}),
h.label.class("flex items-center gap-2").children(
h.input.class("size-3.5 accent-brand").attr("type", "checkbox").checked(model.agreed)
.on("change", ({ checked }) => TooltipDisabledButtonMessage.ToggledAgreement({ checked })),
h.span.class("text-[13px] font-medium").children("I accept the terms")
),
h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(`Published ${model.published} times`)
)
})
Rich content
The pointer can move onto the popup, so it can hold more than a label.
Usage this month: 82% of quota
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Tooltip } from "@effect/ui-kit"
import { Schema } from "effect"
import { TooltipPopup, TooltipPositioner } from "#ui/tooltip"
const TooltipRichMessage = UiSchema.TaggedEnum({
RequestedOpenTooltip: {},
RequestedCloseTooltip: {}
})
const facts = [["Used", "820 000"], ["Limit", "1 000 000"], ["Resets", "1 December"]] as const
export const TooltipRich = Html.component({
name: "TooltipRich",
model: Schema.Struct({ open: Schema.Boolean }),
message: TooltipRichMessage
}).make({
init: () => ({ open: false }),
update: {
RequestedOpenTooltip: ($) => $.evolve({ open: true }),
RequestedCloseTooltip: ($) => $.evolve({ open: false })
},
view: (h, model) =>
h.p.class("m-0 flex items-center gap-1.5 text-sm").children(
"Usage this month: 82% of quota ",
Tooltip(h, {
// The pointer can move onto the popup, so its text can be selected. closeDelay gives it time to get there.
props: { open: model.open, side: "bottom", align: "start", sideOffset: 8, delay: 150, closeDelay: 150 },
onEmit: {
RequestedOpen: () => TooltipRichMessage.RequestedOpenTooltip(),
RequestedClose: () => TooltipRichMessage.RequestedCloseTooltip()
},
view: (tooltip) =>
h.span(
tooltip.trigger(h.button
.class(
"grid size-4.5 place-items-center rounded-full border text-[11px] font-semibold text-muted-foreground " +
"transition-colors duration-150 hover:bg-accent hover:text-foreground"
)
.attr("aria-label", "How quota is counted")).children("?"),
TooltipPositioner(h, tooltip).children(
TooltipPopup(h, tooltip, { variant: "rich" }).children(
h.strong.class("text-[13px]").children("How quota is counted"),
h.span.class("text-muted-foreground").children("Every request that reaches your project counts once, cached responses included."),
h.dl.class("m-0 mt-1 grid grid-cols-[auto_1fr] gap-x-4 gap-y-0.5 border-t pt-2 tabular-nums").children(
...facts.flatMap(([term, value]) => [
h.dt.class("text-muted-foreground").children(term),
h.dd.class("m-0 text-right font-medium").children(value)
])
)
)
)
)
})
)
})
Anatomy
The parts the view closure receives. Apply each one to an element of your own.
| Part | Description |
|---|---|
trigger | The <button> or <a href> the tooltip describes. |
positioner | A <div>, a manual popover placed by the tooltip. sideOffset is its padding. |
popup | A <div> inside the positioner. |
arrow | A <div> inside the popup that points at the trigger. Optional. |
API reference
Props
| Prop | Type | Description |
|---|---|---|
open | boolean | Whether the tooltip shows. Required: the consumer owns it. |
disabled | boolean | The tooltip never shows and emits nothing. The trigger stays enabled. |
delay | number | Milliseconds the pointer rests on the trigger before it opens, 600 by default. |
closeDelay | number | Milliseconds after the pointer leaves before it closes, 0 by default. |
closeOnClick | boolean | Whether activating the trigger closes the tooltip, true by default. |
disableHoverablePopup | boolean | The pointer on the popup doesn't keep the tooltip open. |
describesTrigger | boolean | Makes the popup the trigger's accessible description. |
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. |
timeout (TooltipProvider) | number | Milliseconds after the last tooltip closes during which another opens at once, 400 by default. |
Events
| Event | Description |
|---|---|
RequestedOpen | After the hover delay, or when the trigger receives keyboard focus. |
RequestedClose | The pointer left, focus moved away, the trigger was activated, or Escape or a press outside. |
Data attributes
| Attribute | Description |
|---|---|
data-popup-open | On the trigger while the tooltip shows. |
data-open / data-closed | On the positioner, popup and arrow. |
data-side / data-align | On the positioner, popup and arrow: where the popup ended up. |
data-instant | On the popup and arrow: focus, dismiss or delay, for a change that should skip its transition. |
data-anchor-hidden | On the positioner while the trigger is scrolled out of view. |
--transform-origin | On the positioner: the point on the trigger the popup grows from. |
Related components
The components this page's file and examples import.
- Button: A native button that can stay focusable while disabled.