Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/green-schools-poke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"@devgateway/dvz-ui-react": minor
---

Fix chart tooltips: migrate to floating-ui for proper scroll detection and positioning

- Implemented `useTooltipPosition()` hook using @floating-ui/react with automatic viewport boundary detection (flip/shift middleware)
- Added `useHideTooltipOnScroll()` hook for instant tooltip dismissal on scroll/touch events
- Fixed theme scope styling by anchoring FloatingPortal to nearest `#root` or `.edit-post-visual-editor` ancestor
- Enabled frame-by-frame position tracking via autoUpdate with animationFrame option (required for Nivo's react-spring animations)
- Added independent hover/touch state management for better control over tooltip visibility
- Applied changes to Tooltip.jsx (Bar, Line, Pie charts) and ChartTooltip.jsx (Sankey, GroupedBars)

**Breaking changes:** None. Internal implementation detail; public API unchanged.
**Related:** Addresses off-screen tooltips, scroll persistence
5 changes: 5 additions & 0 deletions packages/dvz-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
},
"dependencies": {
"@artsy/fresnel": "^8.1.0",
"@floating-ui/react": "^0.27.20",
"@floating-ui/react-dom": "^2.1.9",
"@nivo/bar": "^0.96.0",
"@nivo/bump": "^0.96.0",
"@nivo/colors": "^0.96.0",
Expand All @@ -69,6 +71,7 @@
"html-react-parser": "^5.2.6",
"immutable": "^5.1.3",
"lodash": "^4.17.21",
"lodash.debounce": "^4.0.8",
"lodash.isequal": "^4.5.0",
"papaparse": "^5.5.3",
"pure-react-carousel": "^1.32.0",
Expand Down Expand Up @@ -103,11 +106,13 @@
"@types/d3-shape": "^3.1.7",
"@types/file-saver": "^2.0.7",
"@types/lodash": "^4.17.16",
"@types/lodash.debounce": "^4.0.9",
"@types/lodash.isequal": "^4.5.8",
"@types/node": "^22.15.18",
"@types/papaparse": "^5.3.16",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.1",
"@types/string-template": "^1.0.7",
"@types/topojson-client": "^3.1.5",
"@types/uuid": "^10.0.0",
"@vitejs/plugin-react-swc": "^3.9.0",
Expand Down
4 changes: 2 additions & 2 deletions packages/dvz-ui/src/embeddable/big-filter/BigNumberGroup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Container, Grid } from "semantic-ui-react";
import { BigNumberItem } from './BigNumberItem';
import { decode } from '../utils/parseUtils';
import _ from 'lodash';
import debounce from 'lodash.debounce';

