# Waterfall

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

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

```ts title="network.ts"
import type { WaterfallData } from "@ui-sdk/core/waterfall"
import "@ui-sdk/web/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",
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-waterfall aria-label="Network requests">
      <ui-waterfall-header-row>
        <ui-waterfall-column-header>Name</ui-waterfall-column-header>
        <ui-waterfall-column-header>Size</ui-waterfall-column-header>
        <ui-waterfall-column-header aria-label="Timeline">
          <ui-waterfall-axis max-ticks="5"></ui-waterfall-axis>
          <ui-waterfall-mark time="620">DOMContentLoaded</ui-waterfall-mark>
        </ui-waterfall-column-header>
      </ui-waterfall-header-row>
      ${requests
        .map(
          (request) => `
            <ui-waterfall-row value="${request.value}">
              <ui-waterfall-row-header>${request.label}</ui-waterfall-row-header>
              <ui-waterfall-cell>${sizes[request.value]}</ui-waterfall-cell>
              <ui-waterfall-bar></ui-waterfall-bar>
            </ui-waterfall-row>`
        )
        .join("")}
    </ui-waterfall>
  `
  const waterfall = root.querySelector("ui-waterfall")!
  waterfall.getBarLabel = (request, { start, duration }) =>
    `${sizes[request.value]}, starts at ${start}, takes ${duration}`
  waterfall.items = requests
}

export { mount }
```

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

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

导入组件会定义它的元素。在服务端，导入不会做任何事。

```ts
import "@ui-sdk/web/waterfall"
```

## 组合
用下面的组合构建 `ui-waterfall`：

```text
ui-waterfall
├── ui-waterfall-header-row
│   ├── ui-waterfall-column-header
│   └── ui-waterfall-column-header
│       ├── ui-waterfall-axis
│       │   └── ui-waterfall-tick
│       └── ui-waterfall-mark
├── ui-waterfall-row
│   ├── ui-waterfall-row-header
│   │   └── ui-waterfall-indicator
│   ├── ui-waterfall-cell
│   └── ui-waterfall-bar
└── ui-waterfall-row
    ├── ui-waterfall-row-header
    └── ui-waterfall-bar
```

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

`ui-waterfall-row-header` 为 span 命名，并容纳有子 span 的 `ui-waterfall-indicator`。`ui-waterfall-bar` 是时间轴上的单元格。`ui-waterfall-cell` 是其他任意一列，比如状态或大小。表头行、时间轴和标记都是可选的。

## 用法
每个 span 有一个 `value`、一个 `label`、以毫秒计的 `start` 和 `duration`，以及它发起的 span，放在 `children` 里。把它们设置为 `items` property：

```html
<ui-waterfall aria-label="Network requests">
  <ui-waterfall-row value="document">
    <ui-waterfall-row-header>/</ui-waterfall-row-header>
    <ui-waterfall-bar></ui-waterfall-bar>
  </ui-waterfall-row>
  <ui-waterfall-row value="script">
    <ui-waterfall-row-header>app.js</ui-waterfall-row-header>
    <ui-waterfall-bar></ui-waterfall-bar>
  </ui-waterfall-row>
</ui-waterfall>

<script type="module">
  import "@ui-sdk/web/waterfall"

  document.querySelector("ui-waterfall").items = [
    { value: "document", label: "/", start: 0, duration: 182 },
    { value: "script", label: "app.js", start: 192, duration: 410 },
  ]
</script>
```

每一行都会设置 `--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;
}
```

自己不带 `ui-waterfall-row` 元素时，瀑布流为每个 span 渲染一行，带上它的表头和条形；如果里面有 `<template>`，就用它来渲染。

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

## 嵌套的 span
带 `children` 的 span 可以展开和折叠。点击 span 的指示器，或者在它的行上按 Right 和 Left。这个示例写出了每一行，瀑布流负责隐藏折叠 span 里面的行：它隐藏的行会带上 `hidden`。

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

```ts title="trace.ts"
import type { WaterfallData, WaterfallDataItem } from "@ui-sdk/core/waterfall"
import "@ui-sdk/web/waterfall"
import { ChevronRight, createElement } from "lucide"
import { log } 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 },
    ],
  },
]

