# Slider

拖动滑块手柄或用方向键，调整一个数字或一个范围。

用滑块沿刻度选一个数字或一个范围，比如音量或价格区间，可以拖动滑块手柄，也可以用方向键。

<ComponentExample
  name="slider/basic"
  inspect
  caption="拖动滑块手柄，或者聚焦它并用方向键，来调整 Volume。"
/>

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

## 组合
用下面的组合构建 `Slider`：

```text
Slider
├── SliderValue
└── SliderControl
    └── SliderTrack
        ├── SliderIndicator
        └── SliderThumb
```

控件处理轨道周围的按压。每个值在轨道上放一个滑块手柄。

- **Slider** 持有值，是包住滑块手柄的分组。
- **SliderControl** 是按压落下的地方。按压它会移动最近的滑块手柄并开始拖动。在细轨道周围给它一些高度。
- **SliderTrack** 是滑块手柄移动的轨道。滑块手柄和指示器用内联样式按它的百分比定位，所以要给它尺寸。它是定位的盒子。
- **SliderIndicator** 填充轨道直到单个滑块手柄，或者在范围中填充第一个和最后一个滑块手柄之间。
- **SliderThumb** 是你拖动的东西。给每个滑块手柄一个尺寸。
- **SliderValue** 显示格式化后的值，范围两端用连接号（en dash）连接。它是可选的。

每个滑块手柄在内部渲染一个视觉上隐藏的 `<input type="range">`。获得焦点的是这个输入框，所以手机上的屏幕阅读器用它自己的手势来调整。用 `:has(:focus-visible)` 给滑块手柄设置焦点样式。滑块还渲染一个隐藏的输入框，供表单提交。

单个滑块手柄由 `Field` 里的 `FieldLabel` 命名，或者由滑块手柄上的 `aria-label` 命名。在范围里，给每个滑块手柄自己的 `aria-label`，比如“Minimum price”，并在滑块上用 `FieldLabel` 或 `aria-label` 给分组命名。

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

```vue
<script setup lang="ts">
import {
  Slider,
  SliderValue,
  SliderControl,
  SliderTrack,
  SliderIndicator,
  SliderThumb,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Slider :default-value="50">
    <SliderValue />
    <SliderControl>
      <SliderTrack>
        <SliderIndicator />
        <SliderThumb aria-label="Volume" />
      </SliderTrack>
    </SliderControl>
  </Slider>
</template>
```

## 范围
传入数组表示范围，然后为每个数字渲染一个滑块手柄。给每个滑块手柄自己的 `index`（从 0 开始）和名称，比如“Minimum price”。指示器填充第一个和最后一个滑块手柄之间的空间，`FieldLabel` 给分组命名。

```vue title="range.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Field>
    <Slider
      :default-value="[25, 50]"
      :step="5"
      :format="{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }"
    >
      <div data-slot="row">
        <FieldLabel>Price</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb :index="0" aria-label="Minimum price" />
          <SliderThumb :index="1" aria-label="Maximum price" />
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

移动 Price 的任意一端。滑块手柄保持顺序。

## 多个滑块手柄
任意数量的滑块手柄都以同样的方式工作。它们永远不会互相越过，按压轨道会移动最近的那个。

```vue title="multiple.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"

const thumbs = ["Low", "Medium", "High"]
</script>

<template>
  <Field>
    <Slider
      :default-value="[10, 20, 70]"
      :step="10"
      :format="{ style: 'unit', unit: 'percent' }"
    >
      <div data-slot="row">
        <FieldLabel>Alert thresholds</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb
            v-for="(label, index) in thumbs"
            :key="label"
            :index="index"
            :aria-label="label"
          />
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

分别调整 Low、Medium 和 High，不会把一个移过另一个。

## 垂直
设置 `orientation="vertical"` 并给滑块一个高度。底部是最小值，ArrowUp 增加数值，每个部件都会带上 `data-orientation`，所以可以用 `[data-orientation="vertical"]` 给垂直轴设置样式。

