# Waterfall

把一份追踪记录或页面的请求显示为共享时间轴上的条形，span 展开后显示它发起了什么。

任何有起点和时长、并且会嵌套的东西都可以用 Waterfall：浏览器的网络请求、一份 OpenTelemetry 追踪记录、一次构建的各个步骤。每个 span 是一行，带着自己的条形，排在同一条时间轴上；屏幕阅读器和键盘用户会得到一个 treegrid，可以逐个 span 浏览。

```svelte title="network.svelte"
<script lang="ts">
  import {
    Waterfall,
    WaterfallAxis,
    WaterfallBar,
    WaterfallCell,
    WaterfallColumnHeader,
    WaterfallHeaderRow,
    WaterfallMark,
    WaterfallRow,
    WaterfallRowHeader,
    type WaterfallData,
  } from "@ui-sdk/svelte/waterfall"

  const requests: WaterfallData = [
    { value: "document", label: "/", start: 0, duration: 182 },
    { value: "styles", label: "app.css", start: 190, duration: 96 },
    { value: "script", label: "app.js", start: 192, duration: 410 },
    { value: "font", label: "inter.woff2", start: 300, duration: 220 },
    { value: "user", label: "api/user", start: 610, duration: 240 },
    { value: "avatar", label: "avatar.png", start: 860, duration: 150 },
  ]

  const sizes: Record<string, string> = {
    document: "14 kB",
    styles: "8 kB",
    script: "212 kB",
    font: "48 kB",
    user: "1 kB",
    avatar: "36 kB",
  }
</script>

<Waterfall
  aria-label="Network requests"
  items={requests}
  getBarLabel={(request, { start, duration }) =>
    `${sizes[request.value]}, starts at ${start}, takes ${duration}`}
>
  <WaterfallHeaderRow>
    <WaterfallColumnHeader>Name</WaterfallColumnHeader>
    <WaterfallColumnHeader>Size</WaterfallColumnHeader>
    <WaterfallColumnHeader aria-label="Timeline">
      <WaterfallAxis maxTicks={5} />
      <WaterfallMark time={620}>DOMContentLoaded</WaterfallMark>
    </WaterfallColumnHeader>
  </WaterfallHeaderRow>
  {#each requests as request (request.value)}
    <WaterfallRow value={request.value}>
      <WaterfallRowHeader>{request.label}</WaterfallRowHeader>
      <WaterfallCell>{sizes[request.value]}</WaterfallCell>
      <WaterfallBar />
    </WaterfallRow>
  {/each}
</Waterfall>
```

用方向键在请求之间移动。按 Right 进入某一行的单元格，每个条形会读出它的请求从何时开始、持续多久。

## 安装
```bash
npm install @ui-sdk/svelte @ui-sdk/core
```

## 组合
用下面的组合构建 `Waterfall`：

```text
Waterfall
├── WaterfallHeaderRow
│   ├── WaterfallColumnHeader
│   └── WaterfallColumnHeader
│       ├── WaterfallAxis
│       │   └── WaterfallTick
│       └── WaterfallMark
├── WaterfallRow
│   ├── WaterfallRowHeader
│   │   └── WaterfallIndicator
│   ├── WaterfallCell
│   └── WaterfallBar
└── WaterfallRow
    ├── WaterfallRowHeader
    └── WaterfallBar
```

把每个 span 作为 `items` 传入，并按 span 的 `value` 为每一个渲染一个 `WaterfallRow`。这些行是平级的兄弟行：瀑布流从 `items` 读取每一行的层级、在兄弟行中的位置和子节点。给瀑布流一个无障碍名称。

`WaterfallRowHeader` 为 span 命名，并容纳有子 span 的 `WaterfallIndicator`。`WaterfallBar` 是时间轴上的单元格。`WaterfallCell` 是其他任意一列，比如状态或大小。表头行、时间轴和标记都是可选的。

## 用法
每个 span 有一个 `value`、一个 `label`、以毫秒计的 `start` 和 `duration`，以及它发起的 span，放在 `children` 里：