const BigNumberGroup = (props) => {
const {
Expand Down Expand Up @@ -74,7 +74,7 @@ const BigNumberGroup = (props) => {
}

const debouncedApplyFilter = useRef(
_.debounce((newFilters, type) => {
debounce((newFilters, type) => {
if (newFilters.length == 0) {
onSetFilter({ app, group, parent, param: type, value: [] });
onUnSetFilter({ app, group: blockName, parent, param: type });
Expand Down
1 change: 0 additions & 1 deletion packages/dvz-ui/src/embeddable/chart/Radar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { injectIntl } from "react-intl";
import { ResponsiveRadar } from "@nivo/radar";
import Legends from "./Legends.jsx";
import deviceType from "@/utils/deviceType.js";
import _ from "lodash";

const DEFAULT_COLOR = "none";

Expand Down
228 changes: 126 additions & 102 deletions packages/dvz-ui/src/embeddable/chart/Tooltip.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useLayoutEffect, useRef } from "react";
import React, { useCallback, useEffect, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
import template from 'string-template';
import { useFloating, autoUpdate, offset, flip, shift, FloatingPortal } from "@floating-ui/react";

const percentExpresion = /(\+?\%)[\(]([A-z0-9,.,-]+)\)/gi;
const numericExpresion = /(\+?\#)[\(]([A-z0-9,.,-]+)\)/gi;
Expand All @@ -11,104 +12,90 @@ const compactExpresion = /(\+?\#C)[\(]([A-z0-9,.,-]+)\)/gi;
// Minimum gap (px) to keep between the tooltip and the viewport edge.
const VIEWPORT_EDGE_MARGIN = 8;

// Shift needed to bring [start, end] inside [0, viewportSize]; 0 if it already fits.
const clampShift = (start, end, viewportSize, overshoot = 0) => {
if (start < VIEWPORT_EDGE_MARGIN) {
return VIEWPORT_EDGE_MARGIN - start;
// Chart libraries like nivo render our tooltip inside their own
// absolutely-positioned wrapper div, placed near the hovered point.
const isNivoTooltipWrapper = (el) => {
if (!el) {
return false;
}
if (end > viewportSize - VIEWPORT_EDGE_MARGIN) {
return viewportSize - VIEWPORT_EDGE_MARGIN - end - overshoot;
}
return 0;
};

// Nudges an already-positioned tooltip back inside the viewport via a
// corrective transform, without touching the chart library's own positioning
// (chart libraries like nivo can place tooltips past the screen edge).
export const clampTooltipToViewport = (el) => {
if (!el || typeof window === "undefined") {
return;
}

// Reset so we measure relative to the library's original position.
el.style.transform = "";

const rect = el.getBoundingClientRect();
const { innerWidth: viewportWidth, innerHeight: viewportHeight } = window;
const mobileOvershoot = viewportWidth < 768 ? 12 : 40; // extra room on narrow viewports

const shiftX = clampShift(rect.left, rect.right, viewportWidth, mobileOvershoot);
const shiftY = clampShift(rect.top, rect.bottom, viewportHeight);

if (shiftX || shiftY) {
el.style.transform = `translate(${Math.round(shiftX)}px, ${Math.round(shiftY)}px)`;
}
const inlineStyle = (el.getAttribute("style") || "").toLowerCase();
return (
inlineStyle.includes("position: absolute") &&
inlineStyle.includes("pointer-events: none")
);
};

// Frames with an unchanged correction before we consider the tooltip settled.
const SETTLE_FRAMES = 6;
// Safety cap on a burst's length (~1s at 60fps) in case position never settles.
const MAX_BURST_FRAMES = 60;

/**
* Keeps a tooltip inside the viewport, re-clamping every frame for a short
* burst whenever it might have moved (mount, resize, scroll) and stopping
* once the correction settles. The burst is needed because animated wrappers
* (e.g. nivo + react-spring) can still be mid-animation when we first measure.
/**
* Positions a tooltip bubble with floating-ui: anchored to wherever the host
* chart library already placed its wrapper, and kept clear of the viewport
* edges via the `shift`/`flip` middleware. Render the bubble through
* <FloatingPortal> so its `fixed` positioning escapes the host wrapper's own
* transform (nivo animates that transform with react-spring).
*/
export const useClampTooltipToViewport = (deps = []) => {
const ref = useRef(null);

useLayoutEffect(() => {
const el = ref.current;
if (!el || typeof window === "undefined" || !window.requestAnimationFrame) {
clampTooltipToViewport(el);
return undefined;
}

let frameId = null;

const startBurst = () => {
if (frameId != null) {
window.cancelAnimationFrame(frameId);
export const useTooltipPosition = () => {
const { refs, floatingStyles } = useFloating({
placement: "top",
strategy: "fixed",
// The reference (nivo's wrapper) moves via a transform, not a resize/
// layout change, so we need frame-by-frame tracking rather than the
// default scroll/resize-only observers.
whileElementsMounted: (referenceEl, floatingEl, update) =>
autoUpdate(referenceEl, floatingEl, update, { animationFrame: true }),
middleware: [offset(8), flip(), shift({ padding: VIEWPORT_EDGE_MARGIN })],
Comment thread
timothy-mugo marked this conversation as resolved.
Resolved
});

// The theme's `.chart.tooltip` styling (background, border, padding, ...)
// is compiled scoped under `#root`/`.edit-post-visual-editor`. FloatingPortal
// defaults to `document.body`, which escapes that scope and drops the
// styling, so anchor the portal to whichever of those ancestors we find.
const [portalRoot, setPortalRoot] = useState(null);

const anchorRef = useCallback(
(node) => {
if (!node) {
return;
}
const wrapper = isNivoTooltipWrapper(node.parentElement) ? node.parentElement : node;
refs.setReference(wrapper);
setPortalRoot(wrapper.closest("#root, .edit-post-visual-editor") || wrapper.ownerDocument.body);
},
[refs]
);

let lastTransform = null;
let unchangedFrames = 0;

const tick = (frame) => {
clampTooltipToViewport(el);

unchangedFrames = el.style.transform === lastTransform ? unchangedFrames + 1 : 0;
lastTransform = el.style.transform;
return { anchorRef, floatingRef: refs.setFloating, floatingStyles, portalRoot };
};

const settled = unchangedFrames >= SETTLE_FRAMES || frame >= MAX_BURST_FRAMES;
frameId = settled ? null : window.requestAnimationFrame(() => tick(frame + 1));
};
// Hides sticky/touch-triggered tooltips the instant the user scrolls, touches
// to scroll, or taps anywhere (used to dismiss the tooltip). Listeners are
// passive/capturing so they never block scrolling and fire on nested
// scroll containers, not just the window.
export const useHideTooltipOnScroll = (resetDeps = []) => {
const [isHidden, setIsHidden] = useState(false);

tick(0);
};
useEffect(() => {
setIsHidden(false);
}, resetDeps);

startBurst();
useEffect(() => {
if (typeof window === "undefined") {
return undefined;
}

const resizeObserver = typeof ResizeObserver !== "undefined" ? new ResizeObserver(startBurst) : null;
resizeObserver?.observe(el);
const hide = () => setIsHidden(true);
Comment thread
timothy-mugo marked this conversation as resolved.
Resolved

// Capture phase catches scroll on any ancestor, not just the window.
window.addEventListener("scroll", startBurst, true);
window.addEventListener("resize", startBurst);
window.addEventListener("scroll", hide, { capture: true, passive: true });
window.addEventListener("touchmove", hide, { capture: true, passive: true });
window.addEventListener("pointerdown", hide, { capture: true, passive: true });

return () => {
if (frameId != null) {
window.cancelAnimationFrame(frameId);
}
resizeObserver?.disconnect();
window.removeEventListener("scroll", startBurst, true);
window.removeEventListener("resize", startBurst);
window.removeEventListener("scroll", hide, { capture: true });
window.removeEventListener("touchmove", hide, { capture: true });
window.removeEventListener("pointerdown", hide, { capture: true });
};
}, deps);
}, []);

return ref;
return isHidden;
};

const applyFormat = (expresion, str, style, isPercent, intl, container) => {
Expand Down Expand Up @@ -206,29 +193,66 @@ const Tooltip = ({ tooltip, d, intl, tooltipEnableMarkdown }) => {
}

// Must run before any early return below (rules of hooks).
const tooltipRef = useClampTooltipToViewport([str, tooltipEnableMarkdown]);
const hideOnScroll = useHideTooltipOnScroll([d, str]);
// Explicit, event-driven visibility -- independent of nivo's own hover
// detection -- so the tooltip reacts to mouse/touch events on itself
// instead of relying solely on the chart library re-rendering it.
const [isHovered, setIsHovered] = useState(true);
const { anchorRef, floatingRef, floatingStyles, portalRoot } = useTooltipPosition();

// A new/changed data point should always start out visible.
useEffect(() => {
setIsHovered(true);
}, [d, str]);

if (!str) {
return <div></div>;
return <div ref={anchorRef}></div>;
}

if (tooltipEnableMarkdown) {
return (
<div ref={tooltipRef} className={"chart tooltip"}>
<ReactMarkdown
children={str}
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
></ReactMarkdown>
</div>
);
} else {
return (
<div ref={tooltipRef} className={"chart tooltip"}>
<div dangerouslySetInnerHTML={{ __html: str }}></div>
</div>
);
}
const isVisible = isHovered && !hideOnScroll;

const show = () => setIsHovered(true);
const hide = () => setIsHovered(false);
const handleTouchStart = () => setIsHovered(true);
const handleTouchEnd = (event) => {
// Prevent the emulated mouse events that follow a tap from immediately
// hiding the tooltip we just opened via touch.
event.preventDefault();
};

const content = tooltipEnableMarkdown ? (
<ReactMarkdown
children={str}
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
></ReactMarkdown>
) : (
<div dangerouslySetInnerHTML={{ __html: str }}></div>
);

return (
<div ref={anchorRef}>
<FloatingPortal root={portalRoot}>
<div
ref={floatingRef}
className={"chart tooltip"}
role="tooltip"
aria-hidden={!isVisible}
style={{
...floatingStyles,
visibility: isVisible ? "visible" : "hidden",
Comment thread
timothy-mugo marked this conversation as resolved.
Resolved
pointerEvents: isVisible ? "auto" : "none",
}}
onMouseEnter={show}
onMouseLeave={hide}
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
{content}
</div>
</FloatingPortal>
</div>
);
};

export default Tooltip;
34 changes: 17 additions & 17 deletions packages/dvz-ui/src/embeddable/common/ChartTooltip.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeRaw from 'rehype-raw'
import template from 'string-template';
import { useClampTooltipToViewport } from "../chart/Tooltip";
import { FloatingPortal } from "@floating-ui/react";
import { useTooltipPosition, useHideTooltipOnScroll } from "../chart/Tooltip";

const percentExpresion = /(\+?\%)[\(]([A-z0-9,.,-]+)\)/gi
const numericExpresion = /(\+?\#)[\(]([A-z0-9,.,-]+)\)/gi
Expand Down Expand Up @@ -51,24 +52,23 @@ const ChartTooltip = ({tooltip, d, intl, tooltipEnableMarkdown}) => {
}

// Must run on every render, before any conditional early return.
const tooltipRef = useClampTooltipToViewport([str, tooltipEnableMarkdown])

if (data) {
if (tooltipEnableMarkdown) {
return (
<div ref={tooltipRef} className={"chart tooltip"}>
<ReactMarkdown children={str} remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
</ReactMarkdown>
</div>
)
} else {
return (
<div ref={tooltipRef} className={"chart tooltip"} >
<div dangerouslySetInnerHTML={{ __html: str }}></div>
</div>)
}
const { anchorRef, floatingRef, floatingStyles, portalRoot } = useTooltipPosition()
const hideOnScroll = useHideTooltipOnScroll([d, str])

if (data && !hideOnScroll) {
const content = tooltipEnableMarkdown
? <ReactMarkdown children={str} remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}></ReactMarkdown>
: <div dangerouslySetInnerHTML={{ __html: str }}></div>

return (
<div ref={anchorRef}>
<FloatingPortal root={portalRoot}>
<div ref={floatingRef} style={floatingStyles} className={"chart tooltip"} role="tooltip">
{content}
</div>
</FloatingPortal>
</div>
)
} else {
return <div></div>
}
Expand Down
Loading
Loading