# Timeline

按顺序展示带日期的事件，比如活动信息流、更新日志或订单进度，用方向键在它们之间移动。

用 Timeline（时间线）列出一件件已经发生或将要发生的事：项目的活动、订单的状态历史、一次发布的里程碑。对屏幕阅读器来说它是一个列表，键盘只有一个 Tab 停靠点，方向键在事件之间移动。

```svelte title="demo.svelte"
<script lang="ts">
  import {
    Timeline,
    TimelineConnector,
    TimelineDescription,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
  } from "@ui-sdk/svelte/timeline"

  const events = [
    {
      title: "Deployed to production",
      dateTime: "2026-11-10T14:32",
      time: "Today, 2:32 PM",
      description: "Version 2.4.1 is live in every region.",
    },
    {
      title: "Checks passed",
      dateTime: "2026-11-10T14:20",
      time: "Today, 2:20 PM",
      description: "312 tests and the bundle size budget.",
    },
    {
      title: "Pull request merged",
      dateTime: "2026-11-10T13:58",
      time: "Today, 1:58 PM",
      description: "Ada merged Cache search results into main.",
    },
    {
      title: "Review requested",
      dateTime: "2026-11-09T17:05",
      time: "Yesterday, 5:05 PM",
      description: "Grace and Linus were asked to review.",
    },
  ]
</script>

<Timeline aria-label="Activity">
  {#each events as event (event.title)}
    <TimelineItem>
      <TimelineMarker />
      <TimelineConnector />
      <TimelineTitle>{event.title}</TimelineTitle>
      <TimelineTime datetime={event.dateTime}>{event.time}</TimelineTime>
      <TimelineDescription>{event.description}</TimelineDescription>
    </TimelineItem>
  {/each}
</Timeline>
```

用 Tab 进入活动列表，再用 Up 和 Down 在事件之间移动。Home 和 End 跳到第一个和最后一个。

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

## 组合
用下面的组合来构建 `Timeline`：

```text
Timeline
├── TimelineItem
│   ├── TimelineMarker
│   ├── TimelineConnector
│   ├── TimelineTitle
│   ├── TimelineTime
│   └── TimelineDescription
└── TimelineItem
```

条目里的每个部件都是可选的。`TimelineMarker` 是线上的圆点或图标，`TimelineConnector` 是通向下一个事件的连接线。两者都会对屏幕阅读器隐藏，所以它们只用于外观。

## 用法
导入各个部件并把它们组合起来：

```svelte
<script lang="ts">
  import {
    Timeline,
    TimelineConnector,
    TimelineDescription,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
  } from "@ui-sdk/svelte/timeline"
</script>

<Timeline aria-label="Activity">
  <TimelineItem>
    <TimelineMarker />
    <TimelineConnector />
    <TimelineTitle>Deployed to production</TimelineTitle>
    <TimelineTime datetime="2026-11-10T14:32">2:32 PM</TimelineTime>
    <TimelineDescription>Version 2.4.1 is live.</TimelineDescription>
  </TimelineItem>
</Timeline>
```

`Timeline` 渲染一个带 `list` 角色的 `<div>`，每个条目是一个带 `listitem` 角色的 `<div>`。加上 `feed`，同一份标记就变成一个由文章组成的信息流。把 `datetime` 传给 `TimelineTime`，这样日期机器可读，而文字保持自然。

当焦点落到某个事件上时，屏幕阅读器会把它的标题作为名称读出，然后是它的时间和描述。事件内部的链接和按钮仍留在 Tab 顺序里：Tab 从事件移到它们，在它们上面按方向键也不会把焦点移走。

## 横向
设置 `orientation="horizontal"` 让事件排成一行，像路线图。Left 和 Right 取代 Up 和 Down 在事件之间移动，在从右到左（RTL）的文本里两者互换。设置 `loop={false}` 停在任意一端。