```svelte
<script lang="ts">
  import {
    Waterfall,
    WaterfallBar,
    WaterfallRow,
    WaterfallRowHeader,
    type WaterfallData,
  } from "@ui-sdk/svelte/waterfall"

  const requests: WaterfallData = [
    { value: "document", label: "/", start: 0, duration: 182 },
    { value: "script", label: "app.js", start: 192, duration: 410 },
  ]
</script>

<Waterfall aria-label="Network requests" items={requests}>
  {#each requests as request (request.value)}
    <WaterfallRow value={request.value}>
      <WaterfallRowHeader>{request.label}</WaterfallRowHeader>
      <WaterfallBar />
    </WaterfallRow>
  {/each}
</Waterfall>
```

每一行都会设置 `--waterfall-start` 和 `--waterfall-size`，分别表示它的 span 从哪里开始、覆盖时间轴的多少，值为百分比。用纯 CSS 配合它们放置条形，布局不经过 JavaScript：

```css
[data-slot="waterfall-bar"] {
  position: relative;
}

[data-slot="waterfall-bar"]::before {
  content: "";
  position: absolute;
  inset-block: 6px;
  inset-inline-start: var(--waterfall-start);
  width: var(--waterfall-size);
  background: steelblue;
}
```

没有子 span 时，瀑布流为每个 span 渲染一行，带上它的表头和条形。

## 网络请求
第一个示例加了一个表头行。`WaterfallAxis` 在规整的时间点渲染 `WaterfallTick`，最多 `maxTicks` 个；`WaterfallMark` 在每一行上画出同一个时刻，比如 DOMContentLoaded，位置由 `--waterfall-mark` 决定。时间轴对屏幕阅读器隐藏，它们改为听每个条形自己的时间。`getBarLabel` 改变条形的朗读内容；这里的实现加上了请求的大小。

## 嵌套的 span
带 `children` 的 span 可以展开和折叠。点击 span 的指示器，或者在它的行上按 Right 和 Left。要只渲染当前显示的行，用 `bind:expanded` 绑定 `expanded`，传给 `visibleWaterfallRows(items, expanded)`，它会按顺序展平已展开的 span。

点击一行，或者在其上按 Enter 或 Space，会选中它。`bind:value` 保存选中的 span，就像详情面板显示的那个。`format` 改变时间的读法，这里是窄格式的毫秒。

```svelte title="trace.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    createWaterfallController,
    visibleWaterfallRows,
    Waterfall,
    WaterfallAxis,
    WaterfallBar,
    WaterfallColumnHeader,
    WaterfallHeaderRow,
    WaterfallIndicator,
    WaterfallRow,
    WaterfallRowHeader,
    type WaterfallData,
  } from "@ui-sdk/svelte/waterfall"
  import { useLog } from "./log"

  const trace: WaterfallData = [
    {
      value: "checkout",
      label: "POST /checkout",
      start: 0,
      duration: 920,
      children: [
        { value: "auth", label: "auth.verify", start: 12, duration: 64 },
        {
          value: "cart",
          label: "cart.load",
          start: 80,
          duration: 310,
          children: [
            {
              value: "cart-db",
              label: "db.query carts",
              start: 96,
              duration: 140,
            },
            {
              value: "prices",
              label: "pricing.quote",
              start: 240,
              duration: 136,
            },
          ],
        },
        {
          value: "payment",
          label: "payments.charge",
          start: 400,
          duration: 470,
          children: [
            { value: "fraud", label: "fraud.score", start: 410, duration: 120 },
            {
              value: "gateway",
              label: "gateway.capture",
              start: 540,
              duration: 310,
            },
          ],
        },
        { value: "email", label: "email.enqueue", start: 880, duration: 30 },
      ],
    },
  ]

  const log = useLog()
  const spans = createWaterfallController()
  let expanded = $state(["checkout"])
  let value: string | null = $state(null)
  const rows = $derived(visibleWaterfallRows(trace, expanded))
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => spans.expandAll()}>Expand All</button>
    <button type="button" onclick={() => spans.collapseAll()}>
      Collapse All
    </button>
  </div>
  <Waterfall
    aria-label="Checkout trace"
    items={trace}
    controller={spans}
    bind:expanded
    bind:value
    onValueChange={(next) => log(`Selected ${next}`)}
    format={{ style: "unit", unit: "millisecond", unitDisplay: "narrow" }}
  >
    <WaterfallHeaderRow>
      <WaterfallColumnHeader>Span</WaterfallColumnHeader>
      <WaterfallColumnHeader aria-label="Timeline">
        <WaterfallAxis />
      </WaterfallColumnHeader>
    </WaterfallHeaderRow>
    {#each rows as { item } (item.value)}
      <WaterfallRow value={item.value}>
        <WaterfallRowHeader>
          {#if item.children}
            <WaterfallIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </WaterfallIndicator>
          {/if}
          {item.label}
        </WaterfallRowHeader>
        <WaterfallBar />
      </WaterfallRow>
    {/each}
  </Waterfall>
</div>
```

