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.

5.2 KB
Raw Blame
import { curveNatural } from "@visx/curve";
import { LinearGradient } from "@visx/gradient";
import { Group } from "@visx/group";
import { ParentSize } from "@visx/responsive";
import { scaleLinear, scaleUtc } from "@visx/scale";
import { Area, AreaClosed } from "@visx/shape";
import { motion } from "motion/react";
import { useId, useMemo } from "react";

const defaultPadding = { top: 8, right: 2, bottom: 2, left: 2 };

export type MiniAreaChartProps = {
  data: { date: Date; value: number }[];
  curve?: boolean;
  color?: string;
  padding?: Partial<typeof defaultPadding>;
  /** Fades the line and the area in from the left edge */
  fadeIn?: boolean;
  /** Draws a dot on the last data point */
  showEndDot?: boolean;
};

export function MiniAreaChart(props: MiniAreaChartProps) {
  return (
    <ParentSize className="relative">
      {({ width, height }) => {
        return (
          width > 0 &&
          height > 0 && <MiniAreaChartInner {...{ width, height, ...props }} />
        );
      }}
    </ParentSize>
  );
}

function MiniAreaChartInner({
  width,
  height,
  data,
  curve = true,
  color,
  padding: paddingProp,
  fadeIn = false,
  showEndDot = false,
}: MiniAreaChartProps & { width: number; height: number }) {
  const padding = { ...defaultPadding, ...paddingProp };

  const id = useId();

  const zeroedData = useMemo(
    () =>
      data.map(({ date }) => ({
        date,
        value: 0,
      })),
    [data],
  );

  const { yScale, xScale } = useMemo(() => {
    const values = data.map(({ value }) => value);
    const maxY = Math.max(...values);

    const dateTimes = data.map(({ date }) => date.getTime());
    const minDate = new Date(Math.min(...dateTimes));
    const maxDate = new Date(Math.max(...dateTimes));

    return {
      yScale: scaleLinear<number>({
        domain: [-2, Math.max(maxY, 2)],
        range: [height - padding.top - padding.bottom, 0],
        nice: true,
        clamp: true,
      }),
      xScale: scaleUtc<number>({
        domain: [minDate, maxDate],
        range: [0, width - padding.left - padding.right],
        nice: true,
      }),
    };
  }, [data, height, width]);

  return (
    <svg width={width} height={height} key={data.length}>
      <defs>
        <LinearGradient
          id={`${id}-color-gradient`}
          from={color || "#7D3AEC"}
          to={color || "#DA2778"}
          x1={0}
          x2={width - padding.left - padding.right}
          gradientUnits="userSpaceOnUse"
        />
        <LinearGradient
          id={`${id}-mask-gradient`}
          from="white"
          to="white"
          fromOpacity={0.3}
          toOpacity={0}
          x1={0}
          x2={0}
          y1={0}
          y2={1}
        />
        <mask id={`${id}-mask`} maskContentUnits="objectBoundingBox">
          <rect width="1" height="1" fill={`url(#${id}-mask-gradient)`} />
        </mask>
        {fadeIn && (
          <>
            <LinearGradient
              id={`${id}-fade-gradient`}
              from="white"
              to="white"
              fromOpacity={0}
              toOpacity={1}
              fromOffset="0%"
              toOffset="20%"
              x1={0}
              x2={1}
              y1={0}
              y2={0}
            />
            <mask id={`${id}-fade-mask`} maskContentUnits="objectBoundingBox">
              {/* extends past the bounding box, which excludes the stroke and would clip it at the peaks */}
              <rect
                y="-1"
                width="1"
                height="3"
                fill={`url(#${id}-fade-gradient)`}
              />
            </mask>
          </>
        )}
      </defs>
      <Group
        left={padding.left}
        top={padding.top}
        mask={fadeIn ? `url(#${id}-fade-mask)` : undefined}
      >
        <Area
          data={data}
          x={({ date }) => xScale(date)}
          y={({ value }) => yScale(value) ?? 0}
          curve={curve ? curveNatural : undefined}
        >
          {({ path }) => {
            return (
              <motion.path
                initial={{ d: path(zeroedData) || "", opacity: 0 }}
                animate={{ d: path(data) || "", opacity: 1 }}
                strokeWidth={1.5}
                stroke={`url(#${id}-color-gradient)`}
              />
            );
          }}
        </Area>

        <AreaClosed
          data={data}
          x={({ date }) => xScale(date)}
          y={({ value }) => yScale(value) ?? 0}
          yScale={yScale}
          curve={curve ? curveNatural : undefined}
        >
          {({ path }) => {
            return (
              <motion.path
                initial={{ d: path(zeroedData) || "", opacity: 0 }}
                animate={{ d: path(data) || "", opacity: 1 }}
                fill={`url(#${id}-color-gradient)`}
                mask={`url(#${id}-mask)`}
              />
            );
          }}
        </AreaClosed>

        {showEndDot && data.length > 0 && (
          <motion.circle
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            cx={xScale(data[data.length - 1].date)}
            cy={yScale(data[data.length - 1].value) ?? 0}
            r={2.5}
            fill={color || "#DA2778"}
          />
        )}
      </Group>
    </svg>
  );
}