Skip to content

The Open Standard for Generative UI

Fix chart tooltip (#171)

abhithesys0e6f9f9aeec1
diff --git a/js/packages/react-ui/.storybook/main.ts b/js/packages/react-ui/.storybook/main.ts
index 22271a5fc..92d646b10 100644
--- a/js/packages/react-ui/.storybook/main.ts
+++ b/js/packages/react-ui/.storybook/main.ts
@@ -31,6 +31,9 @@ const config: StorybookConfig = {
`,
viteFinal: async (config) => {
return mergeConfig(config, {
+ server: {
+ allowedHosts: [".trycloudflare.com", "127.0.0.1", "localhost"],
+ },
base: "/ui/",
resolve: {
alias: {
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index ab470946b..c0c69c93c 100644
--- a/js/packages/react-ui/package.json
+++ b/js/packages/react-ui/package.json
@@ -2,7 +2,7 @@
"type": "module",
"name": "@crayonai/react-ui",
"license": "MIT",
- "version": "0.8.18",
+ "version": "0.8.19",
"description": "Component library for Generative UI SDK",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx b/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
index c6fc6cf60..f5e2fe85e 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
+++ b/js/packages/react-ui/src/components/Charts/hooks/useTransformKey.tsx
@@ -1,11 +1,17 @@
-import { useMemo } from "react";
+import { useMemo, useRef } from "react";
export const useTransformedKeys = (keys: string[]) => {
+ // Use a ref to maintain a stable cache of key -> UUID mappings
+ const cacheRef = useRef<Record<string, string>>({});
+
return useMemo(() => {
return keys.reduce(
(acc, key) => {
- const transformedKey = crypto.randomUUID();
- acc[key] = transformedKey;
+ // Only generate a new UUID if we don't already have one for this key
+ if (!cacheRef.current[key]) {
+ cacheRef.current[key] = crypto.randomUUID();
+ }
+ acc[key] = cacheRef.current[key];
return acc;
},
{} as Record<string, string>,
diff --git a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/CustomTooltipContent.tsx b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/CustomTooltipContent.tsx
index 7cc00a75d..f423e76bf 100644
--- a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/CustomTooltipContent.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/CustomTooltipContent.tsx
@@ -1,5 +1,5 @@
import clsx from "clsx";
-import { forwardRef, memo, useLayoutEffect, useMemo, useState } from "react";
+import { forwardRef, memo, useMemo } from "react";
import * as RechartsPrimitive from "recharts";
import { ChartStyle, getPayloadConfigFromPayload, useChart } from "../../../Charts/Charts";
import { useSideBarTooltip } from "../../context/SideBarTooltipContext";
@@ -42,23 +42,12 @@ export const CustomTooltipContent = memo(
labelKey,
showPercentage = false,
portalContainer,
- offset,
} = props;
const { config, id } = useChart();
const { isSideBarTooltipOpen } = useSideBarTooltip();
- const [isGreaterThanTen, setIsGreaterThanTen] = useState<boolean>(
- !!(payload?.length && payload.length > 10),
- );
- const [remainingItems, setRemainingItems] = useState<number>(0);
-
- useLayoutEffect(() => {
- if (payload?.length && payload.length > 10) {
- setIsGreaterThanTen(true);
- } else {
- setIsGreaterThanTen(false);
- }
- }, [payload]);
+ const isGreaterThanTen = !!(payload?.length && payload.length > 10);
+ const remainingItems = payload && isGreaterThanTen ? payload.length - 5 : 0;
const tooltipLabel = useMemo(() => {
if (hideLabel || !payload?.length) {
@@ -179,7 +168,6 @@ export const CustomTooltipContent = memo(
// Handle regular layout with potential truncation
const morphPayload = isGreaterThanTen ? payload.slice(0, 5) : payload;
- setRemainingItems(payload.length - morphPayload.length);
return morphPayload.map((item, index) => renderPayloadItem(item, index, false));
}, [
payload,
@@ -192,7 +180,6 @@ export const CustomTooltipContent = memo(
nestLabel,
tooltipLabel,
showPercentage,
- isGreaterThanTen,
]);
// Early return for inactive or empty payload - moved after all hooks
@@ -215,12 +202,7 @@ export const CustomTooltipContent = memo(
);
return (
- <FloatingUIPortal
- active={active}
- chartId={id}
- portalContainer={portalContainer}
- offsetDistance={offset}
- >
+ <FloatingUIPortal chartId={id} portalContainer={portalContainer} position={props.coordinate}>
<ChartStyle id={id} config={config} />
{tooltipContent}
</FloatingUIPortal>
diff --git a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
index 49bf58c59..cb5531bac 100644
--- a/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/PortalTooltip/FloatingUIPortal.tsx
@@ -1,137 +1,61 @@
-import type { Placement } from "@floating-ui/react-dom";
-import { computePosition, flip, offset, shift } from "@floating-ui/react-dom";
+import { autoUpdate, flip, hide, offset, useFloating } from "@floating-ui/react-dom";
import clsx from "clsx";
-import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import React, { useEffect } from "react";
import { createPortal } from "react-dom";
import { useTheme } from "../../../ThemeProvider";
-interface VirtualElement {
- getBoundingClientRect(): DOMRect;
-}
-
interface FloatingUIPortalProps {
- active: boolean;
children: React.ReactNode;
- placement?: Placement;
- offsetDistance?: number;
className?: string;
chartId?: string;
portalContainer?: React.RefObject<HTMLElement | null>;
+ position?: Partial<{ x: number; y: number }>;
}
export const FloatingUIPortal: React.FC<FloatingUIPortalProps> = ({
- active,
children,
- placement = "right-start",
- offsetDistance = 10,
className = "",
chartId,
portalContainer,
+ position,
}) => {
- const mousePositionRef = useRef({ x: Number.MAX_SAFE_INTEGER, y: Number.MAX_SAFE_INTEGER });
- const tooltipRef = useRef<HTMLDivElement>(null);
- const [position, setPosition] = useState({ x: 0, y: 0 });
- const [isPositioned, setIsPositioned] = useState(false);
- const { portalThemeClassName } = useTheme();
-
- // Memoize the virtual element to avoid recreating it on every render
- // this virtual element basically shares the same position as the mouse position
- // and it is used to position the tooltip
- const virtualElement = useMemo<VirtualElement>(
- () => ({
- getBoundingClientRect(): DOMRect {
- return {
- width: 0,
- height: 0,
- x: mousePositionRef.current.x,
- y: mousePositionRef.current.y,
- top: mousePositionRef.current.y,
- left: mousePositionRef.current.x,
- right: mousePositionRef.current.x,
- bottom: mousePositionRef.current.y,
- } as DOMRect;
- },
- }),
- [],
- );
-
- // Function to get the portal target element
- // also memoize it to avoid recreating it on every render
- const getPortalTarget = useCallback((): HTMLElement => {
- if (!portalContainer || !portalContainer.current) {
- return document.body;
- }
- return portalContainer.current;
- }, [portalContainer]);
-
- // Memoize the updatePosition function to avoid recreating it
- const updatePosition = useCallback(async () => {
- if (
- !virtualElement ||
- !tooltipRef.current ||
- virtualElement.getBoundingClientRect().x === Number.MAX_SAFE_INTEGER ||
- virtualElement.getBoundingClientRect().y === Number.MAX_SAFE_INTEGER
- ) {
- return;
- }
-
- // https://floating-ui.com/docs/computePosition
- // not a synchronous function, it returns a promise. so we need to await it.
- const { x, y } = await computePosition(virtualElement, tooltipRef.current, {
- placement,
- middleware: [offset(offsetDistance), flip(), shift({ padding: 8 })],
- });
+ const { refs, floatingStyles, update } = useFloating({
+ placement: "right-start",
+ middleware: [offset(20), flip(), hide()],
+ whileElementsMounted: autoUpdate,
+ });
- if (x === 0 && y === 0) {
- return;
- }
-
- setPosition({ x, y });
- setIsPositioned(true);
- }, [virtualElement, placement, offsetDistance]);
-
- // Memoize the mouse move handler
- const handleMouseMove = useCallback(
- (event: MouseEvent) => {
- mousePositionRef.current = {
- x: event.clientX,
- y: event.clientY,
- };
- updatePosition();
- },
- [updatePosition],
- );
+ const { portalThemeClassName } = useTheme();
useEffect(() => {
- if (!active) {
- setIsPositioned(false);
- return;
+ if (position) {
+ update();
}
-
- document.addEventListener("mousemove", handleMouseMove);
- updatePosition();
-
- return () => {
- document.removeEventListener("mousemove", handleMouseMove);
- setIsPositioned(false);
- };
- }, [active, handleMouseMove, updatePosition]);
-
- if (!active) return null;
-
- return createPortal(
- <div
- ref={tooltipRef}
- className={clsx("crayon-portal-tooltip", portalThemeClassName, className)}
- data-chart={chartId}
- style={{
- left: position.x,
- top: position.y,
- opacity: isPositioned ? 1 : 0,
- }}
- >
- {children}
- </div>,
- getPortalTarget(),
+ }, [position, update]);
+
+ return (
+ <>
+ <div
+ ref={refs.setReference}
+ style={{
+ position: "absolute",
+ top: position?.y,
+ left: position?.x,
+ }}
+ />
+ {createPortal(
+ <div
+ ref={refs.setFloating}
+ className={clsx("crayon-portal-tooltip", portalThemeClassName, className)}
+ data-chart={chartId}
+ style={{
+ ...floatingStyles,
+ }}
+ >
+ {children}
+ </div>,
+ portalContainer?.current || document.body,
+ )}
+ </>
);
};