# Anchor

> 通过层级目录跳转到页内章节，跟随阅读位置并支持独立滚动容器。

网页来源：/components/anchor

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

## 基本用法

`items` 提供目标元素的 `id` 和链接文字 `label`，`children` 表示下级章节。ID 不带 `#`，不预先编码，并且在整个页面内唯一。`title` 为目录添加可见标题。

未指定 `scrollContainer` 时滚动浏览器窗口。以下预览绑定独立内容区，方便直接试用；页面右侧的“本页内容”也是 Anchor。

### 示例：anchor/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { QuireAnchor } from '@quirekit/ui/vue';
import type { QuireKitAnchorItem } from '@quirekit/ui/vue';
const viewport = shallowRef<HTMLElement | null>(null);
const items: QuireKitAnchorItem[] = [
  { id: 'anchor-intro', label: '项目概览', children: [
    { id: 'anchor-goals', label: '目标与范围' }, { id: 'anchor-members', label: '参与成员' }
  ] },
  { id: 'anchor-delivery', label: '交付安排' }
];
</script>
<template>
  <div class="p-qk-surface grid gap-qk-surface" data-anchor-basic>
    <QuireAnchor :items="items" title="项目计划" :scroll-container="() => viewport" :history="false" />
    <div ref="viewport" class="h-64 overflow-auto border border-qk-border-subtle rounded-qk-control p-qk-surface" tabindex="0" aria-label="项目计划正文" data-anchor-viewport>
      <section class="min-h-32"><h3 id="anchor-intro" class="font-medium">项目概览</h3><p>整理团队需要共同完成的工作，建立清晰的时间安排。</p></section>
      <section class="min-h-40"><h4 id="anchor-goals" class="font-medium">目标与范围</h4><p>本阶段完成需求确认、方案评审与交付验收。</p></section>
      <section class="min-h-40"><h4 id="anchor-members" class="font-medium">参与成员</h4><p>产品、设计与开发共同维护这份计划。</p></section>
      <section class="min-h-48"><h3 id="anchor-delivery" class="font-medium">交付安排</h3><p>每周更新进展，记录关键决定与待办事项。</p></section>
    </div>
  </div>
</template>
<style scoped>
@container demo (min-width: 34rem) { [data-anchor-basic] { grid-template-columns: 10rem minmax(0, 1fr); } }
</style>
```

## 滚动容器与偏移

`scrollContainer` 接受元素、选择器或返回元素的函数。`offset` 默认 `16`，控制标题与滚动区域顶部的距离，适合为固定工具栏预留空间。组件本身不吸顶，由外层布局安排目录的位置和高度。

### 示例：anchor/container

文件：`container.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireAnchor, QuireButton, QuireSpace } from '@quirekit/ui/vue';
const offset = ref(48);
const items = [{ id: 'anchor-edit', label: '编辑内容' }, { id: 'anchor-review', label: '提交审核' }, { id: 'anchor-publish', label: '发布文档' }];
</script>
<template>
  <div class="p-qk-surface grid gap-qk-surface" data-anchor-container>
    <QuireSpace><span>顶部偏移</span><QuireButton v-for="value in [16, 48, 80]" :key="value" :aria-pressed="offset === value" @click="offset = value">{{ value }} px</QuireButton></QuireSpace>
    <QuireAnchor :items="items" title="操作指南" scroll-container="#anchor-guide-viewport" :offset="offset" :history="false" />
    <div id="anchor-guide-viewport" class="h-56 overflow-auto border border-qk-border-subtle rounded-qk-control p-qk-surface" tabindex="0" aria-label="操作指南正文">
      <section v-for="item in items" :key="item.id" class="min-h-64"><h3 :id="item.id" class="font-medium">{{ item.label }}</h3><p>完成本节操作后，可以使用目录跳转到下一步。</p></section>
    </div>
  </div>
</template>
```

## 地址与历史

`history` 默认 `push`，点击后写入 fragment，可复制地址并通过后退、前进恢复章节。`replace` 替换当前记录；设为 `false` 时只滚动，不读写页面地址，适合多个独立预览。浏览阅读时不会不断修改 URL。

初始地址和浏览器历史中的 fragment 会在目标挂载后恢复。路由切换仍由宿主负责；目录项只指向当前文档中的元素。

### 示例：anchor/history

文件：`history.vue`

```vue
<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { QuireAnchor, QuireButton, QuireSpace } from '@quirekit/ui/vue';
const history = ref<'push' | 'replace' | false>('push');
const viewport = shallowRef<HTMLElement | null>(null);
const items = [{ id: 'anchor-草稿', label: '草稿' }, { id: 'anchor-待审核', label: '待审核' }, { id: 'anchor-已发布', label: '已发布' }];
</script>
<template>
  <div class="p-qk-surface grid gap-qk-surface" data-anchor-history>
    <QuireSpace><span>历史策略</span><QuireButton v-for="value in (['push', 'replace', false] as const)" :key="String(value)" :aria-pressed="history === value" @click="history = value">{{ value === false ? '不修改地址' : value }}</QuireButton></QuireSpace>
    <QuireAnchor :items="items" title="文档状态" :scroll-container="() => viewport" :history="history" />
    <div ref="viewport" class="h-56 overflow-auto border border-qk-border-subtle rounded-qk-control p-qk-surface" tabindex="0" aria-label="文档状态正文" data-anchor-history-viewport>
      <section v-for="item in items" :key="item.id" class="min-h-64"><h3 :id="item.id" class="font-medium">{{ item.label }}</h3><p>点击目录后查看地址栏；后退和前进可以返回此前章节。</p></section>
    </div>
  </div>