```vue title="vertical.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
} from "@ui-sdk/vue/slider"

const channels = [
  { label: "Bass", value: 50 },
  { label: "Treble", value: 25 },
]
</script>

<template>
  <div data-slot="row">
    <Field v-for="channel in channels" :key="channel.label">
      <Slider orientation="vertical" :default-value="channel.value">
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
      </Slider>
      <FieldLabel>{{ channel.label }}</FieldLabel>
    </Field>
  </div>
</template>
```

向上或向下拖动，或者用方向键，来调整 Bass 和 Treble。

## 字段
把滑块放进 `Field`。标签给滑块手柄命名，描述解释它，`SliderValue` 在标签旁边显示值。屏幕阅读器不会播报 `SliderValue` 的变化，因为滑块手柄已经说出了它的值。

```vue title="field.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Field>
    <Slider
      :default-value="0.3"
      :format="{ style: 'percent' }"
      :min="0"
      :max="1"
      :step="0.01"
    >
      <div data-slot="row">
        <FieldLabel>Volume</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
    <FieldDescription>How loud notifications play.</FieldDescription>
  </Field>
</template>
```

点击 Volume 标签来聚焦滑块手柄，然后用方向键改变值。

## 禁用
设置 `disabled`。禁用的滑块不能获得焦点，也不能移动，并且不会被提交。包住它的禁用 `<fieldset>` 也会禁用它。

```vue title="disabled.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Field>
    <Slider :default-value="50" disabled>
      <div data-slot="row">
        <FieldLabel>Brightness</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
    <FieldDescription>Managed by your organization.</FieldDescription>
  </Field>
</template>
```

Brightness 保留它的值，但不能被聚焦或拖动。