```svelte title="horizontal.svelte"
<script lang="ts">
  import {
    Timeline,
    TimelineConnector,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
  } from "@ui-sdk/svelte/timeline"

  const milestones = [
    { title: "Kickoff", dateTime: "2026-01", time: "January" },
    { title: "Design review", dateTime: "2026-03", time: "March" },
    { title: "Beta", dateTime: "2026-06", time: "June" },
    { title: "Launch", dateTime: "2026-09", time: "September" },
  ]
</script>

<Timeline orientation="horizontal" loop={false} aria-label="Roadmap">
  {#each milestones as milestone (milestone.title)}
    <TimelineItem>
      <TimelineMarker />
      <TimelineConnector />
      <TimelineTitle>{milestone.title}</TimelineTitle>
      <TimelineTime datetime={milestone.dateTime}>
        {milestone.time}
      </TimelineTime>
    </TimelineItem>
  {/each}
</Timeline>
```

用 Tab 进入路线图，按 Right 到达 Launch。再按 Right 会停在那里。

## 状态
为一个流程（比如订单进度）里的每个条目设置 `status`，取 `"complete"`、`"current"` 或 `"upcoming"`。当前事件会得到 `aria-current="step"`，Tab 会先落在它上面。事件的每个部件都通过 `data-complete`、`data-current` 或 `data-upcoming` 展示自己的状态。

用 `createTimelineController` 创建一个控制器，再用条目的 `value` 调用它的 `focus()`，就能从任何地方把焦点移到该条目。

```svelte title="status.svelte"
<script lang="ts">
  import { CheckIcon } from "@lucide/svelte"
  import {
    Timeline,
    TimelineConnector,
    TimelineDescription,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
    createTimelineController,
    type TimelineStatus,
  } from "@ui-sdk/svelte/timeline"

  const steps: {
    value: string
    title: string
    dateTime: string
    time: string
    description: string
    status: TimelineStatus
  }[] = [
    {
      value: "placed",
      title: "Order placed",
      dateTime: "2026-11-01",
      time: "Nov 1",
      description: "We received your order.",
      status: "complete",
    },
    {
      value: "packed",
      title: "Packed",
      dateTime: "2026-11-02",
      time: "Nov 2",
      description: "Your items left the shelf.",
      status: "complete",
    },
    {
      value: "shipped",
      title: "Shipped",
      dateTime: "2026-11-03",
      time: "Nov 3",
      description: "On its way with the carrier.",
      status: "current",
    },
    {
      value: "delivered",
      title: "Delivered",
      dateTime: "2026-11-05",
      time: "Nov 5",
      description: "Expected by Thursday.",
      status: "upcoming",
    },
  ]

  const controller = createTimelineController()
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => controller.focus("shipped")}>
      Go to Current Step
    </button>
  </div>
  <Timeline aria-label="Order status" {controller}>
    {#each steps as step (step.value)}
      <TimelineItem value={step.value} status={step.status}>
        <TimelineMarker>
          {#if step.status === "complete"}
            <CheckIcon aria-hidden="true" />
          {/if}
        </TimelineMarker>
        <TimelineConnector />
        <TimelineTitle>{step.title}</TimelineTitle>
        <TimelineTime datetime={step.dateTime}>{step.time}</TimelineTime>
        <TimelineDescription>{step.description}</TimelineDescription>
      </TimelineItem>
    {/each}
  </Timeline>
</div>
```

用 Tab 进入订单状态。焦点先落在 Shipped，也就是当前步骤。移开焦点，然后选择 Go to Current Step。

标记只向能看见的人展示状态。状态很重要时，也在标题或描述里说出来，比如 “Shipped, in progress”。

## 详情
把 [Collapsible](/docs/svelte/components/collapsible) 放进条目里，做出可以展开的详情。它的触发器是事件内部的一个按钮，所以 Tab 会在事件之后到达它，方向键仍然在事件之间移动。