用 Right 展开 payments.charge，然后在 gateway.capture 上按 Enter。控制台会记录选中的 span。Collapse All 会关闭所有 span。

你也可以渲染每一行，让瀑布流隐藏折叠 span 里面的行：它隐藏的行会带上 `hidden`，所以 `expanded` 可以保持非受控。

## 缩放
`range` 设置时间轴显示的时间区间，形式为 `[start, end]`。改变它就能缩放或平移：条形和刻度跟着移动，超出区间的条形会收缩到区间边缘。不传它时，时间轴从最早的开始时间延伸到最晚的结束时间。

`WaterfallAxis` 的 `children` snippet 也会收到它的 `ticks`，用来画你自己的刻度。

```svelte title="zoom.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Waterfall,
    WaterfallAxis,
    WaterfallBar,
    WaterfallColumnHeader,
    WaterfallHeaderRow,
    WaterfallIndicator,
    WaterfallRow,
    WaterfallRowHeader,
    WaterfallTick,
    type WaterfallAxisState,
    type WaterfallData,
  } from "@ui-sdk/svelte/waterfall"

  const trace: WaterfallData = [
    {
      value: "render",
      label: "render /dashboard",
      start: 0,
      duration: 1200,
      children: [
        { value: "session", label: "session", start: 20, duration: 80 },
        { value: "metrics", label: "metrics", start: 110, duration: 640 },
        { value: "alerts", label: "alerts", start: 110, duration: 260 },
        { value: "html", label: "stream html", start: 760, duration: 420 },
      ],
    },
  ]

  const spans = [trace[0], ...trace[0].children!]
  const full: [number, number] = [0, 1200]

  function zoomed([start, end]: [number, number], factor: number) {
    const center = (start + end) / 2
    const half = Math.min(((end - start) * factor) / 2, full[1] / 2)
    const from = Math.min(Math.max(full[0], center - half), full[1] - half * 2)
    return [from, from + half * 2] as [number, number]
  }

  let range = $state(full)
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => (range = zoomed(range, 0.5))}>
      Zoom In
    </button>
    <button type="button" onclick={() => (range = zoomed(range, 2))}>
      Zoom Out
    </button>
    <button type="button" onclick={() => (range = full)}>Reset</button>
  </div>
  <Waterfall
    aria-label="Dashboard render"
    items={trace}
    {range}
    defaultExpanded={["render"]}
    defaultValue="metrics"
  >
    <WaterfallHeaderRow>
      <WaterfallColumnHeader>Span</WaterfallColumnHeader>
      <WaterfallColumnHeader aria-label="Timeline">
        <WaterfallAxis>
          {#snippet children({ ticks }: WaterfallAxisState)}
            {#each ticks as tick (tick.time)}
              <WaterfallTick time={tick.time}>{tick.label}</WaterfallTick>
            {/each}
          {/snippet}
        </WaterfallAxis>
      </WaterfallColumnHeader>
    </WaterfallHeaderRow>
    {#each spans as span (span.value)}
      <WaterfallRow value={span.value}>
        <WaterfallRowHeader>
          {#if span.children}
            <WaterfallIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </WaterfallIndicator>
          {/if}
          {span.label}
        </WaterfallRowHeader>
        <WaterfallBar />
      </WaterfallRow>
    {/each}
  </Waterfall>
</div>
```

