Tooltip
A popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.
Usage
Example
The tooltip opens while the pointer rests on the trigger or when the trigger gets keyboard focus. The pointer can move onto the tooltip; it closes when the pointer leaves both, on blur (unless the pointer is still over it), on Escape, or when the trigger is pressed. The trigger's button is described by the tooltip (aria-describedby).
Tooltip do
TooltipTrigger do
Button(variant: :outline) { "Show Tooltip" }
end
TooltipContent do
p { "Add to library" }
end
end
Sides
side: places the tooltip around the trigger: :top (the default), :right, :bottom, :left, or the logical :inline_start and :inline_end, which follow the writing direction. side_offset: is the gap in pixels (4 by default); align: (:start, :center, :end) and align_offset: line it up along that edge. It flips to the other side when there is no room.
div(class: "flex flex-wrap gap-2") do
[:inline_start, :left, :top, :bottom, :right, :inline_end].each do |side|
Tooltip do
TooltipTrigger do
Button(variant: :outline, class: "capitalize") { side.to_s.tr("_", " ") }
end
TooltipContent(side: side) do
p { "Add to library" }
end
end
end
end
With icon
An icon-only trigger still needs an accessible name: the tooltip describes the button, it doesn't name it.
Tooltip do
TooltipTrigger do
Button(variant: :ghost, icon: true) do
bookmark_icon
span(class: "sr-only") { "Bookmark" }
end
end
TooltipContent do
p { "Add to library" }
end
end
Long content
Long text wraps at 20rem.
Tooltip do
TooltipTrigger do
Button(variant: :outline) { "Show Tooltip" }
end
TooltipContent do
plain "To learn more about how this works, check out the docs. If you have any questions, please reach out to us."
end
end
With keyboard shortcut
Tooltip do
TooltipTrigger do
Button(variant: :outline, size: :sm) { "Save" }
end
TooltipContent do
plain "Save Changes"
ShortcutKey { "S" }
end
end
Delay and click
delay: waits that many milliseconds of pointer rest before opening (0 by default), close_delay: waits before closing (0 by default, plus a 100 ms grace to cross onto the tooltip). close_on_click: false keeps it open when the trigger is pressed.
Tooltip do
TooltipTrigger(delay: 500, close_on_click: false) do
Button(variant: :outline) { "Hover and wait" }
end
TooltipContent do
p { "Opened after 500 ms" }
end
end
Disabled tooltip
disabled: true keeps the tooltip from opening. open: true renders it open on load. Changing the data-ruby-ui--tooltip-open-value or -disabled-value attribute later opens, closes or disables it, and each open or close dispatches ruby-ui--tooltip:change with detail.open.
Tooltip(disabled: true) do
TooltipTrigger do
Button(variant: :outline) { "No tooltip" }
end
TooltipContent do
p { "You won't see this" }
end
end
Installation
Using RubyUI CLI
Run the install command
rails g ruby_ui:component Tooltip
Manual installation
1
Add RubyUI::Tooltip to app/components/ruby_ui/tooltip/tooltip.rb
# frozen_string_literal: true
module RubyUI
# Root of the tooltip: scopes the trigger and the content for the Stimulus
# controller. open: renders it open on load (Base UI's defaultOpen) and
# disabled: keeps it from opening (Base UI's Root disabled). Setting the
# data-ruby-ui--tooltip-open-value or -disabled-value attribute later
# opens, closes or disables it; each open or close dispatches
# ruby-ui--tooltip:change with detail {open:}.
#
# placement: is the older API: TooltipContent's side: wins over it.
class Tooltip < Base
def initialize(placement: nil, open: false, disabled: false, **attrs)
@placement = placement
@open = open
@disabled = disabled
super(**attrs)
end
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
data: {
slot: "tooltip",
controller: "ruby-ui--tooltip",
ruby_ui__tooltip_placement_value: @placement&.to_s,
ruby_ui__tooltip_open_value: (!!@open).to_s,
ruby_ui__tooltip_disabled_value: (!!@disabled).to_s
},
class: "group"
}
end
end
end
2
Add RubyUI::TooltipContent to app/components/ruby_ui/tooltip/tooltip_content.rb
# frozen_string_literal: true
module RubyUI
# The popup, kept in a <template> until the controller connects. The
# controller places the copy right after the trigger, so it stays inside
# the same container (a Sidebar hides its own tooltips from its state), and
# opens it as a native popover="manual" in the top layer, where no ancestor
# with overflow: hidden clips it. role="tooltip"; the trigger's focusable
# element points at it with aria-describedby.
#
# side:/align: pick the placement (side also takes the logical
# :inline_start / :inline_end), side_offset:/align_offset: the gap, with the
# defaults of shadcn's TooltipContent. Without side:, Tooltip's placement:
# applies, then top. It flips to the other side when there is no room.
class TooltipContent < Base
SIDES = %i[top right bottom left inline_start inline_end].freeze
ALIGNS = %i[start center end].freeze
def initialize(side: nil, side_offset: 4, align: nil, align_offset: 0, **attrs)
@id = "tooltip-#{SecureRandom.hex(4)}"
@side = SIDES.include?(side&.to_sym) ? side.to_s.tr("_", "-") : nil
@align = ALIGNS.include?(align&.to_sym) ? align.to_s : nil
@side_offset = side_offset
@align_offset = align_offset
super(**attrs)
end
def view_template(&block)
template(data: {ruby_ui__tooltip_target: "content"}) do
div(**attrs) do
yield if block
span(**arrow_attrs)
end
end
end
private
def arrow_attrs
{
aria: {hidden: "true"},
data: {slot: "tooltip-arrow"},
class: [
"absolute z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground",
"data-[side=bottom]:top-1 data-[side=top]:-bottom-2.5",
"data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2",
# The controller writes the physical side, so logical sides point right in RTL too.
"data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2"
]
}
end
def default_attrs
{
id: @id,
popover: "manual",
role: "tooltip",
data: {
slot: "tooltip-content",
# Kept in sync with data-open/data-closed for CSS that targets data-[state=...].
state: "closed",
closed: "",
preferred_side: @side,
preferred_align: @align,
side_offset: @side_offset,
align_offset: @align_offset
},
class: [
# Resets the UA popover box (overflow too, or it clips the arrow);
# inline-flex must not beat the UA's hidden closed popover.
"fixed inset-auto m-0 border-0 overflow-visible [&:not(:popover-open)]:hidden",
"z-50 w-fit max-w-xs origin-(--transform-origin) bg-foreground text-background",
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs",
"has-data-[slot=kbd]:pr-1.5 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm",
"data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95",
"data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-closed:fill-mode-forwards",
"data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2",
"data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
"data-[side=inline-start]:slide-in-from-right-2 data-[side=inline-end]:slide-in-from-left-2"
]
}
end
end
end
3
Add RubyUI::TooltipDocs to app/components/ruby_ui/tooltip/tooltip_docs.rb
# frozen_string_literal: true
class Views::Docs::Tooltip < Views::Base
def view_template
component = "Tooltip"
div(class: "max-w-2xl mx-auto w-full py-10 space-y-10") do
render Docs::Header.new(title: "Tooltip", description: "A popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.")
Heading(level: 2) { "Usage" }
render Docs::VisualCodeExample.new(title: "Example", description: "The tooltip opens while the pointer rests on the trigger or when the trigger gets keyboard focus. The pointer can move onto the tooltip; it closes when the pointer leaves both, on blur (unless the pointer is still over it), on Escape, or when the trigger is pressed. The trigger's button is described by the tooltip (aria-describedby).", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger do
Button(variant: :outline) { "Show Tooltip" }
end
TooltipContent do
p { "Add to library" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Sides", description: "side: places the tooltip around the trigger: :top (the default), :right, :bottom, :left, or the logical :inline_start and :inline_end, which follow the writing direction. side_offset: is the gap in pixels (4 by default); align: (:start, :center, :end) and align_offset: line it up along that edge. It flips to the other side when there is no room.", context: self) do
<<~RUBY
div(class: "flex flex-wrap gap-2") do
[:inline_start, :left, :top, :bottom, :right, :inline_end].each do |side|
Tooltip do
TooltipTrigger do
Button(variant: :outline, class: "capitalize") { side.to_s.tr("_", " ") }
end
TooltipContent(side: side) do
p { "Add to library" }
end
end
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With icon", description: "An icon-only trigger still needs an accessible name: the tooltip describes the button, it doesn't name it.", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger do
Button(variant: :ghost, icon: true) do
bookmark_icon
span(class: "sr-only") { "Bookmark" }
end
end
TooltipContent do
p { "Add to library" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Long content", description: "Long text wraps at 20rem.", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger do
Button(variant: :outline) { "Show Tooltip" }
end
TooltipContent do
plain "To learn more about how this works, check out the docs. If you have any questions, please reach out to us."
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled button", description: "A disabled button gets no pointer events, so the wrapper still opens the tooltip on hover.", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger do
Button(variant: :outline, disabled: true) { "Disabled" }
end
TooltipContent do
p { "This feature is currently unavailable" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "With keyboard shortcut", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger do
Button(variant: :outline, size: :sm) { "Save" }
end
TooltipContent do
plain "Save Changes"
ShortcutKey { "S" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Delay and click", description: "delay: waits that many milliseconds of pointer rest before opening (0 by default), close_delay: waits before closing (0 by default, plus a 100 ms grace to cross onto the tooltip). close_on_click: false keeps it open when the trigger is pressed.", context: self) do
<<~RUBY
Tooltip do
TooltipTrigger(delay: 500, close_on_click: false) do
Button(variant: :outline) { "Hover and wait" }
end
TooltipContent do
p { "Opened after 500 ms" }
end
end
RUBY
end
render Docs::VisualCodeExample.new(title: "Disabled tooltip", description: "disabled: true keeps the tooltip from opening. open: true renders it open on load. Changing the data-ruby-ui--tooltip-open-value or -disabled-value attribute later opens, closes or disables it, and each open or close dispatches ruby-ui--tooltip:change with detail.open.", context: self) do
<<~RUBY
Tooltip(disabled: true) do
TooltipTrigger do
Button(variant: :outline) { "No tooltip" }
end
TooltipContent do
p { "You won't see this" }
end
end
RUBY
end
render Components::ComponentSetup::Tabs.new(component_name: component)
render Docs::ComponentsTable.new(component_files(component))
end
end
private
def bookmark_icon
svg(
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewbox: "0 0 24 24",
stroke_width: "1.5",
stroke: "currentColor",
class: "w-4 h-4"
) do |s|
s.path(
stroke_linecap: "round",
stroke_linejoin: "round",
d:
"M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0111.186 0z"
)
end
end
end
4
Add RubyUI::TooltipTrigger to app/components/ruby_ui/tooltip/tooltip_trigger.rb
# frozen_string_literal: true
module RubyUI
# Wraps the element that shows the tooltip (usually a Button). The tooltip
# opens while the pointer rests on it for delay: ms, or when it gets
# keyboard focus, and closes close_delay: ms after the pointer leaves both
# the trigger and the content (plus a short grace to cross the gap), on
# blur (unless the pointer is still over it) or on Escape. close_on_click: closes it when the trigger is pressed.
# Defaults follow shadcn's TooltipProvider (delay 0) and Base UI's Trigger.
class TooltipTrigger < Base
def initialize(delay: 0, close_delay: 0, close_on_click: true, **attrs)
@delay = delay
@close_delay = close_delay
@close_on_click = close_on_click
super(**attrs)
end
def view_template(&)
div(**attrs, &)
end
private
def default_attrs
{
data: {
slot: "tooltip-trigger",
ruby_ui__tooltip_target: "trigger",
delay: @delay,
close_delay: @close_delay,
close_on_click: @close_on_click.to_s
},
# Shrinks to the button, so the hit area and the anchor are the button.
class: "inline-flex w-fit"
}
end
end
end
5
Add tooltip_controller.js to app/javascript/controllers/ruby_ui/tooltip_controller.js
import { Controller } from "@hotwired/stimulus";
import { computePosition, autoUpdate, offset, flip, shift, arrow } from "@floating-ui/dom";
// Connects to data-controller="ruby-ui--tooltip"
//
// Behaves like Base UI's Tooltip: it opens while the pointer rests on the
// trigger (after delay) or when the trigger gets keyboard focus, and closes
// when the pointer leaves both the trigger and the content, on blur, on
// Escape, or when the trigger is pressed (close_on_click). The pointer can
// move onto the content without closing it (WCAG 1.4.13).
//
// TooltipContent ships in a <template>. On connect the controller places a
// copy right after the trigger, so it stays inside the same container (a
// Sidebar hides its tooltips from its own data-state), and opens it as a
// native popover="manual" in the top layer; Floating UI places it next to
// the trigger. The content has role="tooltip" and the trigger's focusable
// element points at it with aria-describedby, as the APG tooltip pattern
// asks (Base UI leaves both out).
const SIDES = ["top", "right", "bottom", "left", "inline-start", "inline-end"];
const ALIGNS = ["start", "center", "end"];
const FOCUSABLE = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
// The pointer needs a moment to cross the gap between trigger and content.
const HOVER_GRACE = 100;
export default class extends Controller {
static targets = ["trigger", "content"];
static values = {
placement: { type: String, default: "top" },
open: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
};
// The copy of the content template that lives in the page.
popup = null;
isOpen = false;
connect() {
document.addEventListener("turbo:before-cache", this.handleBeforeCache);
this.mount();
if (this.openValue && !this.disabledValue) this.open();
this.ready = true;
}
disconnect() {
this.ready = false;
document.removeEventListener("turbo:before-cache", this.handleBeforeCache);
this.unmount();
// Stimulus reuses this instance if the element comes back.
this.pointerInside = false;
this.pressedClosed = false;
}
// Target callbacks run before connect() and again whenever Turbo or other
// code swaps the trigger or the content inside a connected tooltip.
triggerTargetConnected(trigger) {
trigger.addEventListener("mouseenter", this.handleEnter);
trigger.addEventListener("mouseleave", this.handleLeave);
trigger.addEventListener("focusin", this.handleFocusIn);
trigger.addEventListener("focusout", this.handleFocusOut);
trigger.addEventListener("click", this.handleClick);
if (this.ready) this.remount();
}
triggerTargetDisconnected(trigger) {
trigger.removeEventListener("mouseenter", this.handleEnter);
trigger.removeEventListener("mouseleave", this.handleLeave);
trigger.removeEventListener("focusin", this.handleFocusIn);
trigger.removeEventListener("focusout", this.handleFocusOut);
trigger.removeEventListener("click", this.handleClick);
// The copy sits next to (and is placed against) this trigger.
if (this.popup && this.mountedTrigger === trigger) this.unmount();
}
contentTargetConnected() {
if (this.ready) this.remount();
}
contentTargetDisconnected(template) {
if (this.popup && this.mountedTemplate === template) this.unmount();
}
openValueChanged(open) {
if (!this.ready) return;
open ? this.open() : this.close();
}
disabledValueChanged(disabled) {
if (!this.ready) return;
// An open value set while disabled takes effect once enabled again.
if (disabled) {
this.close();
} else if (this.openValue) {
this.open();
}
}
// Kept for markup that still wires data-action to show/hide.
show() {
this.open();
}
hide() {
this.close();
}
// --- Mounting -----------------------------------------------------------------
mount() {
if (this.popup || !this.hasContentTarget || !this.hasTriggerTarget) return;
const template = this.contentTarget;
const trigger = this.triggerTarget;
const popup = template.content?.firstElementChild?.cloneNode(true);
if (!popup) return;
popup.addEventListener("mouseenter", this.handleEnter);
popup.addEventListener("mouseleave", this.handleLeave);
trigger.after(popup);
this.popup = popup;
this.mountedTrigger = trigger;
this.mountedTemplate = template;
this.describe(trigger, popup);
}
unmount() {
const popup = this.popup;
if (!popup) return;
this.close({ animate: false });
popup.removeEventListener("mouseenter", this.handleEnter);
popup.removeEventListener("mouseleave", this.handleLeave);
this.undescribe();
popup.remove();
this.popup = null;
this.mountedTrigger = null;
this.mountedTemplate = null;
}
// A swapped trigger or content while open stays open, without telling
// listeners about a close and reopen that never happened.
remount() {
const wasOpen = this.isOpen;
this.remounting = wasOpen;
try {
this.unmount();
this.mount();
if (wasOpen) this.open();
} finally {
this.remounting = false;
}
}
// --- aria-describedby ---------------------------------------------------------
// The element inside the trigger that receives focus (the Button), else the wrapper.
controlFor(trigger) {
return trigger.matches(FOCUSABLE) ? trigger : trigger.querySelector(FOCUSABLE) || trigger;
}
// Adds the content's id to the control's aria-describedby, keeping a
// caller's own ids. Skipped when the tooltip only repeats the control's
// text (SidebarMenuButton's label): the description would say it twice.
describe(trigger, popup) {
const control = this.controlFor(trigger);
const text = (element) => element.textContent.replace(/\s+/g, " ").trim().toLowerCase();
if (text(popup) !== "" && text(popup) === text(control)) return;
const ids = (control.getAttribute("aria-describedby") || "").split(/\s+/).filter(Boolean);
if (!ids.includes(popup.id)) control.setAttribute("aria-describedby", [...ids, popup.id].join(" "));
this.describedControl = control;
}
undescribe() {
const control = this.describedControl;
this.describedControl = null;
if (!control || !this.popup) return;
const ids = (control.getAttribute("aria-describedby") || "").split(/\s+/).filter((id) => id && id !== this.popup.id);
ids.length ? control.setAttribute("aria-describedby", ids.join(" ")) : control.removeAttribute("aria-describedby");
}
// --- Pointer, focus, click, Escape --------------------------------------------
triggerSetting(key, fallback) {
const own = this.mountedTrigger?.dataset[key];
return own !== undefined && own !== "" ? own : fallback;
}
get openDelay() {
return Number(this.triggerSetting("delay", 0)) || 0;
}
get closeDelay() {
return Number(this.triggerSetting("closeDelay", 0)) || 0;
}
get closeOnClick() {
return this.triggerSetting("closeOnClick", "true") !== "false";
}
handleEnter = (event) => {
this.pointerInside = true;
this.clearTimers();
// After close_on_click, the pointer has to leave the trigger before it opens again.
if (this.isOpen || this.pressedClosed || this.disabledValue) return;
if (event.currentTarget === this.popup) return;
const delay = this.openDelay;
if (delay > 0) {
this.openTimeout = setTimeout(() => this.open(), delay);
} else {
this.open();
}
};
handleLeave = (event) => {
this.pointerInside = false;
if (event.currentTarget === this.mountedTrigger) this.pressedClosed = false;
this.clearTimers();
if (!this.isOpen || this.keyboardFocusInside()) return;
this.closeTimeout = setTimeout(() => this.close(), this.closeDelay + HOVER_GRACE);
};
// Opens on keyboard focus only, as Base UI does: a click focuses the button too.
handleFocusIn = (event) => {
if (this.disabledValue || this.isOpen || !this.isFocusVisible(event.target)) return;
this.clearTimers();
this.open();
};
handleFocusOut = (event) => {
if (this.mountedTrigger?.contains(event.relatedTarget)) return;
if (this.pointerInside) return;
this.close();
};
// Enter and Space on the trigger's button arrive here as a click too. A
// press during the open delay cancels the pending open as well.
handleClick = () => {
if (!this.closeOnClick) return;
this.clearTimers();
this.pressedClosed = this.pointerInside;
this.close();
};
handleKeydown = (event) => {
if (event.key !== "Escape" || !this.isOpen) return;
// A tooltip hidden by CSS (an expanded or mobile sidebar) closes without
// taking the key, so an enclosing Sheet or dialog still gets it.
// A visible one keeps an enclosing <dialog> from closing on the same key.
if (this.isRendered(this.popup)) event.preventDefault();
this.close();
};
handleBeforeCache = () => {
// The snapshot keeps the <template>; connect() places a fresh copy on restore.
this.unmount();
};
isRendered(element) {
return Boolean(element?.isConnected && element.getClientRects().length > 0);
}
keyboardFocusInside() {
const active = document.activeElement;
return Boolean(active && this.mountedTrigger?.contains(active) && this.isFocusVisible(active));
}
isFocusVisible(element) {
try {
return element.matches(":focus-visible");
} catch {
return true;
}
}
clearTimers() {
clearTimeout(this.openTimeout);
clearTimeout(this.closeTimeout);
}
// --- Opening and closing ------------------------------------------------------
open() {
if (this.isOpen || this.disabledValue) return;
this.mount();
const popup = this.popup;
if (!popup || !popup.isConnected) return;
this.clearTimers();
this.isOpen = true;
// Side and origin before the enter animation starts; position() refines both.
const { side, align } = this.preferredPlacement(popup);
popup.dataset.side = side;
popup.dataset.align = align;
popup.removeAttribute("data-closed");
popup.setAttribute("data-open", "");
popup.dataset.state = "open";
if (!popup.matches(":popover-open")) popup.showPopover();
document.addEventListener("keydown", this.handleKeydown);
this.startPositioning();
this.setOpenValue(true);
}
close({ animate = true } = {}) {
this.clearTimers();
if (!this.isOpen) return;
const popup = this.popup;
this.isOpen = false;
document.removeEventListener("keydown", this.handleKeydown);
this.stopPositioning();
popup.removeAttribute("data-open");
popup.setAttribute("data-closed", "");
popup.dataset.state = "closed";
animate ? this.hideAfterExitAnimation(popup) : this.settleExit(popup);
this.setOpenValue(false);
}
// Mirrors the state on the open value (so openValueChanged sees no change)
// and tells listeners, as Base UI's onOpenChange does.
setOpenValue(open) {
if (this.remounting) return;
if (this.openValue !== open) this.openValue = open;
this.dispatch("change", { detail: { open } });
}
// --- Positioning --------------------------------------------------------------
// TooltipContent side:/align:, else Tooltip placement:, else top/center.
preferredPlacement(popup) {
// Logical sides keep their hyphen: "inline-start" is a side, not side-align.
const placement = String(this.placementValue || "");
const [placementSide, placementAlign] = placement.startsWith("inline-") ? [placement] : placement.split("-");
const side = [popup.dataset.preferredSide, placementSide].find((value) => SIDES.includes(value)) || "top";
const align = popup.dataset.preferredSide
? popup.dataset.preferredAlign || "center"
: [popup.dataset.preferredAlign, placementAlign].find((value) => ALIGNS.includes(value)) || "center";
return { side, align };
}
// inline-start / inline-end follow the trigger's writing direction.
physicalSide(side, trigger) {
if (!side.startsWith("inline-")) return side;
const rtl = getComputedStyle(trigger).direction === "rtl";
return (side === "inline-start") !== rtl ? "left" : "right";
}
startPositioning() {
this.stopPositioning();
const trigger = this.mountedTrigger;
const popup = this.popup;
const anchor = this.controlFor(trigger);
this.cleanup = autoUpdate(anchor, popup, () => this.position(anchor, popup));
}
stopPositioning() {
if (this.cleanup) this.cleanup();
this.cleanup = null;
}
position(anchor, popup) {
const { side, align } = this.preferredPlacement(popup);
const physical = this.physicalSide(side, anchor);
const placement = align === "center" ? physical : `${physical}-${align}`;
const sideOffset = Number(popup.dataset.sideOffset ?? 4);
const alignOffset = Number(popup.dataset.alignOffset ?? 0);
const arrowElement = popup.querySelector('[data-slot="tooltip-arrow"]');
const middleware = [
// crossAxis shifts a centered tooltip; alignmentAxis takes over for
// :start / :end and flips the offset for :end, as Base UI does.
offset({ mainAxis: sideOffset, crossAxis: alignOffset, alignmentAxis: alignOffset }),
flip(),
shift({ padding: 5 }),
];
if (arrowElement) middleware.push(arrow({ element: arrowElement, padding: 5 }));
computePosition(anchor, popup, { strategy: "fixed", placement, middleware }).then(
({ x, y, placement: resolved, middlewareData }) => {
if (!popup.isConnected || popup !== this.popup || !this.isOpen) return;
const [resolvedSide, resolvedAlign = "center"] = resolved.split("-");
Object.assign(popup.style, { left: `${x}px`, top: `${y}px` });
// A logical side keeps its logical name, flipped to the other one if Floating UI flipped.
const finalSide = side.startsWith("inline-")
? resolvedSide === physical ? side : side === "inline-start" ? "inline-end" : "inline-start"
: resolvedSide;
popup.dataset.side = finalSide;
popup.dataset.align = resolvedAlign;
if (arrowElement) this.placeArrow(arrowElement, resolvedSide, resolvedAlign, middlewareData.arrow);
popup.style.setProperty("--transform-origin", this.transformOrigin(anchor, popup, resolvedSide, x, y, sideOffset));
},
);
}
// Along the trigger for top/bottom; the classes center it for left/right.
// The arrow takes the physical side, so a logical side points the right
// way in RTL too.
placeArrow(arrowElement, physical, align, data = {}) {
arrowElement.dataset.side = physical;
arrowElement.dataset.align = align;
const vertical = physical === "top" || physical === "bottom";
arrowElement.style.left = vertical && data.x != null ? `${data.x}px` : "";
arrowElement.style.top = !vertical && data.y != null ? `${data.y}px` : "";
}
// The content grows out of the trigger: the origin sits on the trigger's
// center line, at the gap between the two (Base UI's --transform-origin).
transformOrigin(anchor, popup, side, x, y, sideOffset) {
const rect = anchor.getBoundingClientRect();
const { width, height } = popup.getBoundingClientRect();
const centerX = rect.left + rect.width / 2 - x;
const centerY = rect.top + rect.height / 2 - y;
switch (side) {
case "top":
return `${centerX}px ${height + sideOffset}px`;
case "left":
return `${width + sideOffset}px ${centerY}px`;
case "right":
return `${-sideOffset}px ${centerY}px`;
default:
return `${centerX}px ${-sideOffset}px`;
}
}
// --- Exit animation (same block as the other overlay controllers) ------------
exitAnimationNames = new WeakMap();
hideAfterExitAnimation(animated) {
const exitAnimations = animated.getAnimations().filter((animation) => animation instanceof CSSAnimation);
// No exit animation, or no box to run it in (hidden by CSS): animationend would never fire.
if (exitAnimations.length === 0) {
this.settleExit(animated);
return;
}
this.exitAnimationNames.set(animated, exitAnimations.map((animation) => animation.animationName));
animated.addEventListener("animationend", this.handleExitAnimationEnd);
animated.addEventListener("animationcancel", this.handleExitAnimationEnd);
}
handleExitAnimationEnd = (event) => {
// animationend bubbles — an animated child must not hide its container.
if (event.target !== event.currentTarget) return;
// Closing mid-open cancels the enter animation; only the exit run settles this.
if (!this.exitAnimationNames.get(event.currentTarget)?.includes(event.animationName)) return;
this.settleExit(event.currentTarget);
};
settleExit(animated) {
animated.removeEventListener("animationend", this.handleExitAnimationEnd);
animated.removeEventListener("animationcancel", this.handleExitAnimationEnd);
// Reopened mid-exit: it is on its way back in, leave it showing.
if (animated.hasAttribute("data-open")) return;
animated.setAttribute("data-closed", "");
animated.dataset.state = "closed";
if (animated.matches(":popover-open")) animated.hidePopover();
}
}
6
Update the Stimulus controllers manifest file
rake stimulus:manifest:update7
Install @floating-ui/dom Javascript dependency
// with yarn
yarn add @floating-ui/dom
// with npm
npm install @floating-ui/dom
// with importmaps
bin/importmap pin @floating-ui/dom
8
Install required components
Component Tooltip relies on the following RubyUI components. Refer to their individual installation guides for setup instructions:
Components
| Component | Built using | Source |
|---|---|---|
Tooltip | Phlex | |
TooltipContent | Phlex | |
TooltipDocs | Phlex | |
TooltipTrigger | Phlex | |
TooltipController | Stimulus JS |