Timeseries Chart 时间序列图表
@lark-ui/core

时间序列图表是用于展示基于时间的数据的专用图表。 每个数据点都是一个 [timestamp_in_ms, value] 元组。

基础折线图

一个简单的折线图,用于展示随时间变化的多条数据系列。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 基础折线图示例,展示简单的时间序列数据可视化。
 */
export function BasicLineChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "请求数",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "错误数",
        data: buildSeriesData(1, 50, 60_000, 0.3),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="数量"
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

离散计数数据

对于请求次数等离散值,请设置 yAxisMinInterval=1。这可以避免 y 轴出现小数刻度,同时保持速率等连续值的默认坐标轴行为不变。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 请求数离散图表,Y 轴刻度为整数。
 */
export function IntegerYAxisChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(() => {
    const end = Date.now();
    const values = [0, 1, 3, 2, 5, 4, 7, 3, 6, 2, 4, 1];

    return [
      {
        name: "请求数",
        data: values.map((value, index): [number, number] => [
          end - (values.length - index - 1) * 60_000,
          value,
        ]),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
    ];
  }, [isDarkMode]);

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="请求数"
      yAxisMinInterval={1}
    />
  );
}

参考标记

使用 markers 属性可在特定时间戳处渲染垂直参考线,例如部署、 发布或配置变更。标记可以包含简短标签、工具提示(Tooltip)描述、颜色和 线条样式。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

export function ReferenceMarkersChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "请求数",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "错误数",
        data: buildSeriesData(1, 50, 60_000, 0.3),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  const markers = useMemo(
    () => [
      {
        timestamp: data[0].data[15][0],
        label: "变更 a1b2c3d4",
        description: "已应用配置变更",
      },
      {
        timestamp: data[0].data[16][0],
        label: "变更 b2c3d4e5",
        description: "路由规则已更新",
      },
      {
        timestamp: data[0].data[17][0],
        label: "变更 c3d4e5f6",
        description: "限额已调整",
      },
      {
        timestamp: data[0].data[34][0],
        label: "变更 e5f6g7h8",
        description: "已发布新版本",
        lineStyle: "dotted" as const,
      },
    ],
    [data],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      markers={markers}
      xAxisName="时间(UTC)"
      yAxisName="数量"
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

阈值

使用 thresholds 属性可在数值轴上渲染水平参考线,例如内存上限 或配额边界。阈值包含数值和颜色,并可选地附带标签。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

export function ThresholdsChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "已用内存",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      thresholds={[
        {
          value: 55,
          label: "内存上限",
          color: ChartPalette.semantic("Attention", isDarkMode),
        },
      ]}
      xAxisName="时间(UTC)"
      yAxisName="内存(MB)"
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

自定义时间戳与数值格式

使用 xAxisTickFormat 自定义 x 轴标签,使用 tooltipTimestampFormat 自定义标准工具提示和标记工具提示中的 时间戳。两者接收的都是以毫秒为单位的原始时间戳,因此可以统一套用用户 所选的时区。未提供格式化函数时,工具提示中的时间戳会使用浏览器的区域 设置和时区。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/** 使用自定义 UTC 时间戳和紧凑数值格式的时间序列图。 */
export function CustomAxisLabelFormatDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "请求数",
        data: buildSeriesData(0, 50, 60_000, 1000),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="请求数"
      xAxisTickFormat={(timestamp) =>
        new Intl.DateTimeFormat(undefined, {
          timeZone: "UTC",
          hour: "2-digit",
          minute: "2-digit",
        }).format(timestamp)
      }
      yAxisTickFormat={(value) => {
        if (value >= 1000) return `${value / 1000}k`;
        return value.toString();
      }}
      tooltipValueFormat={(value) => `${(value / 1000).toFixed(1)}k 次请求`}
      tooltipTimestampFormat={(timestamp) =>
        new Intl.DateTimeFormat(undefined, {
          timeZone: "UTC",
          dateStyle: "medium",
          timeStyle: "medium",
        }).format(timestamp)
      }
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

渐变填充

将 gradient 设置为 true 即可在每条折线系列下方 渲染垂直渐变填充。填充色从顶部的系列颜色渐变到底部的透明,让图表呈现出 精致的面积图效果,同时不失单条折线的清晰度。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 时间序列图,每条折线下方带渐变填充。
 */
export function GradientLineChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "请求数",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "错误数",
        data: buildSeriesData(1, 50, 60_000, 0.3),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="数量"
      gradient
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

不完整数据

使用 incomplete 属性可标记数据可能不完整或仍在采集中的区域。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 时间序列图,高亮显示数据不完整的区域。
 */
export function IncompleteDataChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "带宽",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.categorical(0, isDarkMode),
      },
    ],
    [isDarkMode],
  );

  const incompleteTimestamp = data[0].data[data[0].data.length - 5][0];

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="Mbps"
      incomplete={{ after: incompleteTimestamp }}
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