按两次 Zoom In。时间轴显示的步进变小，metrics 的 span 会伸出边缘。

## 大规模追踪
一份追踪记录可能有几千个 span。只渲染视野中的行：用 `visibleWaterfallRows` 展平已展开的 span，再按偏移量渲染附近的行。瀑布流仍然报告每一行的层级和在兄弟行中的位置，所以屏幕阅读器听到的是完整层级。给瀑布流设置 `aria-rowcount`，值为显示的行数；给每一行设置 `aria-rowindex`，值为它的索引加一。这样屏幕阅读器按整份追踪记录计算行数，而不只是页面里的这些。

`onHighlight` 报告键盘移到的那一行的索引。在那里把它滚动到可见区域，这样尚未渲染的行一旦渲染就能获得焦点。无论追踪记录多长，按一次方向键只会更新它经过的两行。

```svelte title="virtualized.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    visibleWaterfallRows,
    Waterfall,
    WaterfallBar,
    WaterfallIndicator,
    WaterfallRow,
    WaterfallRowHeader,
    type WaterfallData,
  } from "@ui-sdk/svelte/waterfall"

  const trace: WaterfallData = Array.from({ length: 2000 }, (_, job) => ({
    value: `job-${job + 1}`,
    label: `job ${job + 1}`,
    start: job * 4,
    duration: 60,
    children: Array.from({ length: 4 }, (_, step) => ({
      value: `job-${job + 1}/step-${step + 1}`,
      label: `step ${step + 1}`,
      start: job * 4 + step * 15,
      duration: 15,
    })),
  }))

  const row = 32
  const height = 288

  let scroller: HTMLDivElement | undefined = $state()
  let scrollTop = $state(0)
  let expanded = $state(["job-1"])
  const rows = $derived(visibleWaterfallRows(trace, expanded))
  const start = $derived(Math.max(0, Math.floor(scrollTop / row) - 4))
  const end = $derived(
    Math.min(rows.length, Math.ceil((scrollTop + height) / row) + 4)
  )

  function onHighlight(_value: string, { index }: { index: number }) {
    const el = scroller
    if (!el) {
      return
    }
    const top = index * row
    if (top < el.scrollTop) {
      el.scrollTop = top
    } else if (top + row > el.scrollTop + el.clientHeight) {
      el.scrollTop = top + row - el.clientHeight
    }
    scrollTop = el.scrollTop
  }
</script>

<div
  data-slot="scroll"
  bind:this={scroller}
  onscroll={(event) => (scrollTop = event.currentTarget.scrollTop)}
>
  <Waterfall
    aria-label="Build trace"
    aria-rowcount={rows.length}
    items={trace}
    range={[0, 400]}
    bind:expanded
    {onHighlight}
    style="height: {rows.length * row}px"
  >
    {#each rows.slice(start, end) as { item, index } (item.value)}
      <WaterfallRow
        value={item.value}
        aria-rowindex={index + 1}
        style="top: {index * row}px"
      >
        <WaterfallRowHeader>
          {#if item.children}
            <WaterfallIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </WaterfallIndicator>
          {/if}
          {item.label}
        </WaterfallRowHeader>
        <WaterfallBar />
      </WaterfallRow>
    {/each}
  </Waterfall>
</div>
```

按 End 聚焦 job 2000，或按 Page Down 一次移动一页。这份追踪记录有 10,000 个 span，但只渲染附近的行。

## 受控
选择和展开的 span 彼此独立：

| 值         | 形状                  | 变更通知           |
| ---------- | --------------------- | ------------------ |
| `value`    | 一个字符串或 `null`。 | `onValueChange`    |
| `expanded` | 一个 span 值的数组。  | `onExpandedChange` |

用 `bind:value` 或 `bind:expanded` 控制其中一个，或者用 `defaultValue` 和 `defaultExpanded` 设置起始状态。在变更回调里调用 `details.cancel()` 可以拒绝一次变更。[状态与事件](/docs/svelte/state-and-events)介绍了共享的绑定模式。

