Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(ui): unify accessible tooltips (#1526)

Bingxi Zhao (Frank)ee24f44fa732
diff --git a/web/app/globals.css b/web/app/globals.css
index 7b19f81a1..77725a1a3 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -1118,41 +1118,6 @@ a[href^="#dt-locator-"]:hover {
cursor: pointer;
}
-/* Sidebar tooltip */
-.dt-tooltip-wrapper {
- @apply relative inline-flex;
-}
-
-.dt-tooltip-content {
- @apply absolute z-50 rounded-lg bg-[var(--popover)] px-3 py-1.5 text-xs shadow-md text-[var(--popover-foreground)] pointer-events-none;
- animation: dt-tooltip-fade-in 150ms ease-out;
-}
-
-.dt-tooltip-label {
- @apply font-medium truncate;
-}
-
-.dt-tooltip-desc {
- @apply mt-0.5 text-[11px] text-[var(--muted-foreground)] truncate;
-}
-
-.dt-tooltip-content[data-side="right"] {
- @apply left-full top-1/2 -translate-y-1/2 ml-2 max-w-[200px];
-}
-
-.dt-tooltip-content[data-side="bottom"] {
- @apply bottom-[-40px] left-1/2 -translate-x-1/2 max-w-[180px];
-}
-
-@keyframes dt-tooltip-fade-in {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
-}
-
/* ─── Reduced motion ──────────────────────────────────────────────────────
Honor the OS-level prefers-reduced-motion setting. We don't strip motion
entirely — interaction-critical transitions (drawer slide, menu reveal)
diff --git a/web/components/common/Tooltip.tsx b/web/components/common/Tooltip.tsx
deleted file mode 100644
index 7648bbb20..000000000
--- a/web/components/common/Tooltip.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-"use client";
-
-import type { ReactNode } from "react";
-
-/**
- * Instant CSS tooltip — replaces the native `title` attribute, whose
- * ~1s OS-controlled hover delay makes icon-only buttons feel
- * unresponsive. Fades in after a ~150ms hover-intent delay and also
- * shows on keyboard focus. Pure CSS (group-hover, no portal), so
- * callers should avoid mounting it flush against an overflow-hidden
- * edge where the label would clip.
- */
-export default function Tooltip({
- label,
- side = "bottom",
- suppressed = false,
- children,
-}: {
- label: string;
- /** Which side of the trigger the label appears on. */
- side?: "top" | "bottom";
- /**
- * Hide the label while keeping the trigger mounted. Set this when the
- * trigger has opened something of its own (a menu, a popover): the pointer
- * is still over the button, so the tooltip would otherwise sit on top of
- * the very surface it just opened.
- */
- suppressed?: boolean;
- children: ReactNode;
-}) {
- const place = side === "bottom" ? "top-full mt-1.5" : "bottom-full mb-1.5";
- return (
- <span className="group/tip relative inline-flex">
- {children}
- {suppressed ? null : (
- <span
- role="tooltip"
- aria-hidden
- className={`pointer-events-none absolute left-1/2 z-[80] -translate-x-1/2 ${place} whitespace-nowrap rounded-md bg-[var(--foreground)] px-2 py-1 text-[11px] font-medium leading-none text-[var(--background)] opacity-0 shadow-md transition-opacity duration-100 group-focus-within/tip:opacity-100 group-hover/tip:opacity-100 group-hover/tip:delay-150`}
- >
- {label}
- </span>
- )}
- </span>
- );
-}
diff --git a/web/components/mcp/McpServerRow.tsx b/web/components/mcp/McpServerRow.tsx
index 9db0a65d0..bfe8c1920 100644
--- a/web/components/mcp/McpServerRow.tsx
+++ b/web/components/mcp/McpServerRow.tsx
@@ -10,6 +10,7 @@ import {
Trash2,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import Tooltip from "@/shared/ui/Tooltip";
import { BrandGlyph } from "@/components/common/BrandIcon";
import { brandIconFor } from "@/lib/brand-icons";
@@ -113,15 +114,16 @@ export default function McpServerRow({
{secretFields && secretFields.length > 0 && (
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
{secretFields.map((field) => (
- <span
+ <Tooltip
key={field}
- title={t("Stored on the server and never shown here.")}
- className="inline-flex items-center gap-1 rounded-full border border-[var(--border)]/60 bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]"
+ label={t("Stored on the server and never shown here.")}
>
- <KeyRound className="h-2.5 w-2.5" />
- <span className="font-mono">{field}</span>
- <span className="opacity-70">{t("configured")}</span>
- </span>
+ <span className="inline-flex items-center gap-1 rounded-full border border-[var(--border)]/60 bg-[var(--muted)]/40 px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
+ <KeyRound className="h-2.5 w-2.5" />
+ <span className="font-mono">{field}</span>
+ <span className="opacity-70">{t("configured")}</span>
+ </span>
+ </Tooltip>
))}
</div>
)}
@@ -188,26 +190,27 @@ function Toggle({
label: string;
}) {
return (
- <button
- type="button"
- role="switch"
- aria-checked={checked}
- aria-label={label}
- title={label}
- disabled={disabled}
- onClick={onChange}
- className={`relative inline-flex h-[18px] w-[32px] shrink-0 items-center rounded-full border transition-colors ${
- checked
- ? "border-[var(--primary)] bg-[var(--primary)]/70"
- : "border-[var(--border)] bg-[var(--muted)]/50"
- } ${disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}
- >
- <span
- className={`inline-block h-[12px] w-[12px] transform rounded-full bg-white shadow transition-transform ${
- checked ? "translate-x-[16px]" : "translate-x-[2px]"
- }`}
- />
- </button>
+ <Tooltip label={label} side="bottom">
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ aria-label={label}
+ disabled={disabled}
+ onClick={onChange}
+ className={`relative inline-flex h-[18px] w-[32px] shrink-0 items-center rounded-full border transition-colors ${
+ checked
+ ? "border-[var(--primary)] bg-[var(--primary)]/70"
+ : "border-[var(--border)] bg-[var(--muted)]/50"
+ } ${disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer"}`}
+ >
+ <span
+ className={`inline-block h-[12px] w-[12px] transform rounded-full bg-white shadow transition-transform ${
+ checked ? "translate-x-[16px]" : "translate-x-[2px]"
+ }`}
+ />
+ </button>
+ </Tooltip>
);
}
@@ -225,17 +228,18 @@ function IconButton({
danger?: boolean;
}) {
return (
- <button
- type="button"
- onClick={onClick}
- disabled={disabled}
- aria-label={label}
- title={label}
- className={`rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] ${
- danger ? "hover:text-red-500" : "hover:text-[var(--foreground)]"
- } disabled:cursor-not-allowed disabled:opacity-60`}
- >
- {icon}
- </button>
+ <Tooltip label={label} side="bottom">
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={label}
+ className={`rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] ${
+ danger ? "hover:text-red-500" : "hover:text-[var(--foreground)]"
+ } disabled:cursor-not-allowed disabled:opacity-60`}
+ >
+ {icon}
+ </button>
+ </Tooltip>
);
}
diff --git a/web/components/memory/MemoryGraph.tsx b/web/components/memory/MemoryGraph.tsx
index d0be75610..06d90f021 100644
--- a/web/components/memory/MemoryGraph.tsx
+++ b/web/components/memory/MemoryGraph.tsx
@@ -24,6 +24,7 @@ import {
ZoomOut,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import Tooltip from "@/shared/ui/Tooltip";
import {
buildGraph,
@@ -862,14 +863,16 @@ function IconButton({
children: React.ReactNode;
}) {
return (
- <button
- type="button"
- onClick={onClick}
- title={title}
- className="grid h-8 w-8 place-items-center text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- >
- {children}
- </button>
+ <Tooltip label={title} side="bottom">
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={title}
+ className="grid h-8 w-8 place-items-center text-[var(--muted-foreground)] transition hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ >
+ {children}
+ </button>
+ </Tooltip>
);
}
diff --git a/web/components/notebook/NotebookConsole.tsx b/web/components/notebook/NotebookConsole.tsx
index 3e82bb08f..477c9eb63 100644
--- a/web/components/notebook/NotebookConsole.tsx
+++ b/web/components/notebook/NotebookConsole.tsx
@@ -18,7 +18,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
-import Tooltip from "@/components/common/Tooltip";
+import Tooltip from "@/shared/ui/Tooltip";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import NotebookRecordRow from "@/components/notebook/NotebookRecordRow";
import { useNotebookLibrary } from "@/components/notebook/useNotebookLibrary";
diff --git a/web/components/notebook/NotebookRecordActions.tsx b/web/components/notebook/NotebookRecordActions.tsx
index 561803609..65b3e187c 100644
--- a/web/components/notebook/NotebookRecordActions.tsx
+++ b/web/components/notebook/NotebookRecordActions.tsx
@@ -10,7 +10,7 @@ import {
Trash2,
} from "lucide-react";
import { useTranslation } from "react-i18next";
-import Tooltip from "@/components/common/Tooltip";
+import Tooltip from "@/shared/ui/Tooltip";
import type { NotebookSummary } from "@/lib/notebook-api";
type Panel = "root" | "move" | "copy";
diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsx
index bd98624c3..4a359d6a6 100644
--- a/web/components/reading/AnnotationPopover.tsx
+++ b/web/components/reading/AnnotationPopover.tsx
@@ -9,6 +9,7 @@ import {
Underline,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import Tooltip from "@/shared/ui/Tooltip";
import {
ANNOTATION_COLORS,
ANNOTATION_SWATCH,
@@ -105,20 +106,20 @@ export function AnnotationPopover({
<div className="flex items-center gap-1">
<div className="flex items-center gap-0.5 pr-1">
{ANNOTATION_COLORS.map((swatch) => (
- <button
- key={swatch}
- type="button"
- title={t(swatchLabel(swatch))}
- aria-label={t(swatchLabel(swatch))}
- aria-pressed={color === swatch}
- onClick={() => setColor(swatch)}
- className={`h-5 w-5 rounded-full border transition ${
- color === swatch
- ? "border-[var(--foreground)] scale-110"
- : "border-black/10 hover:scale-105"
- }`}
- style={{ background: ANNOTATION_SWATCH[swatch] }}
- />
+ <Tooltip key={swatch} label={t(swatchLabel(swatch))} side="top">
+ <button
+ type="button"
+ aria-label={t(swatchLabel(swatch))}
+ aria-pressed={color === swatch}
+ onClick={() => setColor(swatch)}
+ className={`h-5 w-5 rounded-full border transition ${
+ color === swatch
+ ? "border-[var(--foreground)] scale-110"
+ : "border-black/10 hover:scale-105"
+ }`}
+ style={{ background: ANNOTATION_SWATCH[swatch] }}
+ />
+ </Tooltip>
))}
</div>
<span className="h-5 w-px bg-[var(--border)]" aria-hidden />
@@ -203,19 +204,20 @@ function IconButton({
active?: boolean;
}) {
return (
- <button
- type="button"
- title={label}
- aria-label={label}
- onClick={onClick}
- className={`inline-flex h-7 w-7 items-center justify-center rounded-lg transition ${
- active
- ? "bg-[var(--muted)] text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
- }`}
- >
- <Icon size={14} />
- </button>
+ <Tooltip label={label} side="bottom">
+ <button
+ type="button"
+ aria-label={label}
+ onClick={onClick}
+ className={`inline-flex h-7 w-7 items-center justify-center rounded-lg transition ${
+ active
+ ? "bg-[var(--muted)] text-[var(--foreground)]"
+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Icon size={14} />
+ </button>
+ </Tooltip>
);
}
diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsx
index c0cccdb07..895ed90b6 100644
--- a/web/components/reading/workspace/ReadingCompanion.tsx
+++ b/web/components/reading/workspace/ReadingCompanion.tsx
@@ -43,7 +43,7 @@ import SessionViewerPanel, {
type SessionViewerPanelHandle,
} from "@/components/chat/home/SessionViewerPanel";
import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";
-import Tooltip from "@/components/common/Tooltip";
+import Tooltip from "@/shared/ui/Tooltip";
import {
type MessageAttachment,
useChatStateAdapter,
diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsx
index 8690a66ca..120177102 100644
--- a/web/components/settings/ServiceConfigEditor.tsx
+++ b/web/components/settings/ServiceConfigEditor.tsx
@@ -56,6 +56,7 @@ import {
SectionHead,
} from "./ModelCards";
import { nextProfileName } from "./profile-naming";
+import Tooltip from "@/shared/ui/Tooltip";
import { searchProviderFields } from "./search-providers";
import {
activeProfileDetail,
@@ -1023,20 +1024,20 @@ export function ServiceConfigEditor({
<span>
{t("Send dimensions")}
</span>
- <span
- tabIndex={0}
- className="group/info relative inline-flex cursor-help focus:outline-none"
+ <Tooltip
+ side="bottom"
+ label={t("Send dimensions")}
+ description={t(
+ "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
+ )}
>
- <Info className="h-3 w-3 opacity-50 transition-opacity group-hover/info:opacity-100 group-focus/info:opacity-100" />
<span
- role="tooltip"
- className="pointer-events-none absolute top-full left-1/2 z-20 mt-1.5 w-64 -translate-x-1/2 rounded-lg border border-[var(--border)] bg-[var(--card)] p-2.5 text-[11px] leading-relaxed text-[var(--foreground)] opacity-0 shadow-lg transition-opacity duration-75 group-hover/info:opacity-100 group-focus/info:opacity-100"
+ tabIndex={0}
+ className="inline-flex cursor-help focus:outline-none"
>
- {t(
- "Some embedding models (e.g. Qwen text-embedding-v4) reject the `dimensions` request param. Turn this off if your provider returns HTTP 400.",
- )}
+ <Info className="h-3 w-3 opacity-50 transition-opacity hover:opacity-100 focus:opacity-100" />
</span>
- </span>
+ </Tooltip>
</label>
</div>
<DimensionField
diff --git a/web/components/sidebar/SidebarNav.tsx b/web/components/sidebar/SidebarNav.tsx
index 83bab7cf9..667a35fc9 100644
--- a/web/components/sidebar/SidebarNav.tsx
+++ b/web/components/sidebar/SidebarNav.tsx
@@ -44,7 +44,7 @@ import {
PRIMARY_NAV_HREFS,
isNavActive,
} from "@/components/sidebar/nav-entries";
-import { Tooltip } from "@/components/ui/Tooltip";
+import { Tooltip } from "@/shared/ui/Tooltip";
import { useDragSort, type DragSort } from "@/hooks/useDragSort";
import { placeMenu, type FloatingMenuPosition } from "@/lib/floating-menu";
import {
diff --git a/web/components/ui/Tooltip.tsx b/web/components/ui/Tooltip.tsx
deleted file mode 100644
index 1140a3555..000000000
--- a/web/components/ui/Tooltip.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client";
-
-import {
- ReactNode,
- useState,
- useCallback,
- useEffect,
- useRef,
- useId,
-} from "react";
-
-interface TooltipProps {
- label: string;
- description?: string;
- children: ReactNode;
- side?: "right" | "bottom";
-}
-
-export function Tooltip({
- label,
- description,
- children,
- side = "right",
-}: TooltipProps) {
- const [visible, setVisible] = useState(false);
- const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- const tooltipId = useId();
-
- const showTooltip = useCallback(() => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- timeoutRef.current = setTimeout(() => setVisible(true), 300);
- }, []);
-
- const showNow = useCallback(() => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- setVisible(true);
- }, []);
-
- const hideTooltip = useCallback(() => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- setVisible(false);
- }, []);
-
- useEffect(() => {
- return () => {
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
- };
- }, []);
-
- return (
- <div
- className="dt-tooltip-wrapper"
- onMouseEnter={showTooltip}
- onMouseLeave={hideTooltip}
- onFocus={showNow}
- onBlur={hideTooltip}
- aria-describedby={visible ? tooltipId : undefined}
- >
- {children}
- {visible && (
- <div
- id={tooltipId}
- className="dt-tooltip-content"
- data-side={side}
- role="tooltip"
- >
- <div className="dt-tooltip-label">{label}</div>
- {description && <div className="dt-tooltip-desc">{description}</div>}
- </div>
- )}
- </div>
- );
-}
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index 36792e02d..9f9c0bec1 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -11,6 +11,32 @@ const config = [
rules: {
// During migration keep as warning; change to "error" once phase2/3 complete.
"i18n/no-literal-ui-text": "warn",
+ "no-restricted-imports": [
+ "error",
+ {
+ paths: [
+ {
+ name: "@/components/common/Tooltip",
+ message: "Import the canonical @/shared/ui/Tooltip primitive.",
+ },
+ {
+ name: "@/components/ui/Tooltip",
+ message: "Import the canonical @/shared/ui/Tooltip primitive.",
+ },
+ ],
+ },
+ ],
+ "no-restricted-syntax": [
+ "warn",
+ {
+ selector: "JSXAttribute[name.name='role'][value.value='tooltip']",
+ message: "Use @/shared/ui/Tooltip instead of a local tooltip implementation.",
+ },
+ {
+ selector: "FunctionDeclaration[id.name=/Icon(Button|Btn)$/] JSXOpeningElement[name.type='JSXIdentifier'][name.name=/^[a-z]/] > JSXAttribute[name.name='title']",
+ message: "Icon button hints must use @/shared/ui/Tooltip so they work on keyboard and touch.",
+ },
+ ],
},
},
{
diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsx
index 92a5ccddc..19de731d7 100644
--- a/web/features/chat/messages/ChatMessageList.tsx
+++ b/web/features/chat/messages/ChatMessageList.tsx
@@ -45,7 +45,7 @@ import {
InlineFileCardProvider,
mergeGeneratedFiles,
} from "@/components/common/InlineFileCard";
-import Tooltip from "@/components/common/Tooltip";
+import Tooltip from "@/shared/ui/Tooltip";
import type {
MessageAttachment,
MessageRequestSnapshot,
diff --git a/web/features/co-writer/components/CoWriterWorkspace.tsx b/web/features/co-writer/components/CoWriterWorkspace.tsx
index 6c4a46a56..a69b65783 100644
--- a/web/features/co-writer/components/CoWriterWorkspace.tsx
+++ b/web/features/co-writer/components/CoWriterWorkspace.tsx
@@ -74,6 +74,7 @@ import { useSynchronizedScroll } from "@/features/co-writer/hooks/useSynchronize
import { useDocumentLifecycle } from "@/features/co-writer/hooks/useDocumentLifecycle";
import type { NotebookSavePayload } from "@/components/notebook/SaveToNotebookModal";
import { CO_WRITER_SAMPLE_TEMPLATE } from "@/app/(workspace)/co-writer/sampleTemplate";
+import Tooltip from "@/shared/ui/Tooltip";
const MarkdownRenderer = dynamic(
() => import("@/components/common/MarkdownRenderer"),
@@ -2448,20 +2449,16 @@ function ToolbarIconBtn({
: "hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]";
return (
- <button
- type="button"
- aria-label={title}
- onClick={onClick}
- disabled={disabled}
- className={`group relative inline-flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/35 disabled:opacity-50 ${toneClass}`}
- >
- {children}
- <span
- role="tooltip"
- className="pointer-events-none absolute left-1/2 top-full z-30 mt-1.5 -translate-x-1/2 whitespace-nowrap rounded-md border border-[var(--border)] bg-[var(--card)] px-2 py-1 text-[10px] font-medium text-[var(--foreground)] opacity-0 shadow-lg transition-opacity delay-[120ms] duration-100 group-hover:opacity-100 group-focus-visible:opacity-100 group-focus-visible:delay-0"
+ <Tooltip label={title} side="bottom">
+ <button
+ type="button"
+ aria-label={title}
+ onClick={onClick}
+ disabled={disabled}
+ className={`inline-flex h-8 w-8 items-center justify-center rounded-lg text-[var(--muted-foreground)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/35 disabled:opacity-50 ${toneClass}`}
>
- {title}
- </span>
- </button>
+ {children}
+ </button>
+ </Tooltip>
);
}
diff --git a/web/shared/ui/IconButton.tsx b/web/shared/ui/IconButton.tsx
index cd7eb2d7b..a56606597 100644
--- a/web/shared/ui/IconButton.tsx
+++ b/web/shared/ui/IconButton.tsx
@@ -34,7 +34,7 @@ export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
ref,
) {
return (
- <Tooltip label={label} side={tooltipSide} disabled={props.disabled}>
+ <Tooltip label={label} side={tooltipSide}>
<button
ref={ref}
type={type}
diff --git a/web/shared/ui/Tooltip.tsx b/web/shared/ui/Tooltip.tsx
index b6f92b423..4abf9e331 100644
--- a/web/shared/ui/Tooltip.tsx
+++ b/web/shared/ui/Tooltip.tsx
@@ -3,6 +3,8 @@
import {
cloneElement,
isValidElement,
+ lazy,
+ Suspense,
useCallback,
useEffect,
useId,
@@ -10,84 +12,156 @@ import {
useState,
type ReactElement,
} from "react";
-import { cn } from "./styles";
+import type { TooltipSide } from "./tooltip-position";
+
+const loadTooltipLayer = () => import("./TooltipLayer");
+const TooltipLayer = lazy(loadTooltipLayer);
export interface TooltipProps {
label: string;
+ description?: string;
children: ReactElement<{ "aria-describedby"?: string }>;
- side?: "top" | "right" | "bottom" | "left";
+ side?: TooltipSide;
delay?: number;
- disabled?: boolean;
+ /** Suppress a tooltip while its trigger owns an open popover or menu. */
+ suppressed?: boolean;
}
-const positions = {
- top: "bottom-full left-1/2 mb-2 -translate-x-1/2",
- right: "left-full top-1/2 ml-2 -translate-y-1/2",
- bottom: "left-1/2 top-full mt-2 -translate-x-1/2",
- left: "right-full top-1/2 mr-2 -translate-y-1/2",
-};
-
export function Tooltip({
label,
+ description,
children,
side = "bottom",
delay = 180,
- disabled = false,
+ suppressed = false,
}: TooltipProps) {
const id = useId();
- const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const wrapperRef = useRef<HTMLSpanElement>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const hoverRef = useRef(false);
+ const keyboardFocusRef = useRef(false);
+ const pointerFocusRef = useRef(false);
+ const touchRef = useRef(false);
const [visible, setVisible] = useState(false);
+ const [layerMounted, setLayerMounted] = useState(false);
+ const renderedVisible = visible && !suppressed;
+ const markLayerMounted = useCallback(() => setLayerMounted(true), []);
- const clear = useCallback(() => {
- if (timer.current) clearTimeout(timer.current);
- timer.current = null;
+ const clearTimer = useCallback(() => {
+ if (timerRef.current) clearTimeout(timerRef.current);
+ timerRef.current = null;
}, []);
+ const hide = useCallback(() => {
+ clearTimer();
+ touchRef.current = false;
+ setVisible(false);
+ }, [clearTimer]);
const show = useCallback(
- (immediate = false) => {
- clear();
- if (disabled) return;
+ (immediate: boolean) => {
+ clearTimer();
+ if (suppressed) return;
+ void loadTooltipLayer();
if (immediate) setVisible(true);
- else timer.current = setTimeout(() => setVisible(true), delay);
+ else timerRef.current = setTimeout(() => setVisible(true), delay);
},
- [clear, delay, disabled],
+ [clearTimer, delay, suppressed],
);
- const hide = useCallback(() => {
- clear();
- setVisible(false);
- }, [clear]);
- useEffect(() => clear, [clear]);
+ useEffect(() => {
+ if (!suppressed) return;
+ const timeout = window.setTimeout(hide, 0);
+ return () => window.clearTimeout(timeout);
+ }, [hide, suppressed]);
+ useEffect(() => clearTimer, [clearTimer]);
+
+ useEffect(() => {
+ if (!renderedVisible) return;
+ const dismissTouch = (event: PointerEvent) => {
+ if (
+ touchRef.current &&
+ wrapperRef.current &&
+ !wrapperRef.current.contains(event.target as Node)
+ ) {
+ hide();
+ }
+ };
+ document.addEventListener("pointerdown", dismissTouch, true);
+ return () => document.removeEventListener("pointerdown", dismissTouch, true);
+ }, [hide, renderedVisible]);
if (!isValidElement(children)) return children;
+ const describedBy = [children.props["aria-describedby"], id]
+ .filter(Boolean)
+ .join(" ");
+ const tooltipText = description ? `${label}. ${description}` : label;
return (
<span
- className="relative inline-flex"
- onMouseEnter={() => show(false)}
- onMouseLeave={hide}
- onFocusCapture={() => show(true)}
- onBlurCapture={hide}
+ ref={wrapperRef}
+ className="inline-flex"
+ onPointerEnter={(event) => {
+ if (event.pointerType === "touch") return;
+ hoverRef.current = true;
+ show(false);
+ }}
+ onPointerLeave={(event) => {
+ if (event.pointerType === "touch") return;
+ hoverRef.current = false;
+ if (!keyboardFocusRef.current) hide();
+ }}
+ onPointerDown={(event) => {
+ pointerFocusRef.current = true;
+ if (event.pointerType !== "touch") return;
+ touchRef.current = true;
+ if (renderedVisible) hide();
+ else {
+ show(true);
+ timerRef.current = setTimeout(hide, 3000);
+ }
+ }}
+ onPointerUp={() => {
+ queueMicrotask(() => {
+ pointerFocusRef.current = false;
+ });
+ }}
+ onFocusCapture={() => {
+ if (pointerFocusRef.current) return;
+ keyboardFocusRef.current = true;
+ show(true);
+ }}
+ onBlurCapture={(event) => {
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ keyboardFocusRef.current = false;
+ if (!hoverRef.current) hide();
+ }}
onKeyDown={(event) => {
if (event.key === "Escape") hide();
}}
>
- {cloneElement(children, {
- "aria-describedby": visible ? id : children.props["aria-describedby"],
- })}
- {visible ? (
- <span
- id={id}
- role="tooltip"
- className={cn(
- "pointer-events-none absolute z-[90] max-w-64 whitespace-nowrap rounded-lg bg-foreground px-2.5 py-1.5 text-xs font-medium text-background shadow-lg",
- positions[side],
- )}
- >
- {label}
+ {cloneElement(children, { "aria-describedby": describedBy })}
+ {!renderedVisible || !layerMounted ? (
+ <span id={id} role="tooltip" className="sr-only">
+ {tooltipText}
</span>
) : null}
+ {renderedVisible && typeof document !== "undefined"
+ ? (
+ <Suspense fallback={null}>
+ <TooltipLayer
+ anchorRef={wrapperRef}
+ id={id}
+ label={label}
+ description={description}
+ side={side}
+ onMount={markLayerMounted}
+ />
+ </Suspense>
+ )
+ : null}
</span>
);
}
+export { placeTooltip, type TooltipSide } from "./tooltip-position";
+
export default Tooltip;
diff --git a/web/shared/ui/TooltipLayer.tsx b/web/shared/ui/TooltipLayer.tsx
new file mode 100644
index 000000000..9326bafc6
--- /dev/null
+++ b/web/shared/ui/TooltipLayer.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import {
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from "react";
+import { createPortal } from "react-dom";
+import {
+ placeTooltip,
+ type TooltipPosition,
+ type TooltipSide,
+} from "./tooltip-position";
+
+export default function TooltipLayer({
+ anchorRef,
+ id,
+ label,
+ description,
+ side,
+ onMount,
+}: {
+ anchorRef: RefObject<HTMLSpanElement | null>;
+ id: string;
+ label: string;
+ description?: string;
+ side: TooltipSide;
+ onMount: () => void;
+}) {
+ const tooltipRef = useRef<HTMLSpanElement>(null);
+ const [position, setPosition] = useState<TooltipPosition | null>(null);
+
+ useLayoutEffect(() => {
+ onMount();
+ const update = () => {
+ if (!anchorRef.current || !tooltipRef.current) return;
+ setPosition(
+ placeTooltip(
+ anchorRef.current.getBoundingClientRect(),
+ tooltipRef.current.getBoundingClientRect(),
+ side,
+ window.innerWidth,
+ window.innerHeight,
+ ),
+ );
+ };
+ update();
+ window.addEventListener("resize", update);
+ window.addEventListener("scroll", update, true);
+ return () => {
+ window.removeEventListener("resize", update);
+ window.removeEventListener("scroll", update, true);
+ };
+ }, [anchorRef, onMount, side]);
+
+ return createPortal(
+ <span
+ ref={tooltipRef}
+ id={id}
+ role="tooltip"
+ data-side={position?.side ?? side}
+ style={
+ position
+ ? { left: position.left, top: position.top }
+ : { left: 0, top: 0 }
+ }
+ className={`pointer-events-none fixed z-[1000] max-w-72 rounded-lg bg-[var(--foreground)] px-2.5 py-1.5 text-left text-[11px] font-medium leading-snug text-[var(--background)] shadow-lg [overflow-wrap:anywhere] ${position ? "opacity-100" : "opacity-0"}`}
+ >
+ <span className="block">{label}</span>
+ {description ? (
+ <span className="mt-0.5 block font-normal opacity-80">
+ {description}
+ </span>
+ ) : null}
+ </span>,
+ document.body,
+ );
+}
diff --git a/web/shared/ui/tooltip-position.ts b/web/shared/ui/tooltip-position.ts
new file mode 100644
index 000000000..1eeb1cec7
--- /dev/null
+++ b/web/shared/ui/tooltip-position.ts
@@ -0,0 +1,86 @@
+export type TooltipSide = "top" | "right" | "bottom" | "left";
+
+export interface TooltipPosition {
+ left: number;
+ top: number;
+ side: TooltipSide;
+}
+
+const GAP = 8;
+const VIEWPORT_MARGIN = 8;
+
+function opposite(side: TooltipSide): TooltipSide {
+ if (side === "top") return "bottom";
+ if (side === "bottom") return "top";
+ if (side === "left") return "right";
+ return "left";
+}
+
+function coordinates(
+ anchor: DOMRect,
+ tooltip: DOMRect,
+ side: TooltipSide,
+): { left: number; top: number } {
+ if (side === "top") {
+ return {
+ left: anchor.left + (anchor.width - tooltip.width) / 2,
+ top: anchor.top - tooltip.height - GAP,
+ };
+ }
+ if (side === "bottom") {
+ return {
+ left: anchor.left + (anchor.width - tooltip.width) / 2,
+ top: anchor.bottom + GAP,
+ };
+ }
+ if (side === "left") {
+ return {
+ left: anchor.left - tooltip.width - GAP,
+ top: anchor.top + (anchor.height - tooltip.height) / 2,
+ };
+ }
+ return {
+ left: anchor.right + GAP,
+ top: anchor.top + (anchor.height - tooltip.height) / 2,
+ };
+}
+
+export function placeTooltip(
+ anchor: DOMRect,
+ tooltip: DOMRect,
+ preferred: TooltipSide,
+ viewportWidth: number,
+ viewportHeight: number,
+): TooltipPosition {
+ let side = preferred;
+ let point = coordinates(anchor, tooltip, side);
+ const overflowsPreferred =
+ (side === "top" && point.top < VIEWPORT_MARGIN) ||
+ (side === "bottom" && point.top + tooltip.height > viewportHeight - VIEWPORT_MARGIN) ||
+ (side === "left" && point.left < VIEWPORT_MARGIN) ||
+ (side === "right" && point.left + tooltip.width > viewportWidth - VIEWPORT_MARGIN);
+ if (overflowsPreferred) {
+ const flipped = opposite(side);
+ const flippedPoint = coordinates(anchor, tooltip, flipped);
+ const flippedFits =
+ flippedPoint.left >= VIEWPORT_MARGIN &&
+ flippedPoint.top >= VIEWPORT_MARGIN &&
+ flippedPoint.left + tooltip.width <= viewportWidth - VIEWPORT_MARGIN &&
+ flippedPoint.top + tooltip.height <= viewportHeight - VIEWPORT_MARGIN;
+ if (flippedFits) {
+ side = flipped;
+ point = flippedPoint;
+ }
+ }
+ return {
+ side,
+ left: Math.min(
+ Math.max(point.left, VIEWPORT_MARGIN),
+ Math.max(VIEWPORT_MARGIN, viewportWidth - tooltip.width - VIEWPORT_MARGIN),
+ ),
+ top: Math.min(
+ Math.max(point.top, VIEWPORT_MARGIN),
+ Math.max(VIEWPORT_MARGIN, viewportHeight - tooltip.height - VIEWPORT_MARGIN),
+ ),
+ };
+}
diff --git a/web/tests/architecture-contracts.test.ts b/web/tests/architecture-contracts.test.ts
index 3e5891ea1..c82653826 100644
--- a/web/tests/architecture-contracts.test.ts
+++ b/web/tests/architecture-contracts.test.ts
@@ -65,6 +65,31 @@ test("source modules cannot import Next route pages", () => {
assert.deepEqual(violations, []);
});
+test("the canonical tooltip owns every tooltip role and guards import paths", () => {
+ const roleOwners = allSources
+ .filter((file) => /role=["']tooltip["']/.test(fs.readFileSync(file, "utf8")))
+ .map((file) => path.relative(root, file));
+ assert.deepEqual(roleOwners.sort(), [
+ "shared/ui/Tooltip.tsx",
+ "shared/ui/TooltipLayer.tsx",
+ ].sort());
+ assert.equal(fs.existsSync(path.join(root, "components/common/Tooltip.tsx")), false);
+ assert.equal(fs.existsSync(path.join(root, "components/ui/Tooltip.tsx")), false);
+
+ const legacyImports = allSources
+ .filter((file) =>
+ /@\/components\/(?:common|ui)\/Tooltip/.test(
+ fs.readFileSync(file, "utf8"),
+ ),
+ )
+ .map((file) => path.relative(root, file));
+ assert.deepEqual(legacyImports, []);
+
+ const eslintConfig = fs.readFileSync(path.join(root, "eslint.config.mjs"), "utf8");
+ assert.match(eslintConfig, /no-restricted-imports/);
+ assert.match(eslintConfig, /JSXAttribute\[name\.name='title'\]/);
+});
+
test("tracked source contains no editor backups or generated trash", () => {
const suspicious = execFileSync("git", ["ls-files", "web"], {
cwd: path.dirname(root),
diff --git a/web/tests/tooltip.spec.tsx b/web/tests/tooltip.spec.tsx
new file mode 100644
index 000000000..f89d1936f
--- /dev/null
+++ b/web/tests/tooltip.spec.tsx
@@ -0,0 +1,95 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import Tooltip, { placeTooltip } from "@/shared/ui/Tooltip";
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function visualTooltip(): HTMLElement | null {
+ return document.body.querySelector('[role="tooltip"].fixed');
+}
+
+it("keeps an accessible description connected before the visual hint opens", () => {
+ render(
+ <Tooltip label="Open settings">
+ <button type="button">Settings</button>
+ </Tooltip>,
+ );
+ const button = screen.getByRole("button", { name: "Settings" });
+ const describedBy = button.getAttribute("aria-describedby");
+ expect(describedBy).toBeTruthy();
+ expect(document.getElementById(describedBy!)).toHaveTextContent("Open settings");
+});
+
+it("renders through a body portal and keeps keyboard focus visible", async () => {
+ const { container } = render(
+ <div className="overflow-hidden">
+ <Tooltip label="A long keyboard hint" side="top">
+ <button type="button">Action</button>
+ </Tooltip>
+ </div>,
+ );
+ const button = screen.getByRole("button", { name: "Action" });
+ fireEvent.focus(button);
+ await waitFor(() =>
+ expect(visualTooltip()?.parentElement).toBe(document.body),
+ );
+
+ fireEvent.pointerLeave(button.parentElement!, { pointerType: "mouse" });
+ expect(visualTooltip()).toBeInTheDocument();
+ expect(container.querySelector('[role="tooltip"].fixed')).toBeNull();
+
+ fireEvent.keyDown(button.parentElement!, { key: "Escape" });
+ expect(visualTooltip()).toBeNull();
+});
+
+it("shows on touch and on hover over a disabled trigger", async () => {
+ vi.useFakeTimers();
+ render(
+ <Tooltip label="Unavailable because setup is incomplete" delay={20}>
+ <button type="button" disabled>
+ Disabled
+ </button>
+ </Tooltip>,
+ );
+ const wrapper = screen.getByRole("button", { name: "Disabled" }).parentElement!;
+ fireEvent.pointerEnter(wrapper, { pointerType: "mouse" });
+ await act(async () => {
+ vi.advanceTimersByTime(20);
+ await import("@/shared/ui/TooltipLayer");
+ });
+ expect(visualTooltip()).toHaveTextContent("Unavailable because setup is incomplete");
+
+ fireEvent.pointerLeave(wrapper, { pointerType: "mouse" });
+ expect(visualTooltip()).toBeNull();
+ fireEvent.pointerDown(wrapper, { pointerType: "touch" });
+ expect(visualTooltip()).toHaveTextContent("Unavailable because setup is incomplete");
+});
+
+it("flips and clamps near viewport edges", () => {
+ const rect = (values: Partial<DOMRect>): DOMRect =>
+ ({
+ x: 0,
+ y: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ left: 0,
+ width: 0,
+ height: 0,
+ toJSON: () => ({}),
+ ...values,
+ }) as DOMRect;
+ const placed = placeTooltip(
+ rect({ left: 4, right: 24, top: 40, bottom: 60, width: 20, height: 20 }),
+ rect({ width: 180, height: 40 }),
+ "left",
+ 240,
+ 120,
+ );
+ expect(placed.side).toBe("right");
+ expect(placed.left).toBeGreaterThanOrEqual(8);
+ expect(placed.top).toBeGreaterThanOrEqual(8);
+ expect(placed.left + 180).toBeLessThanOrEqual(232);
+});