```svelte title="details.svelte"
<script lang="ts">
  import { ChevronDownIcon } from "@lucide/svelte"
  import {
    Timeline,
    TimelineConnector,
    TimelineDescription,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
  } from "@ui-sdk/svelte/timeline"
  import {
    Collapsible,
    CollapsiblePanel,
    CollapsibleTrigger,
  } from "@ui-sdk/svelte/collapsible"

  const releases = [
    {
      title: "Version 2.4",
      dateTime: "2026-10-28",
      time: "October 28",
      description: "Faster search and resumable uploads.",
      changes: [
        "Search now matches file contents, not only names.",
        "Uploads resume after the connection drops.",
      ],
    },
    {
      title: "Version 2.3",
      dateTime: "2026-09-30",
      time: "September 30",
      description: "Shared links and a new sidebar.",
      changes: [
        "Shared links remember the folder they were opened from.",
        "The sidebar collapses to icons on narrow screens.",
      ],
    },
    {
      title: "Version 2.2",
      dateTime: "2026-08-26",
      time: "August 26",
      description: "Dark mode follows your system.",
      changes: [
        "Dark mode follows the system setting.",
        "Avatars are sharper.",
      ],
    },
  ]
</script>

<Timeline aria-label="Changelog">
  {#each releases as release (release.title)}
    <TimelineItem>
      <TimelineMarker />
      <TimelineConnector />
      <TimelineTitle>{release.title}</TimelineTitle>
      <TimelineTime datetime={release.dateTime}>{release.time}</TimelineTime>
      <TimelineDescription>{release.description}</TimelineDescription>
      <Collapsible>
        <CollapsibleTrigger>
          What Changed
          <ChevronDownIcon aria-hidden="true" />
        </CollapsibleTrigger>
        <CollapsiblePanel>
          <ul>
            {#each release.changes as change (change)}
              <li>{change}</li>
            {/each}
          </ul>
        </CollapsiblePanel>
      </Collapsible>
    </TimelineItem>
  {/each}
</Timeline>
```

用 Tab 移到 Version 2.4 下的 What Changed，按 Enter。用 Shift+Tab 回到事件，再按 Down 移到 Version 2.3。