function rows(items: WaterfallDataItem[]): string {
  return items
    .map(
      (item) => `
        <ui-waterfall-row value="${item.value}">
          <ui-waterfall-row-header>
            ${
              item.children
                ? `<ui-waterfall-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-waterfall-indicator>`
                : ""
            }
            ${item.label}
          </ui-waterfall-row-header>
          <ui-waterfall-bar></ui-waterfall-bar>
        </ui-waterfall-row>
        ${rows(item.children ?? [])}`
    )
    .join("")
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Expand All</button>
        <button type="button">Collapse All</button>
      </div>
      <ui-waterfall aria-label="Checkout trace" default-expanded="checkout">
        <ui-waterfall-header-row>
          <ui-waterfall-column-header>Span</ui-waterfall-column-header>
          <ui-waterfall-column-header aria-label="Timeline">
            <ui-waterfall-axis></ui-waterfall-axis>
          </ui-waterfall-column-header>
        </ui-waterfall-header-row>
        ${rows(trace)}
      </ui-waterfall>
    </div>
  `
  const waterfall = root.querySelector("ui-waterfall")!
  const [expand, collapse] = root.querySelectorAll("button")
  waterfall.format = {
    style: "unit",
    unit: "millisecond",
    unitDisplay: "narrow",
  }
  waterfall.items = trace
  expand.addEventListener("click", () => waterfall.api.expandAll())
  collapse.addEventListener("click", () => waterfall.api.collapseAll())
  waterfall.addEventListener("valuechange", (event) =>
    log(root, `Selected ${event.detail.value}`)
  )
}

export { mount }
```

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

要只写出当前显示的行，在每次 `expandedchange` 时把 `expanded` property 传给 `visibleWaterfallRows(items, expanded)`，它会按顺序展平已展开的 span。Large Traces 示例就是这么做的。

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

在时间轴里写 `ui-waterfall-tick` 元素来自定义刻度：空的元素会显示它的时间。

```ts title="zoom.ts"
import type { WaterfallData } from "@ui-sdk/core/waterfall"
import "@ui-sdk/web/waterfall"
import { ChevronRight, createElement } from "lucide"

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]
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Zoom In</button>
        <button type="button">Zoom Out</button>
        <button type="button">Reset</button>
      </div>
      <ui-waterfall
        aria-label="Dashboard render"
        default-expanded="render"
        default-value="metrics"
      >
        <ui-waterfall-header-row>
          <ui-waterfall-column-header>Span</ui-waterfall-column-header>
          <ui-waterfall-column-header aria-label="Timeline">
            <ui-waterfall-axis></ui-waterfall-axis>
          </ui-waterfall-column-header>
        </ui-waterfall-header-row>
        ${spans
          .map(
            (span) => `
              <ui-waterfall-row value="${span.value}">
                <ui-waterfall-row-header>
                  ${
                    span.children
                      ? `<ui-waterfall-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-waterfall-indicator>`
                      : ""
                  }
                  ${span.label}
                </ui-waterfall-row-header>
                <ui-waterfall-bar></ui-waterfall-bar>
              </ui-waterfall-row>`
          )
          .join("")}
      </ui-waterfall>
    </div>
  `
  const waterfall = root.querySelector("ui-waterfall")!
  const [zoomIn, zoomOut, reset] = root.querySelectorAll("button")
  let range = full
  const show = (next: [number, number]) => {
    range = next
    waterfall.range = range
  }
  waterfall.items = trace
  show(full)
  zoomIn.addEventListener("click", () => show(zoomed(range, 0.5)))
  zoomOut.addEventListener("click", () => show(zoomed(range, 2)))
  reset.addEventListener("click", () => show(full))
}

