# 切片器与时间线

- Human documentation: [https://docs.univer.ai/zh-CN/guides/sheets/features/slicer](https://docs.univer.ai/zh-CN/guides/sheets/features/slicer)

- Agent Markdown: [https://docs.univer.ai/zh-CN/guides/sheets/features/slicer.md](https://docs.univer.ai/zh-CN/guides/sheets/features/slicer.md)

- Requested language: `zh-CN`

- Content language: `zh-CN`

- Documentation version: `1.3.0`

- Source: [sheets/features/slicer.zh-CN.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/slicer.zh-CN.mdx)

---

#### Package metadata

```json
{
  "preset": [
    {
      "client": "@univerjs/preset-sheets-advanced",
      "locale": "@univerjs/preset-sheets-advanced/locales/zh-CN",
      "style": "@univerjs/preset-sheets-advanced/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs-pro/sheets-slicer",
      "facade": "@univerjs-pro/sheets-slicer/facade"
    },
    {
      "client": "@univerjs-pro/sheets-slicer-ui",
      "locale": "@univerjs-pro/sheets-slicer-ui/locale/zh-CN",
      "style": "@univerjs-pro/sheets-slicer-ui/lib/index.css"
    }
  ],
  "license": true,
  "server": false
}
```

切片器可按源数据成员筛选表格、数据透视表和透视图。时间线用于筛选受支持的透视表原始日期字段，不支持表格列、文本字段、计算字段和派生分组字段。

## 接入配置

#### 插件模式

在现有的 [Sheets 配置](https://docs.univer.ai/zh-CN/guides/sheets/getting-started/installation.md)中加入以下内容，并配置[绘图支持](https://docs.univer.ai/zh-CN/guides/sheets/features/images.md)以及[表格](https://docs.univer.ai/zh-CN/guides/sheets/features/table.md)或[数据透视表](https://docs.univer.ai/zh-CN/guides/sheets/features/pivot-table.md)数据源。在创建工作簿前加载语言包并注册这些插件。

```package-install
npm install @univerjs-pro/sheets-slicer @univerjs-pro/sheets-slicer-ui
```

```ts
import { UniverSheetsSlicerPlugin } from '@univerjs-pro/sheets-slicer'
import { UniverSheetsSlicerUIPlugin } from '@univerjs-pro/sheets-slicer-ui'
import SheetsSlicerUILocale from '@univerjs-pro/sheets-slicer-ui/locale/zh-CN'
import { LocaleType } from '@univerjs/core'
import '@univerjs-pro/sheets-slicer/facade'
import '@univerjs-pro/sheets-slicer-ui/lib/index.css'

univerAPI.loadLocales(LocaleType.ZH_CN, SheetsSlicerUILocale)
univer.registerPlugin(UniverSheetsSlicerPlugin)
univer.registerPlugin(UniverSheetsSlicerUIPlugin)
```

#### 预设模式

高级预设已包含切片器和时间线的模型、UI 及 Facade API。将它与核心、绘图预设组合，并合并语言包。若已使用高级预设，把 `slicer` 选项合并到原配置，不要重复注册。客户端许可证配置见[使用许可证](https://docs.univer.ai/zh-CN/server/license.md)。

```package-install
npm install @univerjs/preset-sheets-core @univerjs/preset-sheets-drawing @univerjs/preset-sheets-advanced
```

```ts
import { LocaleType, mergeLocales } from '@univerjs/core'
import { UniverSheetsAdvancedPreset } from '@univerjs/preset-sheets-advanced'
import AdvancedLocale from '@univerjs/preset-sheets-advanced/locales/zh-CN'
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import CoreLocale from '@univerjs/preset-sheets-core/locales/zh-CN'
import { UniverSheetsDrawingPreset } from '@univerjs/preset-sheets-drawing'
import DrawingLocale from '@univerjs/preset-sheets-drawing/locales/zh-CN'
import { createUniver } from '@univerjs/presets'
import '@univerjs/preset-sheets-core/lib/index.css'
import '@univerjs/preset-sheets-drawing/lib/index.css'
import '@univerjs/preset-sheets-advanced/lib/index.css'

const { univerAPI } = createUniver({
  locale: LocaleType.ZH_CN,
  locales: {
    [LocaleType.ZH_CN]: mergeLocales(CoreLocale, DrawingLocale, AdvancedLocale),
  },
  presets: [
    UniverSheetsCorePreset({ container: 'app' }),
    UniverSheetsDrawingPreset(),
    UniverSheetsAdvancedPreset({ slicer: { maxMemberWindowSize: 200 } }),
  ],
})
```

使用 [Worker](https://docs.univer.ai/zh-CN/guides/sheets/getting-started/worker.md) 时，在高级预设中设置 `useWorker: true`，并在 Worker 中注册 `UniverSheetsAdvancedWorkerPreset()`，其中也包含切片器计算插件。

## 创建切片器

下面的示例使用活动工作表 I1 处的数据透视表，其源数据中包含名为 `Region` 的字段。通过 `getSourceFieldsInfo()` 获取原始字段的稳定 ID；不能将显示名称或报表字段 ID 传给 `newSlicer()`。

```ts
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook?.getActiveSheet()
if (!fWorkbook || !fWorksheet) throw new Error('No active worksheet')

const pivotTable = fWorkbook.getPivotTableByCell(
  fWorkbook.getId(),
  fWorksheet.getSheetId(),
  0,
  8,
)
const regionField = pivotTable?.getSourceFieldsInfo().find((field) => field.name === 'Region')
if (!pivotTable || !regionField) throw new Error('Region source field not found')

const slicer = await fWorksheet.insertSlicer(
  pivotTable.newSlicer(regionField.id)
    .setCaption(regionField.name)
    .setPosition('N2')
    .build(),
)
```

`pivotTable.newSlicer()` 会将构建器绑定到数据源。`build()` 只生成配置，`insertSlicer()` 才会创建控件。控件所在工作表可以与数据源工作表不同，但二者必须属于同一工作簿。若使用表格数据源，调用 `fWorksheet.newSlicer(columnId).setTableReference({ subUnitId, tableId })`，其中 `columnId` 为表格列的稳定 ID。

## 创建时间线

继续使用同一数据透视表，下面的示例要求存在名为 `Date` 的原始日期字段。`newTimeline()` 会验证数据源并拒绝不支持的字段。时间线范围 API 使用工作簿日期系统中的 Excel 序列值，不接受 JavaScript `Date` 对象。

```ts
const dateField = pivotTable.getSourceFieldsInfo().find((field) => field.name === 'Date')
if (!dateField) throw new Error('Date source field not found')

const timeline = await fWorksheet.insertTimeline(
  pivotTable.newTimeline(dateField.id)
    .setCaption(dateField.name)
    .setLevel(univerAPI.Enum.TimelineLevel.Month)
    .setPosition('N18')
    .build(),
)
```

## 查找控件与监听变化

在控件所在工作表上调用 `getSlicer(viewId)` / `getSlicers()` 和 `getTimeline(viewId)` / `getTimelines()`。`viewId` 是控件 `getId()` 返回的业务 ID，不是绘图 ID。

通过 `univerAPI.addEvent()` 监听 `SlicerAdded`、`SlicerChanged`、`SlicerRemoved`、`TimelineAdded`、`TimelineChanged` 和 `TimelineRemoved`。事件表示已提交的本地变化，不表示远程保存或渲染已完成。不再需要监听时，调用返回订阅的 `dispose()`。

API 参考：

- [FSheetSlicer](https://docs.univer.ai/zh-CN/reference/facade/sheet-slicer.md)
- [FSheetSlicerBuilder](https://docs.univer.ai/zh-CN/reference/facade/sheet-slicer-builder.md)
- [FSheetTimeline](https://docs.univer.ai/zh-CN/reference/facade/sheet-timeline.md)
- [FSheetTimelineBuilder](https://docs.univer.ai/zh-CN/reference/facade/sheet-timeline-builder.md)
- [FEventName](https://docs.univer.ai/zh-CN/reference/facade/events.md#univerjs-prosheets-slicer)

## 成员查询与共享筛选

使用 `setSelection()` 时传入有类型的源值：数字 `1`、字符串 `'1'` 和空白是不同成员，不要传显示标签或当前列表下标。筛选会作用于同一缓存的所有视图及已连接的报表。表格数据源会替换该列的筛选，保留其他列。调用 `clearFilter()` 可清除筛选。

```ts
import { FilterSelectionMode, RecordValueType } from '@univerjs/core'

const accepted = await slicer.setSelection({
  mode: FilterSelectionMode.Include,
  values: [{ type: RecordValueType.String, value: 'EMEA' }],
})
```

`getItems({ start, count })` 只查询一个窗口，不是全部源数据，也不会改变选择。默认查询 100 项，上限由 `maxMemberWindowSize` 控制，默认为正整数 200。分页时保留当前窗口之外的选择。`setConnections()` 会替换透视报表连接，可先用 `getConnectionCandidates()` 获取兼容报表。编辑操作需要相应的工作表权限，详见 [FSheetSlicer](https://docs.univer.ai/zh-CN/reference/facade/sheet-slicer.md)。
