# useTableSortable

## 使用方法

把排序状态和它的回调放进配置对象，交给 `useTableSortable`。它返回的插件通过 `plugins` 属性传给 `Table`。

```ts
import { useTableSortable } from '@astryx-vue/core/Table'
```

## 示例

### useTableSortable —— 可排序的列

列可以排序的表格。点表头就在升序和降序之间切换。

```vue
<script setup lang="ts">
import type { TableColumn } from '@astryx-vue/core/Table'
import { pixel, proportional, Table, useTableSortable, useTableSortableState } from '@astryx-vue/core/Table'

interface Employee extends Record<string, unknown> {
  id: string
  name: string
  email: string
  role: string
  age: number
}

const employees: Employee[] = [
  { id: '1', name: 'Alice', email: 'alice@example.com', role: 'Engineer', age: 32 },
  { id: '2', name: 'Bob', email: 'bob@example.com', role: 'Designer', age: 28 },
  { id: '3', name: 'Charlie', email: 'charlie@example.com', role: 'Manager', age: 45 },
  { id: '4', name: 'Diana', email: 'diana@example.com', role: 'Engineer', age: 37 },
  { id: '5', name: 'Eve', email: 'eve@example.com', role: 'Admin', age: 29 },
]

const columns: TableColumn<Employee>[] = [
  { key: 'name', header: 'Name', width: proportional(1), sortable: true },
  { key: 'email', header: 'Email', width: proportional(2), sortable: true },
  { key: 'role', header: 'Role', width: proportional(1), sortable: true },
  { key: 'age', header: 'Age', width: pixel(80), sortable: true },
]

const { sortedData, sortConfig } = useTableSortableState<Employee>({
  data: employees,
  defaultSort: [{ sortKey: 'name', direction: 'ascending' }],
})
const sortablePlugin = useTableSortable<Employee>(sortConfig)
</script>

<template>
  <Table
    :data="sortedData"
    :columns="columns"
    id-key="id"
    :plugins="{ sortable: sortablePlugin }"
  />
</template>
```

## 属性

配置对象是 `MaybeRefOrGetter`：传一个 getter 或 ref，插件才会跟着当前排序状态走。

## 参数

| 参数 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `sort` | `TableSortState` | — | 当前排序状态：一个有序数组，每项是 `{ sortKey, direction }`。第一项是主排序，后面的是次级排序。空数组表示不排序。方向写全词：`'ascending'` / `'descending'`，不是 `'asc'` / `'desc'`。 |
| `onSortChange` | `(sort: TableSortState) => void` | — | 用户点表头改变排序时调用，参数是下一个排序状态。 |
| `allowUnsortedState` | `boolean` | `true` | 是否允许转回不排序。为 true 时依次是升序、降序、不排序；为 false 时是升序、降序、升序。 |
| `isMultiSortEnabled` | `boolean` | `false` | 允许按住 Shift 再点来加多列排序。普通点击仍然整体替换排序状态。 |

## 返回值

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `sortFor` | `(column: TableColumn) => TableSortContribution \| null` | 给出某个表头该用的排序信息；这一列不能排序时返回 `null`。列上写了 `sortable: true` 或 `sortable: { sortKey }` 才算能排序。 |
| `sortFor().direction` | `'ascending' \| 'descending' \| null` | 这一列当前的方向，没有排序时是 `null`。 |
| `sortFor().rank` | `number \| null` | 多列排序时它排第几（从 1 计），显示在箭头旁边。只排了一列时是 `null`。 |
| `sortFor().label` | `string` | 表头按钮的本地化无障碍名称，例如「按名称排序。改为降序」。 |
| `sortFor().onClick` | `(event: MouseEvent) => void` | 点击处理函数。普通点击整体替换排序状态；按住 Shift 点击会加上、改向或去掉这一列。Shift 从事件上读。 |