export { mount }
```

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

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

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

```ts title="virtualized.ts"
import {
  visibleWaterfallRows,
  type WaterfallData,
} from "@ui-sdk/core/waterfall"
import "@ui-sdk/web/waterfall"
import { ChevronRight, createElement } from "lucide"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="scroll">
      <ui-waterfall aria-label="Build trace" default-expanded="job-1"></ui-waterfall>
    </div>
  `
  const scroller = root.querySelector("div")!
  const waterfall = root.querySelector("ui-waterfall")!

  let rows = visibleWaterfallRows(trace, ["job-1"])

  const rendered = new Map<string, HTMLElement>()
  const render = () => {
    waterfall.style.height = `${rows.length * row}px`
    waterfall.setAttribute("aria-rowcount", String(rows.length))
    const start = Math.max(0, Math.floor(scroller.scrollTop / row) - 4)
    const end = Math.min(
      rows.length,
      Math.ceil((scroller.scrollTop + height) / row) + 4
    )
    const visible = new Map(
      rows.slice(start, end).map((entry) => [entry.item.value, entry])
    )
    for (const [value, el] of rendered) {
      if (visible.has(value)) {
        continue
      }
      el.remove()
      rendered.delete(value)
    }
    for (const [value, { item, index }] of visible) {
      let el = rendered.get(value)
      if (!el) {
        waterfall.insertAdjacentHTML(
          "beforeend",
          `<ui-waterfall-row value="${item.value}">
            <ui-waterfall-row-header>
              ${
                item.children
                  ? `<ui-waterfall-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-waterfall-indicator>`
                  : ""
              }
              ${item.label}
            </ui-waterfall-row-header>
            <ui-waterfall-bar></ui-waterfall-bar>
          </ui-waterfall-row>`
        )
        el = waterfall.lastElementChild as HTMLElement
        rendered.set(value, el)
      }
      el.style.top = `${index * row}px`
      el.setAttribute("aria-rowindex", String(index + 1))
    }
  }
  render()
  waterfall.range = [0, 400]
  waterfall.items = trace
  scroller.addEventListener("scroll", render)
  waterfall.addEventListener("expandedchange", (event) => {
    rows = visibleWaterfallRows(trace, event.detail.value)
    render()
  })
  waterfall.addEventListener("highlight", (event) => {
    const { index } = event.detail
    const top = index * row
    if (top < scroller.scrollTop) {
      scroller.scrollTop = top
    } else if (top + row > scroller.scrollTop + scroller.clientHeight) {
      scroller.scrollTop = top + row - scroller.clientHeight
    }
    render()
  })
}

export { mount }
```

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

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

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

在元素上读写这些 property，并监听它们的变更事件，或者用 `default-value` 和 `default-expanded` 设置起始状态。在变更事件里调用 `event.preventDefault()` 可以拒绝一次变更。[状态与事件](/docs/web-components/state-and-events)介绍了共享的绑定模式。

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

## 自定义渲染
自定义元素没有渲染函数。用 `as-child` 把部件绑定到你自己的元素上，或者在部件里放任意内容，再用部件的数据属性把它显示出来。绑定自己的元素见[部件与组合](/docs/web-components/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/web-components/components/waterfall#data-attributes)下。

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

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

### `<ui-waterfall-row>`
- `--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.

## 数据属性
### `<ui-waterfall-mark>`
`[data-slot="waterfall-mark"]`

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

### `<ui-waterfall-row>`
`[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.

### `<ui-waterfall-row-header>`
`[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.

### `<ui-waterfall-indicator>`
`[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.

### `<ui-waterfall-cell>`
`[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.

### `<ui-waterfall-bar>`
`[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 参考
props 是 kebab 命名的属性，比如 `default-value` 和 `max-ticks`。列表，比如 `expanded`，是用逗号分隔的值。`items`、`range`、`format`、`getBarLabel` 和 `controller` 是 property。回调是 `<ui-waterfall>` 上的 DOM 事件，不冒泡，新状态在 `event.detail.value` 里，`reason` 和 `event` 在它旁边。

### 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.
- `valuechange event`: 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.
- `expandedchange event`: Runs when spans want to expand or collapse. `details.reason` says why, and `details.cancel()` stops it.
- `highlight event`: 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.

`ui-waterfall-axis`:

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

`ui-waterfall-tick` and `ui-waterfall-mark`:

- `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.

`ui-waterfall-row` 及其 `ui-waterfall-row-header`、`ui-waterfall-indicator`、`ui-waterfall-cell` 和 `ui-waterfall-bar`：

- `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.

### 控制器
元素的 `api` property 有相同的方法。

- `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`。`ui-waterfall-row-header` 是 `rowheader`，所以焦点沿一列向下移动时，屏幕阅读器会重复 span 的名称；每个 `ui-waterfall-bar` 是一个 `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.