时间范围选择

通过提供 onTimeRangeChange 回调即可启用时间范围选择。用户 可以在图表上点击并拖动来选择时间范围。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 启用了时间范围选择的时间序列图。
 */
export function TimeRangeSelectionChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "CPU 使用率",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.categorical(0, isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="%"
      onTimeRangeChange={(from, to) => {
        alert(
          `已选时间范围:\n起始:${new Date(from).toLocaleString()}\n结束:${new Date(to).toLocaleString()}`,
        );
      }}
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

工具提示页脚

使用 tooltipFooter 属性可在标准系列工具提示的数值下方添加 简短的补充说明。它适用于所有的时间序列图表配置,包括折线图、柱状图、 渐变图、阈值图和自定义坐标轴图表。

读取延迟
P99
124ms
P95
76ms
P75
32ms
P50
10ms
import { ChartPalette, TimeseriesChart, ChartLegend, LayerCard } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

export function ChartExampleDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "P99",
        data: buildSeriesData(3, 30, 60_000, 1),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
      {
        name: "P95",
        data: buildSeriesData(2, 30, 60_000, 0.6),
        color: ChartPalette.semantic("Warning", isDarkMode),
      },
      {
        name: "P75",
        data: buildSeriesData(1, 30, 60_000, 0.4),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "P50",
        data: buildSeriesData(0, 30, 60_000, 0.2),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <LayerCard>
      <LayerCard.Secondary>读取延迟</LayerCard.Secondary>
      <LayerCard.Primary>
        <div className="mb-2 flex gap-4 divide-x divide-lark-hairline px-2">
          <ChartLegend.LargeItem
            name="P99"
            color={ChartPalette.semantic("Attention", isDarkMode)}
            value="124"
            unit="ms"
          />
          <ChartLegend.LargeItem
            name="P95"
            color={ChartPalette.semantic("Warning", isDarkMode)}
            value="76"
            unit="ms"
          />
          <ChartLegend.LargeItem
            name="P75"
            color={ChartPalette.semantic("Neutral", isDarkMode)}
            value="32"
            unit="ms"
          />
          <ChartLegend.LargeItem
            name="P50"
            color={ChartPalette.semantic("Neutral", isDarkMode)}
            value="10"
            unit="ms"
          />
        </div>
        <TimeseriesChart
          xAxisName="时间(UTC)"
          echarts={echarts}
          isDarkMode={isDarkMode}
          data={data}
          height={300}
          tooltipFooter="百分位数采用 5 分钟滚动窗口计算。"
        />
      </LayerCard.Primary>
    </LayerCard>
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

工具提示光标跟随

使用 tooltipFollowCursor 属性可控制工具提示沿哪个坐标轴跟随 光标。默认值为 “both”,即自由跟随光标。设为 “x” 则可获得类似 Recharts 的轴锁定工具提示,仅沿水平方向移动。

工具提示跟随光标
import { ChartPalette, TimeseriesChart, Select } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo, useState } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 演示 `tooltipFollowCursor` 属性的交互示例。可通过下拉框在不同的光标跟随模式
 * 之间切换,观察工具提示的表现。
 */
export function TooltipFollowCursorDemo() {
  const isDarkMode = useIsDarkMode();
  const [selected, setSelected] = useState<FollowCursorOption>(
    FOLLOW_CURSOR_OPTIONS[0],
  );

  const data = useMemo(
    () => [
      {
        name: "P99",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
      {
        name: "P50",
        data: buildSeriesData(1, 50, 60_000, 0.4),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <div className="flex w-full flex-col gap-4">
      <Select
        label="工具提示跟随光标"
        value={selected}
        onValueChange={(v) => {
          if (v) setSelected(v);
        }}
        renderValue={(v) => v.label}
      >
        {FOLLOW_CURSOR_OPTIONS.map((opt) => (
          <Select.Option key={opt.value} value={opt}>
            {opt.label}
          </Select.Option>
        ))}
      </Select>
      <TimeseriesChart
        echarts={echarts}
        isDarkMode={isDarkMode}
        data={data}
        xAxisName="时间(UTC)"
        yAxisName="延迟(ms)"
        tooltipFollowCursor={selected.value}
      />
    </div>
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

工具提示边界

使用 tooltipBoundary 属性可将工具提示限制在指定的容器元素内。 默认情况下,工具提示不会溢出任何裁剪祖先元素(滚动容器、视口)。传入 一个 DOM 元素可以进一步收窄范围——当图表位于卡片或面板内部、不希望工具 提示溢出时非常有用。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useCallback, useMemo, useState } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 演示 `tooltipBoundary` 属性的示例。图表位于一个小的可滚动容器内——工具提示会被
 * 限制在容器内,而不会溢出到页面其他区域。
 */
export function TooltipBoundaryDemo() {
  const isDarkMode = useIsDarkMode();
  const [boundary, setBoundary] = useState<HTMLDivElement | null>(null);
  const boundaryRef = useCallback(
    (el: HTMLDivElement | null) => setBoundary(el),
    [],
  );

  const data = useMemo(
    () => [
      {
        name: "请求数",
        data: buildSeriesData(0, 50, 60_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "错误数",
        data: buildSeriesData(1, 50, 60_000, 0.3),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <div
      ref={boundaryRef}
      className="w-full overflow-auto rounded-lg border border-lark-line"
      style={{ height: 300 }}
    >
      <TimeseriesChart
        echarts={echarts}
        isDarkMode={isDarkMode}
        data={data}
        xAxisName="时间(UTC)"
        yAxisName="数量"
        height={280}
        tooltipBoundary={boundary ?? undefined}
      />
    </div>
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

柱状图

将 type=“bar” 即可将系列渲染为堆叠柱状而非折线。其他所有 属性——坐标轴、工具提示、颜色——行为完全一致。

import { ChartPalette, TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 以堆叠柱状图渲染的时间序列图。
 */
export function BarChartDemo() {
  const isDarkMode = useIsDarkMode();

  const data = useMemo(
    () => [
      {
        name: "age > 10 的请求数",
        data: buildSeriesData(0, 20, 3_600_000, 1),
        color: ChartPalette.semantic("Neutral", isDarkMode),
      },
      {
        name: "错误数",
        data: buildSeriesData(1, 20, 3_600_000, 0.3),
        color: ChartPalette.semantic("Attention", isDarkMode),
      },
    ],
    [isDarkMode],
  );

  return (
    <TimeseriesChart
      echarts={echarts}
      isDarkMode={isDarkMode}
      type="bar"
      data={data}
      xAxisName="时间(UTC)"
      yAxisName="数量"
      tooltipValueFormat={(r) => r.toFixed(2)}
    />
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

图例高亮

悬停某个图例项时,图表上对应的系列会被高亮,其他系列则淡出。可在 onPointerEnter 和 onPointerLeave 上配合 ChartLegend 项使用,并结合图表 ref 上的 dispatchAction 实现。

读取延迟
P99
124ms
P95
76ms
P75
32ms
P50
10ms
import { ChartPalette, TimeseriesChart, ChartLegend, LayerCard } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useMemo, useRef, useState } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 带图例项的时间序列图,悬停图例项会高亮对应的系列。
 * 悬停时向图表派发高亮动作,并让其他图例项淡出。
 */
export function LegendHighlightDemo() {
  const isDarkMode = useIsDarkMode();
  const chartRef = useRef<echarts.ECharts>(null);
  const [hoveredSeries, setHoveredSeries] = useState<string | null>(null);

  const series = useMemo(
    () => [
      {
        name: "P99",
        color: ChartPalette.semantic("Attention", isDarkMode),
        value: "124",
        unit: "ms",
      },
      {
        name: "P95",
        color: ChartPalette.semantic("Warning", isDarkMode),
        value: "76",
        unit: "ms",
      },
      {
        name: "P75",
        color: ChartPalette.semantic("Neutral", isDarkMode),
        value: "32",
        unit: "ms",
      },
      {
        name: "P50",
        color: ChartPalette.semantic("Neutral", isDarkMode),
        value: "10",
        unit: "ms",
      },
    ],
    [isDarkMode],
  );

  const data = useMemo(
    () =>
      series.map((s, i) => ({
        name: s.name,
        data: buildSeriesData(3 - i, 30, 60_000, 1 - i * 0.2),
        color: s.color,
      })),
    [series],
  );

  return (
    <LayerCard>
      <LayerCard.Secondary>读取延迟</LayerCard.Secondary>
      <LayerCard.Primary>
        <div className="mb-2 flex divide-x divide-lark-line px-2">
          {series.map((s) => (
            <ChartLegend.LargeItem
              key={s.name}
              name={s.name}
              color={s.color}
              value={s.value}
              unit={s.unit}
              inactive={hoveredSeries !== null && hoveredSeries !== s.name}
              onPointerEnter={() => {
                setHoveredSeries(s.name);
                chartRef.current?.dispatchAction({
                  type: "highlight",
                  seriesName: s.name,
                });
              }}
              onPointerLeave={() => {
                setHoveredSeries(null);
                chartRef.current?.dispatchAction({
                  type: "downplay",
                  seriesName: s.name,
                });
              }}
              className="not-first:pl-4"
            />
          ))}
        </div>
        <TimeseriesChart
          ref={chartRef}
          xAxisName="时间(UTC)"
          echarts={echarts}
          isDarkMode={isDarkMode}
          data={data}
          height={300}
        />
      </LayerCard.Primary>
    </LayerCard>
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

图例点击

点击 ChartLegend 中的某个项会单独显示该系列,只呈现它并 隐藏其余系列。再次点击已单独显示的系列即可恢复全部系列。

读取延迟
P99
124ms
P95
76ms
P75
32ms
P50
10ms
import { ChartPalette, TimeseriesChart, ChartLegend, LayerCard } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useEffect, useMemo, useRef, useState } from "react";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 点击图例项可单独显示某个系列的时间序列图。点击 `ChartLegend` 项会只显示该系列
 * 并隐藏其余系列;再次点击已单独显示的系列可恢复全部系列。可见性通过隐藏的
 * ECharts 图例以及 `legendSelect` / `legendUnSelect` 动作来控制。
 */
export function LegendOnClickDemo() {
  const isDarkMode = useIsDarkMode();
  const chartRef = useRef<echarts.ECharts>(null);
  const [hiddenSeries, setHiddenSeries] = useState<Record<string, boolean>>({});

  const series = useMemo(
    () => [
      {
        name: "P99",
        color: ChartPalette.semantic("Attention", isDarkMode),
        value: "124",
        unit: "ms",
      },
      {
        name: "P95",
        color: ChartPalette.semantic("Warning", isDarkMode),
        value: "76",
        unit: "ms",
      },
      {
        name: "P75",
        color: ChartPalette.semantic("Neutral", isDarkMode),
        value: "32",
        unit: "ms",
      },
      {
        name: "P50",
        color: ChartPalette.semantic("Neutral", isDarkMode),
        value: "10",
        unit: "ms",
      },
    ],
    [isDarkMode],
  );

  const data = useMemo(
    () =>
      series.map((s, i) => ({
        name: s.name,
        data: buildSeriesData(3 - i, 30, 60_000, 1 - i * 0.2),
        color: s.color,
      })),
    [series],
  );

  // 切换主题会重新初始化 ECharts 实例,并把图例选中状态重置为全部显示。
  // 这里同步重置自身状态,避免图例状态不同步。
  useEffect(() => {
    setHiddenSeries({});
  }, [isDarkMode]);

  // 点击可单独显示某个系列:通过(隐藏的)ECharts 图例只显示被点击的系列、
  // 隐藏其余系列。再次点击已单独显示的系列可恢复全部系列。
  const handleClick = (name: string) => {
    const chart = chartRef.current;
    if (!chart) return;

    setHiddenSeries((prev) => {
      // 已经单独显示该系列了吗?(仅它可见,其余全部隐藏)
      const isIsolated = series.every((s) =>
        s.name === name ? !prev[s.name] : prev[s.name],
      );

      const nextHidden: Record<string, boolean> = {};
      for (const s of series) {
        const shouldHide = isIsolated ? false : s.name !== name;
        nextHidden[s.name] = shouldHide;
        chart.dispatchAction({
          type: shouldHide ? "legendUnSelect" : "legendSelect",
          name: s.name,
        });
      }
      return nextHidden;
    });
  };

  return (
    <LayerCard>
      <LayerCard.Secondary>读取延迟</LayerCard.Secondary>
      <LayerCard.Primary>
        <div className="mb-2 flex divide-x divide-lark-line px-2">
          {series.map((s) => (
            <ChartLegend.LargeItem
              key={s.name}
              name={s.name}
              color={s.color}
              value={s.value}
              unit={s.unit}
              inactive={hiddenSeries[s.name] ?? false}
              onClick={() => handleClick(s.name)}
              className="not-first:pl-4"
            />
          ))}
        </div>
        <TimeseriesChart
          ref={chartRef}
          xAxisName="时间(UTC)"
          echarts={echarts}
          isDarkMode={isDarkMode}
          data={data}
          height={300}
          enableLegendSelection
        />
      </LayerCard.Primary>
    </LayerCard>
  );
}

function buildSeriesData(
  seed = 0,
  points = 50,
  stepMs = 60_000,
  timeScale = 1,
): [number, number][] {
  const end = Date.now();
  const start = end - (points - 1) * stepMs;

  return Array.from({ length: points }, (_, i) => {
    const ts = start + i * stepMs;
    const trend = i * 0.15;
    const noise = (Math.random() - 0.5) * 8;
    const value = Math.round((30 + seed * 15 + trend + noise) * 100) / 100;
    return [ts, value * timeScale];
  });
}

加载状态

将 loading 设置为 true 即可在数据加载期间显示 与图表 type 相匹配的骨架屏。

折线图

import { TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 加载状态下的折线时间序列图,展示平静区域形状的骨架屏。
 */
export function LoadingChartDemo() {
  const isDarkMode = useIsDarkMode();
  return (
    <div className="flex w-full flex-1 flex-col">
      <TimeseriesChart
        echarts={echarts}
        isDarkMode={isDarkMode}
        xAxisName="时间(UTC)"
        yAxisName="数量"
        data={[]}
        loading
      />
    </div>
  );
}

柱状图

import { TimeseriesChart } from "@lark-ui/core";
import * as echarts from "echarts/core";
import { useIsDarkMode } from "~/lib/use-is-dark-mode";

/**
 * 加载状态下的柱状时间序列图,展示与图表 `type="bar"` 输出一致的柱状骨架屏。
 */
export function LoadingBarChartDemo() {
  const isDarkMode = useIsDarkMode();
  return (
    <div className="flex w-full flex-1 flex-col">
      <TimeseriesChart
        echarts={echarts}
        isDarkMode={isDarkMode}
        type="bar"
        xAxisName="时间(UTC)"
        yAxisName="数量"
        data={[]}
        loading
      />
    </div>
  );
}