## 控制器
`createWaterfallController()` 的实例可以展开或折叠 span、改变选择，或者聚焦某一行。`reveal(value)` 打开一个 span 的所有祖先并聚焦它的行。Nested Spans 示例用它来实现 Expand All 和 Collapse All。设置和生命周期见[控制器](/docs/svelte/controllers)。

## 自定义渲染
每个部件都接受 `render` snippet，它的 `children` snippet 会收到部件的状态。props 合并和基于状态的渲染见[部件与组合](/docs/svelte/parts-and-composition)。

## 样式
用 `data-selected`、`data-expanded`、`data-branch` 和 `data-level` 给行的状态设置样式，它的表头、指示器、单元格和条形也会带上这些属性。焦点会在行和单元格之间移动，所以用 `:focus-visible` 给获得焦点的那个设置样式。用 `--waterfall-level` 给行的表头缩进，用 `--waterfall-start` 和 `--waterfall-size` 放置它的条形。

每个部件都有一个 `data-slot`，比如 `waterfall-row`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/svelte/components/waterfall#data-attributes)下。

### WaterfallTick
- `--waterfall-tick`: Where the tick's time sits on the axis, as a percentage. Use it for `inset-inline-start`.

### WaterfallMark
- `--waterfall-mark`: Where the mark's time sits on the axis, as a percentage. Use it for `inset-inline-start`.

### WaterfallRow
- `--waterfall-level`: The span's depth, from 1 at the top level. Use it to indent the row's header.
- `--waterfall-start`: Where the span starts on the axis, as a percentage, clamped to the range. Use it for the bar's `inset-inline-start`.
- `--waterfall-size`: How much of the axis the span covers, as a percentage. Use it for the bar's width. Zero for a span outside the range.

## 数据属性
### WaterfallMark
`[data-slot="waterfall-mark"]`

- `data-outside`: Present while the mark's time is outside the range, so it doesn't show on the axis.

### WaterfallRow
`[data-slot="waterfall-row"]`

- `data-level` (`1`, `2`): The span's depth, from 1 at the top level. Also in the `--waterfall-level` variable.
- `data-branch`: Present on a span with children.
- `data-expanded`: Present while a span with children is expanded.
- `data-selected`: Present on the selected span's row and its parts.

### WaterfallRowHeader
`[data-slot="waterfall-row-header"]`

- `data-level` (`1`, `2`): The span's depth, from 1 at the top level. Also in the `--waterfall-level` variable.
- `data-branch`: Present on a span with children.
- `data-expanded`: Present while a span with children is expanded.
- `data-selected`: Present on the selected span's row and its parts.

### WaterfallIndicator
`[data-slot="waterfall-indicator"]`

- `data-level` (`1`): The span's depth, from 1 at the top level. Also in the `--waterfall-level` variable.
- `data-branch`: Present on a span with children.
- `data-expanded`: Present while a span with children is expanded.

### WaterfallCell
`[data-slot="waterfall-cell"]`

- `data-level` (`1`, `2`): The span's depth, from 1 at the top level. Also in the `--waterfall-level` variable.
- `data-branch`: Present on a span with children.
- `data-expanded`: Present while a span with children is expanded.
- `data-selected`: Present on the selected span's row and its parts.

### WaterfallBar
`[data-slot="waterfall-bar"]`

- `data-level` (`1`, `2`): The span's depth, from 1 at the top level. Also in the `--waterfall-level` variable.
- `data-branch`: Present on a span with children.
- `data-expanded`: Present while a span with children is expanded.
- `data-selected`: Present on the selected span's row and its parts.

