Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

8.8 KB
Raw Blame
import { cn } from "@dub/utils";
import { Group } from "@visx/group";
import { ParentSize } from "@visx/responsive";
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,
  type ChartContext as ChartContextType,
} from "./types";
import { useTooltip } from "./use-tooltip";

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>,
) {
  return (
    <ParentSize className="relative">
      {({ width, height }) => {
        return (
          width > 0 &&
          height > 0 &&
          props.data.length > 0 &&
          props.series.length > 0 && (
            <TimeSeriesChartInner {...props} width={width} height={height} />
          )
        );
      }}
    </ParentSize>
  );
}

function TimeSeriesChartInner<T extends Datum>({
  type = "area",
  width: outerWidth,
  height: outerHeight,
  children,
  data,
  series,
  tooltipContent = (d) => series[0].valueAccessor(d).toString(),
  tooltipClassName = "",
  defaultTooltipIndex = null,
  onHoverDateChange,
  onXValueClick,
  tooltipBounds = "flip",
  margin: marginProp = {
    top: 12,
    right: 5,
    bottom: 32,
    left: 5,
  },
  padding: paddingProp,
}: {
  width: number;
  height: number;
} & TimeSeriesChartProps<T>) {
  const [leftAxisMargin, setLeftAxisMargin] = useState<number>();

  const margin = {
    ...marginProp,
    left: marginProp.left + (leftAxisMargin ?? 0),
  };

  const padding = paddingProp ?? {
    top: 0.1,
    bottom: type === "area" ? 0.1 : 0,
  };

  const width = outerWidth - margin.left - margin.right;
  const height = outerHeight - margin.top - margin.bottom;

  const { startDate, endDate } = useMemo(() => {
    const dates = data.map(({ date }) => date);
    const times = dates.map((d) => d.getTime());

    return {
      startDate: dates[times.indexOf(Math.min(...times))],
      endDate: dates[times.indexOf(Math.max(...times))],
    };
  }, [data]);

  const { minY, maxY } = useMemo(() => {
    const activeSeries = series.filter(({ isActive }) => isActive !== false);
    const values = data
      .flatMap((d) =>
        type === "bar"
          ? // Sum values for stacked bars
            activeSeries.reduce((sum, s) => sum + s.valueAccessor(d), 0)
          : activeSeries.map((s) => s.valueAccessor(d)),
      )
      .filter((v): v is number => v != null);

    return {
      // Start at 0 for bar charts
      minY: type === "area" ? Math.min(...values) : Math.min(0, ...values),
      maxY: Math.max(...values),
    };
  }, [data, series, type]);

  const { yScale, xScale } = useMemo(() => {
    const rangeY = maxY - minY;
    return {
      yScale: scaleLinear<number>({
        domain: [
          minY - rangeY * (padding.bottom ?? 0),
          maxY + rangeY * (padding.top ?? 0),
        ],
        range: [height, 0],
        nice: true,
        clamp: true,
      }),
      xScale:
        type === "area"
          ? scaleUtc<number>({
              domain: [startDate, endDate],
              range: [0, width],
            })
          : scaleBand({
              domain: data.map(({ date }) => date),
              range: [0, width],
              padding: 0.15,
              align: 0.5,
            }),
    };
  }, [startDate, endDate, minY, maxY, height, width, data.length, type]);

  const chartContext: ChartContextType<T> = {
    type,
    width,
    height,
    data,
    series,
    startDate,
    endDate,
    xScale: xScale as any,
    yScale,
    minY,
    maxY,
    margin,
    padding,
    tooltipContent,
    tooltipClassName,
    defaultTooltipIndex,
    onHoverDateChange,
    leftAxisMargin,
    setLeftAxisMargin,
  };

  const tooltipContext = useTooltip({
    seriesId: series[0].id,
    chartContext,
    onHoverDateChange,
    defaultIndex: defaultTooltipIndex ?? undefined,
  });

  const {
    tooltipData,
    TooltipWrapper,
    tooltipLeft,
    tooltipTop,
    handleTooltip,
    hideTooltip,
    containerRef,
  } = tooltipContext;

  return (
    <ChartContext.Provider value={chartContext}>
      <ChartTooltipContext.Provider value={tooltipContext}>
        <svg width={outerWidth} height={outerHeight} ref={containerRef}>
          {children}
          <Group left={margin.left} top={margin.top}>
            {/* Tooltip hover line + circle */}
            {tooltipData &&
              ("bandwidth" in xScale ? (
                <>
                  <Bar
                    x={
                      (xScale(tooltipData.date) ?? 0) -
                      xScale.bandwidth() * xScale.padding()
                    }
                    width={xScale.bandwidth() * (1 + xScale.padding() * 2)}
                    y={0}
                    height={height}
                    className="fill-[rgb(var(--content-emphasis))]"
                    fillOpacity={0.05}
                  />
                </>
              ) : (
                <>
                  <Line
                    x1={xScale(tooltipData.date)}
                    x2={xScale(tooltipData.date)}
                    y1={height}
                    y2={0}
                    className="stroke-[rgb(var(--content-emphasis))]"
                    strokeOpacity={0.5}
                    strokeWidth={1}
                  />

                  {series
                    .filter(({ isActive }) => isActive)
                    .map((s) => (
                      <Circle
                        key={s.id}
                        cx={xScale(tooltipData.date)}
                        cy={yScale(s.valueAccessor(tooltipData))}
                        r={4}
                        className={s.colorClassName ?? "text-blue-800"}
                        fill="currentColor"
                      />
                    ))}
                </>
              ))}

            {/* Tooltip hover region */}
            <Bar
              x={0}
              y={0}
              width={width}
              height={height}
              onTouchStart={handleTooltip}
              onTouchMove={handleTooltip}
              onMouseMove={handleTooltip}
              onMouseLeave={hideTooltip}
              onClick={() => {
                if (tooltipData) {
                  onXValueClick?.(tooltipData);
                }
              }}
              onTouchEnd={() => {
                if (tooltipData) {
                  onXValueClick?.(tooltipData);
                }
              }}
              className={onXValueClick ? "cursor-pointer" : undefined}
              fill="transparent"
            />
          </Group>
        </svg>

        {/* Tooltips */}
        <div className="pointer-events-none absolute inset-0">
          {tooltipData &&
            (() => {
              // Anchor bars at their center so the offset is symmetric when
              // the tooltip flips to the left near the right edge
              const left =
                (tooltipLeft ?? 0) +
                margin.left +
                ("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;
              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>
  );
}