</template>
```

## 动态内容与当前位置

标题增删或内容高度变化后，当前位置会重新计算。`change` 返回当前 ID；无可见目标时返回空字符串。空 `items` 不渲染目录，长名称自动换行。

### 示例：anchor/dynamic

文件：`dynamic.vue`

```vue
<script setup lang="ts">
import { computed, ref, shallowRef } from 'vue';
import { QuireAnchor, QuireButton, QuireSpace } from '@quirekit/ui/vue';
const showAppendix = ref(false);
const empty = ref(false);
const current = ref('');
const viewport = shallowRef<HTMLElement | null>(null);
const items = computed(() => empty.value ? [] : [
  { id: 'anchor-summary', label: '工作总结' }, { id: 'anchor-next', label: '后续计划与需要跨团队共同确认的事项' },
  ...(showAppendix.value ? [{ id: 'anchor-appendix', label: '附录' }] : [])
]);
</script>
<template>
  <div class="p-qk-surface grid gap-qk-surface" data-anchor-dynamic>
    <QuireSpace><QuireButton @click="showAppendix = !showAppendix">{{ showAppendix ? '移除附录' : '添加附录' }}</QuireButton><QuireButton @click="empty = !empty">{{ empty ? '恢复内容' : '清空内容' }}</QuireButton></QuireSpace>
    <QuireAnchor :items="items" title="总结目录" :scroll-container="() => viewport" :history="false" @change="current = $event" />
    <p class="text-qk-text-secondary" role="status">当前位置：{{ current || '无' }}</p>
    <div ref="viewport" class="h-56 overflow-auto border border-qk-border-subtle rounded-qk-control p-qk-surface" tabindex="0" aria-label="总结正文">
      <section v-for="item in items" :key="item.id" class="min-h-64"><h3 :id="item.id" class="font-medium">{{ item.label }}</h3><p>目录与标题来自同一份数据，可以随内容同步更新。</p></section>
      <p v-if="empty">暂无内容，可通过“恢复内容”重新开始阅读。</p>
    </div>
  </div>
</template>
```

## 键盘与动效

链接使用 Tab、Shift+Tab 和 Enter。普通点击或 Enter 将焦点移到目标标题；滚动阅读和历史恢复不抢焦点。保留修饰键打开、复制链接等原生行为，`navigate(item, event)` 中可用 `event.preventDefault()` 取消跳转。

`behavior` 默认 `smooth`，可设为 `instant`。系统启用减少动效时始终立即滚动；初始地址与历史恢复也立即定位。

## API

### QuireAnchor

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| items | 是 | — | Headings in reading order. An empty list renders no navigation. |
| title | 否 | — | Optional visible heading above the links. |
| ariaLabel | 否 | — | Navigation landmark name. Falls back to title, then the language pack. |
| scrollContainer | 否 | — | Scrollable element, selector or getter; omitted means window. |
| offset | 否 | 16 | Distance from the viewport's inner top edge to the heading, in px. Defaults to 16. |
| behavior | 否 | "smooth" | Explicit navigation motion. Defaults to smooth; reduced motion always uses instant. |
| history | 否 | "push" | Fragment history policy. Defaults to push; false disables URL writes and restoration. |

**items**

```ts
readonly QuireKitAnchorItem[]
```

```ts
readonly ({
  /** ID of the target heading or section element, without the leading hash. */
  id: string;
  /** Readable link text, also used as the accessible name. */
  label: string;
  /** Descendants in document reading order. */
  children?: undefined | readonly QuireKitAnchorItem[];
})[]
```

**title**

```ts
string | undefined
```

```ts
undefined | string
```

**ariaLabel**

```ts
string | undefined
```

```ts
undefined | string
```

**scrollContainer**

```ts
QuireKitAnchorContainer | undefined
```

```ts
undefined | string | HTMLElement | { (): HTMLElement | null | undefined; }
```

**offset**

```ts
number | undefined
```

```ts
undefined | number
```

**behavior**

```ts
"smooth" | "instant" | undefined
```

```ts
undefined | "smooth" | "instant"
```

**history**

```ts
false | "push" | "replace" | undefined
```

```ts
undefined | false | "push" | "replace"
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| change | 否 | — |  |
| navigate | 否 | — |  |

**change**

```ts
[id: string]
```

**navigate**

```ts
[item: QuireKitAnchorItem, event: MouseEvent]
```

#### Slots

无。

#### 公开实例成员

无。

#### 相关类型

```ts
type QuireKitAnchorItem = {
  /** ID of the target heading or section element, without the leading hash. */
  id: string;
  /** Readable link text, also used as the accessible name. */
  label: string;
  /** Descendants in document reading order. */
  children?: undefined | readonly QuireKitAnchorItem[];
};
```