## API 参考
### Waterfall
- `items` (`WaterfallData`): The spans, each with a `value`, a `label`, a `start`, a `duration` and the spans it started as `children`.
- `range?` (`[number, number]`): The stretch of time the axis shows, as `[start, end]` in milliseconds. Bars outside it shrink to its edges. Change it to zoom or pan.
- `value?` (`string | null`): The selected span's value. Pass it to control the selection. `null` selects nothing.
- `defaultValue?` (`string | null`): The span selected at first, when uncontrolled.
- `onValueChange?` (`((value: string | null, details: ChangeDetails<WaterfallValueChangeReason>) => void)`): Runs when the selection wants to change. `details.reason` says why, and `details.cancel()` stops it.
- `expanded?` (`string[]`): The expanded spans' values. Pass it to control which spans show their children.
- `defaultExpanded?` (`string[]`): The spans expanded at first, when uncontrolled.
- `onExpandedChange?` (`((expanded: string[], details: ChangeDetails<WaterfallExpandedChangeReason>) => void)`): Runs when spans want to expand or collapse. `details.reason` says why, and `details.cancel()` stops it.
- `onHighlight?` (`((value: string, details: ListHighlightDetails) => void)`): Runs when the keyboard moves focus to a row, with its place among the rows that show, from 0. A waterfall that renders only the rows in view scrolls that row into view here, so it can take focus once it renders.
- `format?` (`NumberFormat`): How times read on the axis and to screen readers: `Intl.NumberFormat` options for a number of milliseconds, or a function of it.
- `locale?` (`string`): The locale times are formatted in. Defaults to the page's `lang`, or the browser's language without one, once the page is interactive. Server markup uses English until then, so it never disagrees with the client.
- `getBarLabel?` (`((item: WaterfallDataItem, details: WaterfallBarLabelDetails) => string)`): What screen readers hear for a span's bar. Set it in the page's language.
- `controller?` (`object`): Drives the waterfall from anywhere. Create one with `createWaterfallController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### WaterfallAxis
- `maxTicks?` (`number`): The most ticks the axis shows. Ticks fall on round times, so it may show fewer.

### WaterfallTick 与 WaterfallMark
- `time` (`number`): The moment it marks, in milliseconds.

### WaterfallRow
- `value` (`string`): The value of the span the row shows.

### 以数据形式提供的条目
`items` 里的每个 span：

- `value` (`string`): Identifies the span. Unique in the waterfall.
- `label` (`string`): What its row shows, and what typeahead matches.
- `start` (`number`): When it starts, in milliseconds, on the same clock as every other span.
- `duration` (`number`): How long it lasts, in milliseconds.
- `children?` (`WaterfallDataItem[]`): The spans it started. Leave it out for a span with none.

`visibleWaterfallRows(items, expanded)` 返回的每一行：

- `item` (`WaterfallDataItem`): The span this row shows, the same object you passed in.
- `parent` (`string | null`): The value of the span it's nested in, or `null` at the top level.
- `level` (`number`): Its depth, 1 at the top level.
- `index` (`number`): Its place among the rows that show, from 0.

### 状态
每个部件的渲染函数、基于状态的类名和槽位会收到什么。

`Waterfall`:

- `range` (`[number, number]`): The stretch of time the axis shows, as `[start, end]` in milliseconds.

`WaterfallAxis`:

- `ticks` (`WaterfallTickData[]`): The ticks it shows, at round times inside the range.

`WaterfallTick` and `WaterfallMark`:

- `time` (`number`): The moment it marks, in milliseconds.
- `label` (`string`): The time as `format` and the locale show it.
- `position` (`number`): Where it sits between the range's start and end, from 0 to 100.
- `outside` (`boolean`): Whether its time is outside the range, so it doesn't show on the axis.

`WaterfallRow` 及其 `WaterfallRowHeader`、`WaterfallIndicator`、`WaterfallCell` 和 `WaterfallBar`：

- `expanded` (`boolean`): Whether it's a span with children that's expanded.
- `selected` (`boolean`): Whether it's the selected span.
- `branch` (`boolean`): Whether its span has children.
- `level` (`number`): Its depth, 1 at the top level.

### 原因
span 为什么展开或折叠：

- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `imperative` (`none`): A controller or `api` call.

为什么选择改变：

- `imperative` (`none`): A controller or `api` call.
- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.

### 控制器
用 `createWaterfallController()` 创建一个，并作为 `controller` 传入。

- `getValue()` (`() => string | null`): The selected span's value, or `null`.
- `setValue(value, options?)` (`(value: string | null, options?: WaterfallChangeOptions<WaterfallValueChangeReason> | undefined) => boolean`): Selects a span, or nothing with `null`. Returns false when canceled.
- `getExpanded()` (`() => string[]`): The values of the expanded spans.
- `setExpanded(expanded, options?)` (`(expanded: string[], options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Expands exactly these spans. Returns false when canceled.
- `isExpanded(value)` (`(value: string) => boolean`): Whether a span is expanded.
- `expand(value, options?)` (`(value: string, options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Expands a span.
- `collapse(value, options?)` (`(value: string, options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Collapses a span. Focus inside it moves to its row.
- `toggle(value, options?)` (`(value: string, options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Expands a collapsed span, or collapses an expanded one.
- `expandAll(options?)` (`(options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Expands every span with children.
- `collapseAll(options?)` (`(options?: WaterfallChangeOptions<WaterfallExpandedChangeReason> | undefined) => boolean`): Collapses every span.
- `reveal(value)` (`(value: string) => void`): Expands a span's ancestors and focuses its row, through `onHighlight` when it isn't rendered.
- `focus(value?)` (`(value?: string | undefined) => void`): Focuses a span's row, or the row with the tab stop.

## 无障碍
瀑布流遵循 [WAI-ARIA treegrid 模式](https://www.w3.org/WAI/ARIA/apg/patterns/treegrid/)。行带 `row` 角色，并有 `aria-level`、`aria-posinset`、`aria-setsize`；选中的行带 `aria-selected="true"`，有子 span 的 span 带 `aria-expanded`。`WaterfallRowHeader` 是 `rowheader`，所以焦点沿一列向下移动时，屏幕阅读器会重复 span 的名称；每个 `WaterfallBar` 是一个 `gridcell`，它的名称说明 span 何时开始、持续多久，比如“Starts at 120 ms, lasts 340 ms”。时间用页面语言的 `Intl` 格式化。

### 键盘
瀑布流只有一个 Tab 停靠点。Tab 从选中的行或第一行进入，之后回到最后聚焦的行或单元格。

| 按键                 | 作用                                                                 |
| -------------------- | -------------------------------------------------------------------- |
| Down / Up Arrow      | 聚焦下一行或上一行。在单元格里时保持所在列。                         |
| Right Arrow          | 在行上，展开它，或移到它的第一个单元格。在单元格里，向右移动。       |
| Left Arrow           | 在单元格里，向左移动，然后回到行。在行上，折叠它，或聚焦它的父行。   |
| Home / End           | 聚焦第一行或最后一行。在单元格里，是这一行的第一个或最后一个单元格。 |
| Ctrl+Home / Ctrl+End | 聚焦第一行或最后一行，并保持所在列。                                 |
| Page Up / Page Down  | 一次移动一页行。                                                     |
| Enter / Space        | 选中这一行。                                                         |
| Typing               | 聚焦下一个标签以这段文字开头的行。                                   |

在 Mac 上，Command 替代 Ctrl。在从右到左（RTL）的文本中，Left 和 Right 互换。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Rows**

- Spans start collapsed, and only top-level rows show.
- Clicking the indicator expands a span without selecting it.
- Clicking a row's cell selects the row and focuses the cell.
- A change can be canceled.
- A controller expands and collapses everything, and reveals a span.
- Collapsing a span from its indicator moves focus out of it.

**Keyboard**

- The waterfall is one tab stop.
- Down and Up move between rows, Home and End to the first and last.
- Right expands a collapsed row, then moves into its cells.
- Left moves back through the cells to the row, collapses it, then moves to the parent.
- Down and Up in a cell keep its column.
- Home and End in a cell go to the row's ends, and with Control to the column's.
- A focused cell keeps the tab stop.
- A cell hidden by a collapse gives up the tab stop.
- Enter and Space select the focused row.
- Typing moves to the next row whose name starts with it.

**Time axis**

- Each row places its bar as a share of the range.
- Each bar tells screen readers when its span starts and how long it lasts.
- The axis shows round times, hidden from screen readers.

Runs in React、Vue 和 web components.