## 信息流
设置 `feed`，让时间线在人们滚动时加载更多，像社交信息流一样。它遵循 [WAI-ARIA feed 模式](https://www.w3.org/WAI/ARIA/apg/patterns/feed/)：根变成一个 `feed`，每个条目变成一个带位置和总数的 `article`，从任意一篇文章内部，Page Down 和 Page Up 都能在文章之间移动。

加载或更换文章时设置 `busy`。它会设置 `aria-busy`，所以屏幕阅读器会等新文章到达再继续读。

```svelte title="feed.svelte"
<script lang="ts">
  import {
    Timeline,
    TimelineConnector,
    TimelineDescription,
    TimelineItem,
    TimelineMarker,
    TimelineTime,
    TimelineTitle,
  } from "@ui-sdk/svelte/timeline"
  import { useLog } from "./log"

  const updates = [
    {
      id: 1,
      author: "Ada",
      date: "2026-11-10",
      time: "Nov 10",
      text: "Shipped the new onboarding flow.",
    },
    {
      id: 2,
      author: "Grace",
      date: "2026-11-10",
      time: "Nov 10",
      text: "Fixed the flaky upload test.",
    },
    {
      id: 3,
      author: "Linus",
      date: "2026-11-09",
      time: "Nov 9",
      text: "Moved the docs to the new theme.",
    },
    {
      id: 4,
      author: "Margaret",
      date: "2026-11-09",
      time: "Nov 9",
      text: "Wrote the launch checklist.",
    },
    {
      id: 5,
      author: "Ada",
      date: "2026-11-08",
      time: "Nov 8",
      text: "Cut search latency in half.",
    },
    {
      id: 6,
      author: "Grace",
      date: "2026-11-07",
      time: "Nov 7",
      text: "Added keyboard shortcuts to the editor.",
    },
    {
      id: 7,
      author: "Linus",
      date: "2026-11-06",
      time: "Nov 6",
      text: "Cleaned up the old billing code.",
    },
    {
      id: 8,
      author: "Margaret",
      date: "2026-11-05",
      time: "Nov 5",
      text: "Ran the accessibility review.",
    },
    {
      id: 9,
      author: "Ada",
      date: "2026-11-04",
      time: "Nov 4",
      text: "Started the mobile layout.",
    },
  ]

  const pageSize = 3
  const log = useLog()
  let count = $state(pageSize)
  let busy = $state(false)

  function loadMore() {
    busy = true
    setTimeout(() => {
      count += pageSize
      busy = false
      log(`Loaded ${pageSize} more updates`)
    }, 600)
  }
</script>

<div data-slot="stack">
  <div data-slot="controls">
    <button
      type="button"
      disabled={busy || count >= updates.length}
      onclick={loadMore}
    >
      {busy ? "Loading…" : "Load More"}
    </button>
  </div>
  <Timeline feed {busy} aria-label="Team updates">
    {#each updates.slice(0, count) as update (update.id)}
      <TimelineItem>
        <TimelineMarker />
        <TimelineConnector />
        <TimelineTitle>{update.author}</TimelineTitle>
        <TimelineTime datetime={update.date}>{update.time}</TimelineTime>
        <TimelineDescription>{update.text}</TimelineDescription>
      </TimelineItem>
    {/each}
  </Timeline>
</div>
```

用 Tab 进入更新列表，按 Page Down。选择 Load More：信息流会一直处于忙碌状态，直到三条新更新到达。控制台会记录每次加载。

大多数时间线用列表就好。信息流用于会不断增长的长列表，屏幕阅读器的阅读模式应该从一篇文章流到下一篇文章。

## 自定义渲染
用一个 `render` snippet 把任意部件渲染成别的元素，比如把标题渲染成标题元素，让人们可以按标题在事件之间移动。snippet 必须把它的 `props` 展开到元素上：

```svelte
<TimelineTitle>
  {#snippet render({ props })}
    <h3 {...props}>Deployed to production</h3>
  {/snippet}
</TimelineTitle>
```

[部件与组合](/docs/svelte/parts-and-composition)说明了渲染约定。

## 样式
部件没有样式。把一个条目排成网格，让标记占一列，连接线沿着它定位。每个部件上的 `data-orientation` 说明事件的排列方向。

用条目上的 `data-first` 和 `data-last` 在最后一个事件之后隐藏连接线。事件进入页面后才会写入这些属性；对于服务器渲染的标记，`:last-child` 在水合之前做同样的事。

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

`Timeline` 写入 `--timeline-count`，即它包含多少事件，每个 `TimelineItem` 写入 `--timeline-index`，即它从 0 开始的位置。可以用它们做横向一行的网格列，或让动画依次错开。

### Timeline
- `--timeline-count`: How many events are in the page. Size a horizontal grid's columns with it.

### TimelineItem
- `--timeline-index`: The event's place among the events in the page, 0 for the first. It follows them as they move.

## 数据属性
### Timeline
`[data-slot="timeline"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-busy`: Present while a feed is loading or changing events, with `busy`.

### TimelineItem
`[data-slot="timeline-item"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.
- `data-first`: Present on the first event. Written once it's in the page.
- `data-last`: Present on the last event. Written once it's in the page.

### TimelineMarker
`[data-slot="timeline-marker"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.

### TimelineConnector
`[data-slot="timeline-connector"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.

### TimelineTime
`[data-slot="timeline-time"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.

### TimelineTitle
`[data-slot="timeline-title"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.

### TimelineDescription
`[data-slot="timeline-description"]`

- `data-complete`: Present when the event's status is `complete`.
- `data-orientation` (`horizontal`, `vertical`): Which way the events run.
- `data-current`: Present when the event's status is `current`.
- `data-upcoming`: Present when the event's status is `upcoming`.

## API 参考
### Timeline
- `orientation?` (`TimelineOrientation`): Which arrow keys move between events: up and down, or left and right.
- `loop?` (`boolean`): Whether arrow keys wrap from the last event to the first.
- `feed?` (`boolean`): Whether the events are a feed that loads more as people scroll, rather than a list. Each event becomes an article with its position, and Page Down and Page Up move between them from anywhere inside one.
- `busy?` (`boolean`): Whether a feed is loading or changing events, which sets `aria-busy` so screen readers wait until it's done. Only a feed reads it.
- `controller?` (`{ focus: (value?: string) => void; }`): Focuses an event from anywhere. Create one with `createTimelineController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### TimelineItem
- `value?` (`string`): Names the event for the controller's `focus()`. Generated when left out.
- `status?` (`TimelineStatus`): Where the event stands in a process. The `"current"` one sets `aria-current="step"` and takes the tab stop first.

`TimelineMarker`、`TimelineConnector`、`TimelineTime`、`TimelineTitle` 和 `TimelineDescription` 不接受自己的选项，只有它们渲染出的元素的 props。

### 状态
渲染函数和基于状态的类名在 `Timeline` 上收到什么：

- `orientation` (`TimelineOrientation`): Which way the events run.
- `feed` (`boolean`): Whether the events are a feed rather than a list.
- `busy` (`boolean`): Whether a feed is loading or changing events.

在 `TimelineItem` 以及它里面的每个部件上：

- `status` (`TimelineStatus | undefined`): Where the event stands in a process, or `undefined` when it has no status.
- `orientation` (`TimelineOrientation`): Which way the events run.

### 控制器
- `focus(value?)` (`(value?: string | undefined) => void`): Moves focus to an event by its `value`, or to the event that holds the tab stop.

## 无障碍
时间线是一个由 `listitem` 组成的 `list`，用 `aria-label` 命名。加上 `feed`，它遵循 [WAI-ARIA feed 模式](https://www.w3.org/WAI/ARIA/apg/patterns/feed/)：一个由 `article` 组成的 `feed`，每个都有 `aria-posinset` 和 `aria-setsize`，加载时带 `aria-busy`。每个事件通过 `aria-labelledby` 由标题命名，并通过 `aria-describedby` 由时间和描述描述。当前事件带有 `aria-current="step"`。

### 键盘
事件只有一个 Tab 停靠点，也就是游走焦点（roving focus）。Tab 先进入当前事件，没有则进入第一个，之后返回到上一次聚焦的事件。服务器渲染的标记在水合之前把停靠点留在第一个事件上。

| 按键                       | 作用                               |
| -------------------------- | ---------------------------------- |
| `ArrowDown` / `ArrowUp`    | 在垂直时间线的事件之间移动焦点     |
| `ArrowRight` / `ArrowLeft` | 在横向时间线的事件之间移动焦点     |
| `Home` / `End`             | 聚焦第一个或最后一个事件           |
| `PageDown` / `PageUp`      | 在信息流里从内部聚焦下一篇或上一篇 |
| `Tab`                      | 从事件移到它里面的链接和按钮       |

方向键只在事件本身按下时才移动焦点，所以里面的控件会自己处理方向键。在从右到左的文本里，Left 和 Right 互换。

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

- A busy feed sets aria-busy.

**A list of events**

- The events are a named list of list items.
- Each event is named by its title and described by its time and description.
- Tab lands on the current event, then on the links inside it, then leaves.
- The current event says it's the current step.
- Each event and its parts show its status.
- ArrowDown and ArrowUp move between events.
- ArrowLeft and ArrowRight do nothing in a vertical list.
- Home and End move to the first and last events.
- Arrow keys wrap from the last event to the first.
- Arrow keys on a link inside an event leave focus on the link.
- Page Down does nothing in a list.
- Tab comes back to the event focused last.
- Only the event with the tab stop is in the tab order.
- The first and last events are marked.
- An event added at the top becomes the first.
- Events that change places move the first and last marks.
- Each event carries its place and the list how many there are.
- The tab stop follows the current step when it moves before focus enters.
- The controller moves focus to an event.
- Markers and connectors are hidden from assistive technology.

**A list that doesn't loop**

- Arrow keys stop at either end.

**A horizontal list**

- ArrowRight and ArrowLeft move between events.
- ArrowDown and ArrowUp do nothing.

**A feed**

- The events are a named feed of articles.
- Each article says where it sits and how many there are.
- An article added at the top moves every position.
- Articles moved inside a wrapper take their new places.
- Page Down and Page Up move between articles.
- Page Down from a link inside an article moves to the next article.
- Page Down on the last article stays there.
- The feed isn't busy until it's told.

Runs in React、Vue 和 web components.
