The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add a tooltipBounds clamp option to TimeSeriesChart
Rafi571c0bf80477
diff --git a/packages/ui/src/charts/clamped-tooltip.tsx b/packages/ui/src/charts/clamped-tooltip.tsxnew file mode 100644index 0000000000..d15300af85--- /dev/null+++ b/packages/ui/src/charts/clamped-tooltip.tsx@@ -0,0 +1,60 @@+import { PropsWithChildren, useLayoutEffect, useRef, useState } from "react";++// Places the tooltip like visx's TooltipWithBounds (next to the anchor, and+// flipped near an edge), then moves it back inside the container. On narrow+// charts a flipped tooltip can still pass the edge of the screen, which moves+// the page on mobile browsers.+export function ClampedTooltip({+ left,+ top,+ offsetLeft,+ offsetTop,+ containerWidth,+ containerHeight,+ children,+}: PropsWithChildren<{+ left: number;+ top: number;+ offsetLeft: number;+ offsetTop: number;+ containerWidth: number;+ containerHeight: number;+}>) {+ const ref = useRef<HTMLDivElement>(null);+ const [size, setSize] = useState<{ width: number; height: number } | null>(+ null,+ );++ useLayoutEffect(() => {+ if (!ref.current) return;+ const { offsetWidth: width, offsetHeight: height } = ref.current;+ if (width !== size?.width || height !== size?.height) {+ setSize({ width, height });+ }+ });++ let x = left + offsetLeft;+ let y = top + offsetTop;++ if (size) {+ if (x + size.width > containerWidth) x = left - offsetLeft - size.width;+ if (y + size.height > containerHeight) y = top - offsetTop - size.height;++ x = Math.max(0, Math.min(x, containerWidth - size.width));+ y = Math.max(0, Math.min(y, containerHeight - size.height));+ }++ return (+ <div+ ref={ref}+ className="pointer-events-none absolute left-0 top-0"+ style={{+ transform: `translate(${Math.round(x)}px, ${Math.round(y)}px)`,+ // hidden until measured, so that it does not flash in the wrong place+ visibility: size ? "visible" : "hidden",+ }}+ >+ {children}+ </div>+ );+}diff --git a/packages/ui/src/charts/time-series-chart.tsx b/packages/ui/src/charts/time-series-chart.tsxindex 3999fa9da1..aace374fa1 100644--- a/packages/ui/src/charts/time-series-chart.tsx+++ b/packages/ui/src/charts/time-series-chart.tsx@@ -5,6 +5,7 @@ import { scaleBand, scaleLinear, scaleUtc } from "@visx/scale";import { Bar, Circle, Line } from "@visx/shape";import { PropsWithChildren, useMemo, useState } from "react";import { ChartContext, ChartTooltipContext } from "./chart-context";+import { ClampedTooltip } from "./clamped-tooltip";import {ChartProps,Datum,@@ -12,7 +13,15 @@ import {} from "./types";import { useTooltip } from "./use-tooltip";-type TimeSeriesChartProps<T extends Datum> = PropsWithChildren<ChartProps<T>>;+type TimeSeriesChartProps<T extends Datum> = PropsWithChildren<+ ChartProps<T> & {+ /**+ * "flip" (the default) flips the tooltip near an edge. "clamp" also keeps+ * it inside the chart, for narrow charts on mobile.+ */+ tooltipBounds?: "flip" | "clamp";+ }+>;export function TimeSeriesChart<T extends Datum>(props: TimeSeriesChartProps<T>,@@ -45,6 +54,7 @@ function TimeSeriesChartInner<T extends Datum>({defaultTooltipIndex = null,onHoverDateChange,onXValueClick,+ tooltipBounds = "flip",margin: marginProp = {top: 12,right: 5,@@ -242,37 +252,56 @@ function TimeSeriesChartInner<T extends Datum>({{/* Tooltips */}<div className="pointer-events-none absolute inset-0">- {tooltipData && (- <TooltipWrapper- key={tooltipData.date.toString()}+ {tooltipData &&+ (() => {// Anchor bars at their center so the offset is symmetric when// the tooltip flips to the left near the right edge- left={+ const left =(tooltipLeft ?? 0) +margin.left +- ("bandwidth" in xScale ? xScale.bandwidth() / 2 : 0)- }- top={(tooltipTop ?? 0) + margin.top}- offsetLeft={+ ("bandwidth" in xScale ? xScale.bandwidth() / 2 : 0);+ const top = (tooltipTop ?? 0) + margin.top;+ const offsetLeft ="bandwidth" in xScale? xScale.bandwidth() * (0.5 + xScale.padding())- : 8- }- offsetTop={12}- className="absolute"- unstyled={true}- >- <div- className={cn(- "border-border-default bg-bg-default pointer-events-none rounded-lg border px-4 py-2 text-base shadow-sm",- tooltipClassName,- )}- >- {tooltipContent?.(tooltipData) ??- series[0].valueAccessor(tooltipData)}- </div>- </TooltipWrapper>- )}+ : 8;+ const body = (+ <div+ className={cn(+ "border-border-default bg-bg-default pointer-events-none rounded-lg border px-4 py-2 text-base shadow-sm",+ tooltipClassName,+ )}+ >+ {tooltipContent?.(tooltipData) ??+ series[0].valueAccessor(tooltipData)}+ </div>+ );++ return tooltipBounds === "clamp" ? (+ <ClampedTooltip+ left={left}+ top={top}+ offsetLeft={offsetLeft}+ offsetTop={12}+ containerWidth={outerWidth}+ containerHeight={outerHeight}+ >+ {body}+ </ClampedTooltip>+ ) : (+ <TooltipWrapper+ key={tooltipData.date.toString()}+ left={left}+ top={top}+ offsetLeft={offsetLeft}+ offsetTop={12}+ className="absolute"+ unstyled={true}+ >+ {body}+ </TooltipWrapper>+ );+ })()}</div></ChartTooltipContext.Provider></ChartContext.Provider>