## 受控
绑定 `v-model:value`，或者传入 `value` 并处理 `@value-change`，来控制滑块。值保持它的形状：数字仍然是数字，数组仍然是数组。每次变更都带一个[原因](https://ui-sdk.cn/docs/vue/components/slider#reasons)，比如 `drag`、`track-press` 或 `step-key`，`details.thumb` 说明哪个滑块手柄移动了。调用 `details.cancel()` 保留当前值。

```vue title="controlled.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const value = ref([0.3, 0.7])
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="value = [0.3, 0.7]">Reset</button>
    </div>
    <Field>
      <Slider
        v-model:value="value"
        @value-change="
          (next, details) => log(`${next.join(' – ')} (${details.reason})`)
        "
        :min="0"
        :max="1"
        :step="0.1"
      >
        <div data-slot="row">
          <FieldLabel>Temperature</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb :index="0" aria-label="Minimum temperature" />
            <SliderThumb :index="1" aria-label="Maximum temperature" />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </Field>
  </div>
</template>
```

拖动 Temperature 的任意一个滑块手柄，记录范围和它的原因。Reset 从外部设置值。

## 步进与边界
`min` 和 `max` 设置边界，默认是 0 和 100；`step` 设置一次步进移动多远，从 `min` 开始计算。小数步进避免浮点漂移，所以 0.1 的步进可以干净地到达 0.3。当从 `min` 出发的步进落不到 `max` 上时，它下方的最高步进位置就是终点。

```vue title="step.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <div data-slot="stack">
    <Field>
      <Slider
        :default-value="2010"
        :min="1990"
        :max="2030"
        :step="5"
        :format="{ useGrouping: false }"
      >
        <div data-slot="row">
          <FieldLabel>Year</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
        <div data-slot="ticks" aria-hidden="true">
          <span v-for="tick in 9" :key="tick" />
        </div>
      </Slider>
    </Field>
    <Field>
      <Slider :default-value="0.5" :min="0" :max="1" :step="0.05">
        <div data-slot="row">
          <FieldLabel>Opacity</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
        <div data-slot="ticks" aria-hidden="true">
          <span v-for="tick in 21" :key="tick" />
        </div>
      </Slider>
    </Field>
  </div>
</template>
```

以 5 为步进移动 Year，以 0.05 为步进移动 Opacity。

## 大步进
方向键移动一个步进。Page Up、Page Down 和 Shift 加方向键按 `large-step` 移动，除非另行设置，它是十个步进。Home 和 End 跳到边界。

```vue title="large-step.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Field>
    <Slider
      :default-value="100"
      :min="25"
      :max="400"
      :large-step="25"
      :format="{ style: 'unit', unit: 'percent' }"
    >
      <div data-slot="row">
        <FieldLabel>Zoom</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

聚焦 Zoom，按方向键移动 1%，然后按 Page Up、Page Down 或 Shift 加方向键移动 25%。

## 滑块手柄之间的距离
设置 `min-steps-between-thumbs`，让相邻的滑块手柄相隔这么多步进。滑块手柄会在邻居那里停下，Home 和 End 也只把它移动到邻居允许的位置。

```vue title="min-steps.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"

const time = (minutes: number) =>
  `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}`
</script>

<template>
  <Field>
    <Slider
      :default-value="[540, 1020]"
      :min="0"
      :max="1440"
      :step="15"
      :min-steps-between-thumbs="16"
      :format="time"
    >
      <div data-slot="row">
        <FieldLabel>Opening hours</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb :index="0" aria-label="Opens" />
          <SliderThumb :index="1" aria-label="Closes" />
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

移动 Opening hours 的任意一端。滑块手柄至少相隔四小时。

## 格式化与 locale
`format` 接受 `Intl.NumberFormat` 选项，比如 `{ style: "currency", currency: "USD" }` 或 `{ style: "percent" }`，也接受一个作用于值的函数。它决定 `SliderValue` 显示什么，以及屏幕阅读器为每个滑块手柄播报什么，而值本身仍是普通数字。`locale` 设置分隔符、数字和符号的位置。不设置时，页面可交互后，滑块使用页面的 `lang`，或者浏览器的语言。在此之前，服务端标记使用英语，所以它永远不会和客户端不一致。

```vue title="format.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"

const sliders = [
  {
    label: "Budget",
    defaultValue: 40,
    max: 100,
    step: 1,
    format: { style: "currency", currency: "USD", maximumFractionDigits: 0 },
  },
  {
    label: "Opacity",
    defaultValue: 0.6,
    max: 1,
    step: 0.01,
    format: { style: "percent" },
  },
  {
    label: "Weight",
    defaultValue: 20,
    max: 50,
    step: 0.5,
    format: { style: "unit", unit: "kilogram" },
  },
  {
    label: "Duration",
    defaultValue: 90,
    max: 600,
    step: 15,
    format: (seconds: number) =>
      `${Math.floor(seconds / 60)} min ${seconds % 60} s`,
  },
  {
    label: "Preis",
    defaultValue: 40,
    max: 100,
    step: 1,
    format: { style: "currency", currency: "EUR" },
    locale: "de-DE",
  },
] satisfies {
  label: string
  defaultValue: number
  max: number
  step: number
  format: Intl.NumberFormatOptions | ((value: number) => string)
  locale?: string
}[]
</script>

<template>
  <div data-slot="stack">
    <Field v-for="slider in sliders" :key="slider.label">
      <Slider
        :default-value="slider.defaultValue"
        :max="slider.max"
        :step="slider.step"
        :format="slider.format"
        :locale="'locale' in slider ? slider.locale : undefined"
      >
        <div data-slot="row">
          <FieldLabel>{{ slider.label }}</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </Field>
  </div>
</template>
```

调整 Budget、Opacity、Weight、Duration 和 Preis，比较货币、百分比、单位、自定义函数和德语格式。

## 提交时保存
`@value-change` 在拖动的每一步运行。`@value-commit` 只运行一次，在改变值的交互结束时：指针抬起、按键松开，或者屏幕阅读器完成调整。用提交回调在每次交互后保存一次。没有改变值的按压不会提交任何东西。

```vue title="commit.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
import { useLog } from "./log"

const log = useLog()
</script>

<template>
  <Field>
    <Slider
      @value-commit="
        (value, details) => log(`Saved ${value} (${details.reason})`)
      "
      :default-value="50"
    >
      <div data-slot="row">
        <FieldLabel>Brightness</FieldLabel>
        <SliderValue />
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb />
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

拖动 Brightness 再松开，或者按方向键。松开时控制台只记录一次值。

## 控制器
来自 `createSliderController()` 的控制器可以从任何地方用 `setValue()` 移动滑块，用 `getValue()` 读取它，用 `focus()` 聚焦一个滑块手柄。通过它设置的值会被限制在边界内、吸附到步进并排序，并以 `imperative` 原因报告。

```vue title="controller.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  createSliderController,
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
import { useLog } from "./log"

const log = useLog()
const volume = createSliderController<number>()
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="volume.setValue(0)">Mute</button>
      <button type="button" @click="volume.setValue(volume.getValue() + 10)">
        Louder
      </button>
      <button type="button" @click="log(`Volume is ${volume.getValue()}`)">
        Read
      </button>
      <button type="button" @click="volume.focus()">Focus</button>
    </div>
    <Field>
      <Slider
        :default-value="40"
        :controller="volume"
        @value-change="
          (value, details) => log(`Volume ${value} (${details.reason})`)
        "
      >
        <div data-slot="row">
          <FieldLabel>Volume</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </Field>
  </div>
</template>
```

用 Mute、Louder 和 Focus 从滑块外部操作 Volume。控制台用 imperative 原因记录每次变更，Read 记录值。

## 表单
表单看到的是滑块旁边的一个隐藏输入框。它接收滑块的 `name`、`form` 和 `disabled`，所以 `FormData`、`form.reset()`、禁用的 `<fieldset>` 和浏览器的恢复都能工作。

- **提交：** 单个滑块手柄在 `name` 下提交它的数字，比如 `40`。范围提交 `"start/end"`，比如 `200/800`。没有名称时，它不提交任何东西。
- **重置：** 表单重置把它恢复到 `default-value`，原因为 `reset`。
- **从别处加入表单：** 把 `form` 设为某个表单的 id。

`required` 会加上 `data-required`。滑块总是有值，所以它永远不会阻止表单提交。

```vue title="form.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
import { useId } from "vue"
import { useLog } from "./log"

const log = useLog()
const form = useId()

function onSubmit(event: Event) {
  const data = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(`Submitted ${data.join(", ")}`)
}
</script>

<template>
  <div data-slot="stack">
    <form :id="form" data-slot="stack" @submit.prevent="onSubmit">
      <Field>
        <Slider name="price" :default-value="[200, 800]" :max="1000" :step="10">
          <div data-slot="row">
            <FieldLabel>Price</FieldLabel>
            <SliderValue />
          </div>
          <SliderControl>
            <SliderTrack>
              <SliderIndicator />
              <SliderThumb :index="0" aria-label="Minimum price" />
              <SliderThumb :index="1" aria-label="Maximum price" />
            </SliderTrack>
          </SliderControl>
        </Slider>
      </Field>
      <Field>
        <Slider name="rating" :default-value="3" :min="1" :max="5">
          <div data-slot="row">
            <FieldLabel>Minimum rating</FieldLabel>
            <SliderValue />
          </div>
          <SliderControl>
            <SliderTrack>
              <SliderIndicator />
              <SliderThumb />
            </SliderTrack>
          </SliderControl>
        </Slider>
      </Field>
    </form>
    <Field>
      <Slider
        name="distance"
        :form="form"
        :default-value="25"
        :max="100"
        :step="5"
        :format="{ style: 'unit', unit: 'kilometer' }"
      >
        <div data-slot="row">
          <FieldLabel>Distance</FieldLabel>
          <SliderValue />
        </div>
        <SliderControl>
          <SliderTrack>
            <SliderIndicator />
            <SliderThumb />
          </SliderTrack>
        </SliderControl>
      </Slider>
    </Field>
    <div data-slot="row">
      <button type="submit" :form="form" data-variant="solid">Save</button>
      <button type="reset" :form="form">Reset</button>
    </div>
  </div>
</template>
```

调整各个筛选器并按 Save，记录提交的值。Distance 位于表单之外，通过 id 加入表单。Reset 恢复默认值。

## 只读
设置 `read-only`，让滑块保持可聚焦、可提交，同时拖动、按键和屏幕阅读器的调整都不会改变它的值。

```vue
<Field>
  <FieldLabel>Storage</FieldLabel>
  <Slider name="storage" :default-value="50" read-only>
    <SliderControl>
      <SliderTrack>
        <SliderIndicator />
        <SliderThumb />
      </SliderTrack>
    </SliderControl>
  </Slider>
  <FieldDescription>Set by your plan.</FieldDescription>
</Field>
```

## 自定义渲染
每个部件都接受一个 `render` 插槽，它接收要绑定的 props 和部件的状态；默认插槽也会收到状态，比如滑块手柄是否正在被拖动、它的 `thumbValue`，以及它沿轨道的位置 `percent`。这里滑块手柄渲染一个 `span`，它的默认插槽添加一个显示其值的气泡，`SliderValue` 的默认插槽添加一个百分号。

```vue title="render.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  Slider,
  SliderControl,
  SliderIndicator,
  SliderThumb,
  SliderTrack,
  SliderValue,
} from "@ui-sdk/vue/slider"
</script>

<template>
  <Field>
    <Slider :default-value="60">
      <div data-slot="row">
        <FieldLabel>Brightness</FieldLabel>
        <SliderValue v-slot="{ state }">{{ state.text }}%</SliderValue>
      </div>
      <SliderControl>
        <SliderTrack>
          <SliderIndicator />
          <SliderThumb>
            <template #render="{ props, children }">
              <span v-bind="props"><component :is="children" /></span>
            </template>
            <template #default="{ state }">
              <span data-slot="output">{{ state.thumbValue }}</span>
            </template>
          </SliderThumb>
        </SliderTrack>
      </SliderControl>
    </Slider>
  </Field>
</template>
```

聚焦或拖动 Brightness 的滑块手柄，在上方显示它的值。

渲染约定见[部件与组合](/docs/vue/parts-and-composition)，每个部件的字段见[状态](https://ui-sdk.cn/docs/vue/components/slider#state)。

## 样式
部件没有样式，除了它们需要的位置：滑块手柄和指示器会以内联样式获得 `position: absolute` 和它们在轨道上的百分比位置。给控件在细轨道周围一些高度，给轨道尺寸和背景，给每个滑块手柄尺寸。获得焦点的是滑块手柄里的 range 输入框，所以用 `:has(:focus-visible)` 在滑块手柄上绘制焦点环，并用 `data-dragging` 给拖动设置样式。

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

指示器和滑块手柄还会写入 CSS 变量，供其他应该跟随它们的东西使用，比如滑块手柄上方的标签。

### SliderIndicator
- `--slider-indicator-start`: Where the indicator starts along the track, as a percentage. 0% for a single thumb.
- `--slider-indicator-size`: How much of the track the indicator covers, as a percentage.

### SliderThumb
- `--slider-thumb-position`: Where the thumb sits along the track, as a percentage from the start. Use it for a label that follows the thumb.

## 数据属性
### Slider
`[data-slot="slider"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-dragging`: Present while a thumb is being dragged.

### SliderValue
`[data-slot="slider-value"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-dragging`: Present while a thumb is being dragged.

### SliderControl
`[data-slot="slider-control"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-dragging`: Present while a thumb is being dragged.

### SliderTrack
`[data-slot="slider-track"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-dragging`: Present while a thumb is being dragged.

### SliderIndicator
`[data-slot="slider-indicator"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-dragging`: Present while a thumb is being dragged.

### SliderThumb
`[data-slot="slider-thumb"]`

- `data-orientation` (`horizontal`, `vertical`): The slider's axis.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-index` (`0`, `1`): Which value the thumb shows, from 0.
- `data-dragging`: Present while this thumb is being dragged.

## API 参考
属性与下面相同，回调是事件。

### Slider
- `value?` (`Value`): The value: a number for one thumb, or an array with one number per thumb, like `[20, 80]` for a range. Pass it to control the slider.
- `defaultValue?` (`Value`): The value at first, when uncontrolled. A form reset returns to it.
- `@value-change` (`((value: Value, details: SliderValueChangeDetails) => void)`): Runs while the value changes: on every step of a drag or a key. `details.thumb` says which thumb moved, and `details.cancel()` stops it.
- `@value-commit` (`((value: Value, details: SliderValueCommitDetails) => void)`): Runs once an interaction that changed the value ends: the pointer lifts, the key comes up, or a screen reader adjusts it. For saving.
- `min?` (`number`): The lowest value.
- `max?` (`number`): The highest value. When the steps from `min` don't land on it, the highest step below it is the end.
- `step?` (`number`): How far one step moves, from `min`.
- `largeStep?` (`number`): How far Page Up, Page Down and Shift with an arrow key move.
- `minStepsBetweenThumbs?` (`number`): How many steps apart neighbouring thumbs stay. Thumbs never pass each other.
- `orientation?` (`"horizontal" | "vertical"`): The slider's axis. Vertical sliders grow upward.
- `disabled?` (`boolean`): Disables it like a native control: thumbs can't be focused or moved, and nothing is submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops drags, keys and screen reader adjustments from changing it.
- `required?` (`boolean`): Marks it required, with `data-required`. A slider always has a value, so it never blocks a form.
- `name?` (`string`): The name it submits under: the number, or a range as `"start/end"`. Without one, it submits nothing.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `format?` (`NumberFormat`): How values read, for screen readers and `SliderValue`: `Intl.NumberFormat` options, like `{ style: "currency", currency: "EUR" }`, or a function of the value.
- `locale?` (`string`): The locale values 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.
- `controller?` (`{ getValue: () => Value; setValue(value: Value, options?: SliderChangeOptions): boolean; focus: (thumb?: number) => void; }`): Moves the slider from anywhere. Create one with `createSliderController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### SliderThumb
- `index?` (`number`): Which value the thumb shows, from 0. Give each thumb of a range its own.

### 状态
渲染插槽和默认插槽会收到什么。每个部件都会收到滑块的状态。

- `value` (`number | number[]`): The value: a number, or one number per thumb.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but drags and keys don't change it.
- `required` (`boolean`): Whether it's marked required.
- `dragging` (`boolean`): Whether a thumb is being dragged.
- `orientation` (`"horizontal" | "vertical"`): The slider's axis.

滑块手柄会增加自己的字段，并用自己的 `thumbValue` 代替整个 `value`，所以只有自己的值移动时滑块手柄才会重新渲染：

- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but drags and keys don't change it.
- `required` (`boolean`): Whether it's marked required.
- `dragging` (`boolean`): Whether a thumb is being dragged.
- `orientation` (`"horizontal" | "vertical"`): The slider's axis.
- `index` (`number`): Which value the thumb shows.
- `thumbValue` (`number`): The thumb's own value.
- `percent` (`number`): Where the thumb sits, from 0 to 100.

`SliderValue` 增加格式化后的文本：

- `value` (`number | number[]`): The value: a number, or one number per thumb.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but drags and keys don't change it.
- `required` (`boolean`): Whether it's marked required.
- `dragging` (`boolean`): Whether a thumb is being dragged.
- `orientation` (`"horizontal" | "vertical"`): The slider's axis.
- `text` (`string`): The formatted value, a range joined with an en dash.

### 原因
`details.reason` 说明值为什么变化。

- `track-press` (`PointerEvent`): A press on a slider's track or an area's surface moved the nearest thumb there.
- `drag` (`PointerEvent`): A slider thumb or a resize handle was dragged, or an item was dragged to a new place in a list.
- `step-key` (`KeyboardEvent`): Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
- `accessibility-adjust` (`Event`): A screen reader's adjust gesture, like a swipe up or down on a slider.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createSliderController()` 创建一个，并作为 `controller` 传入。

`setValue()` 接受可选的 `{ reason, event }`，像拖动一样运行变更回调，并在变更被取消时返回 `false`。

- `getValue()` (`() => Value`): The value: a number, or one number per thumb.
- `setValue(value, options?)` (`(value: Value, options?: SliderChangeOptions | undefined) => boolean`): Sets the value, as a user would. It's clamped, snapped to the step and sorted.
- `focus(thumb?)` (`(thumb?: number | undefined) => void`): Moves focus to a thumb, the first by default.

### 事件
事件先收到新值，然后收到详情。`v-model` 只在变更事件未被取消时更新。

| 绑定            | 所属     | 收到                                                           |
| --------------- | -------- | -------------------------------------------------------------- |
| `v-model:value` | `Slider` | 值：一个数字，或者每个滑块手柄一个数字                         |
| `@value-change` | `Slider` | `(value, details)`：新值、[原因](https://ui-sdk.cn/docs/vue/components/slider#reasons)和 `details.thumb`   |
| `@value-commit` | `Slider` | `(value, details)`：交互结束时的值、它的原因和 `details.thumb` |

## 无障碍
滑块遵循 [WAI-ARIA 滑块模式](https://www.w3.org/WAI/ARIA/apg/patterns/slider/)；范围则遵循[多滑块手柄滑块模式](https://www.w3.org/WAI/ARIA/apg/patterns/slider-multithumb/)。每个滑块手柄都是原生 range 输入框，由 `FieldLabel` 或它自己的 `aria-label` 命名，滑块是包住它们的分组。

### 键盘
聚焦一个滑块手柄即可使用这些按键。Tab 按顺序在多个滑块手柄之间移动。

| 按键                                       | 移动滑块手柄                                                |
| ------------------------------------------ | ----------------------------------------------------------- |
| ArrowRight or ArrowUp                      | 向上一个 `step`。在从右到左（RTL）中，ArrowRight 向下移动。 |
| ArrowLeft or ArrowDown                     | 向下一个 `step`。在从右到左（RTL）中，ArrowLeft 向上移动。  |
| Page Up, Page Down, or Shift with an arrow | 按 `large-step` 移动，默认十个步进。                        |
| Home or End                                | 移到最小值或最大值，或者邻居滑块手柄允许的最远位置。        |

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

**Keyboard**

- Starts at its default value.
- ArrowRight and ArrowUp increase it by one step.
- ArrowLeft and ArrowDown decrease it by one step.
- Page Up and Page Down move by the large step.
- Shift with an arrow key moves by the large step.
- Home and End go to the minimum and the maximum.
- A value never goes past the bounds.
- Tab moves through the thumbs in order.
- Home and End move a range thumb as far as its neighbour.
- A range thumb stops at its neighbour.
- A canceled change keeps the value.
- A controlled slider follows its value.

**Pointer**

- Pressing the track moves the thumb there.
- Pressing the track focuses the thumb.
- Pressing the track shows no focus ring, as a native range doesn't.
- Pressing a range's track moves the nearest thumb.
- Dragging a thumb follows the pointer.
- Grabbing a thumb off center doesn't move it.
- Dragging past the end stops at the bound.
- Dragging continues outside the slider.
- Dragging right from stacked thumbs moves the upper one.
- The value commits once, when the pointer lifts.
- A screen reader's adjustment reaches the form as one input and one change.
- A browser agent's snapshot gives the thumb a ref, and filling it sets the value.
- A drag sends input as it moves, and change once when the pointer lifts.
- Pressing a thumb without moving commits nothing.
- A press on the track commits.
- The thumb sits at its value along the track.

**Vertical**

- It says it's vertical.
- ArrowUp increases it and ArrowDown decreases it.
- The bottom is the minimum.
- Dragging up increases it.

**Value and state**

- The value part shows the value, and a range joined with a dash.
- The value reads in the format and the locale.
- A disabled slider can't be focused or changed.
- Its parts say when it's dragged.
- A single slider submits its value under its name.

Runs in React、Vue 和 web components.

模式之外：

- A dragged range thumb stops at its neighbour, as the APG's multi-thumb slider says.
- Each range thumb's own range ends at its neighbour.
- A form reset returns every slider to its default.
- Holding an arrow key commits once, when the key comes up.
- Dragging left from stacked thumbs moves the lower one.
- Pressing the track beside stacked thumbs moves the one on that side.
- A key moves a thumb as close to its neighbour as the minimum distance allows.
- Touch drags on the control never scroll the page.
- A range submits one start/end value.
- Clicking a range's label focuses its first thumb.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while moving to a slider with a keyboard.
- A range thumb announces how far it can go and its formatted value.

Runs in React、Vue 和 web components.
