# 轻提示

## 使用方法

`Toast` 是一种不打断操作的轻量反馈，用来确认操作结果或提示状态变化，数秒后自动消失。使用时，在应用根节点放置一次 `ToastViewport`，然后在任意组件中调用 `useToast` 弹出提示。

在触摸屏上，朝提示所在的那条边滑动可以关掉它：贴在屏幕下方的向下滑，贴在上方的向上滑。横向滑动留给页面滚动。滑在按钮或链接上时不关，那一下属于控件自己。鼠标拖动不会关掉提示。

```vue
<script setup lang="ts">
import { ToastViewport, useToast } from '@astryx-vue/core/Toast'

const toast = useToast()

toast({ body: '操作成功', type: 'success' })
</script>

<template>
  <div>
    <button @click="toast({ body: '已保存' })">
      保存
    </button>
    <ToastViewport />
  </div>
</template>
```

### 结构

- **正文**: 说明发生了什么，或用户该知道什么的主要消息。
- **尾部内容**: 正文后面的操作，比如撤销按钮或链接。
- **关闭按钮**: 让用户在自动隐藏之前手动关掉这条提示的按钮。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 将 `ToastViewport` 放在应用顶层，确保提示能覆盖所有页面，位置与堆叠顺序也保持一致。 |
| 推荐 | 错误信息使用 `type="error"`，组件会自动应用 `role="alert"`，让屏幕阅读器优先播报。 |
| 推荐 | 保持提示文本简洁，一行说明操作结果即可，用户通常只会扫一眼。 |
| 避免 | 避免同时弹出大量提示：信息过载会让用户忽略真正重要的内容，必要时合并为一条。 |
| 避免 | 避免用 Toast 替代需要用户确认的对话框：提示会自动消失，用户可能来不及做出响应。 |

## 示例

### 操作

常驻通知的末尾可以放按钮或链接，用来撤销删除，或者打开报告。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { Link } from '@astryx-vue/core/Link'
import { VStack } from '@astryx-vue/core/Stack'
import { Toast, ToastViewport, useToast } from '@astryx-vue/core/Toast'

const toast = useToast()
</script>

<template>
  <VStack :gap="3">
    <Toast :is-auto-hide="false" body="Item deleted" type="info">
      <template #end>
        <Button
          label="Undo"
          size="sm"
          variant="secondary"
          @click="toast({ body: 'Undo successful', type: 'info' })"
        />
      </template>
    </Toast>
    <Toast :is-auto-hide="false" body="Your report is ready." type="info">
      <template #end>
        <Link href="#" has-underline>
          View report
        </Link>
      </template>
    </Toast>
    <ToastViewport />
  </VStack>
</template>
```

### 去重

uniqueID 把重复通知收成一条。ignore 保留第一条，overwrite 用新内容替换，适合进度百分比。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { HStack, VStack } from '@astryx-vue/core/Stack'
import { Toast, ToastViewport, useToast } from '@astryx-vue/core/Toast'

const toast = useToast()
</script>

<template>
  <VStack :gap="3">
    <Toast :is-auto-hide="false" body="You are offline" type="info" />
    <HStack align="center" :gap="3">
      <Button
        label="Offline (ignore)"
        size="sm"
        variant="secondary"
        @click="toast({ body: 'You are offline', uniqueID: 'offline', collisionBehavior: 'ignore', isAutoHide: false })"
      />
      <Button
        label="Progress (overwrite)"
        size="sm"
        variant="secondary"
        @click="toast({ body: `Uploading… ${Math.floor(Math.random() * 100)}%`, uniqueID: 'upload-progress', collisionBehavior: 'overwrite', isAutoHide: false })"
      />
    </HStack>
    <ToastViewport />
  </VStack>
</template>
```

### 关闭

useToast 返回的函数可以关掉那一条通知，适合耗时操作自己收尾。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { HStack, VStack } from '@astryx-vue/core/Stack'
import { Toast, ToastViewport, useToast } from '@astryx-vue/core/Toast'
import { ref } from 'vue'

const toast = useToast()
const dismiss = ref<(() => void) | null>(null)

function show(): void {
  dismiss.value = toast({ body: 'Uploading file…', isAutoHide: false })
}

function dismissFromCode(): void {
  dismiss.value?.()
  dismiss.value = null
}
</script>

<template>
  <VStack :gap="3">
    <Toast :is-auto-hide="false" body="Uploading file…" type="info" />
    <HStack align="center" :gap="3">
      <Button label="Show toast" size="sm" variant="secondary" @click="show" />
      <Button label="Dismiss via code" size="sm" variant="ghost" @click="dismissFromCode" />
    </HStack>
    <ToastViewport />
  </VStack>
</template>
```

### 堆叠

通知纵向叠放，进入和离开都有动画。再点一次会再排上一条。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { VStack } from '@astryx-vue/core/Stack'
import { Toast, ToastViewport, useToast } from '@astryx-vue/core/Toast'
import { ref } from 'vue'

const messages = [
  { body: 'Changes saved.', type: 'info' as const },
  { body: 'Failed to upload file.', type: 'error' as const },
  { body: 'Message sent to Sarah Chen.', type: 'info' as const },
]

const toast = useToast()
const count = ref(0)

function show(): void {
  const message = messages[count.value % messages.length]
  count.value += 1
  toast(message)
}
</script>

<template>
  <VStack :gap="3">
    <Toast
      v-for="message in messages"
      :key="message.body"
      :is-auto-hide="false"
      :body="message.body"
      :type="message.type"
    />
    <Button label="Show toast" size="sm" variant="secondary" @click="show" />
    <ToastViewport />
  </VStack>
</template>
```

### 类型

信息与错误并排。信息会自己消失，错误一直留到被关掉。

```vue
<script setup lang="ts">
import { Button } from '@astryx-vue/core/Button'
import { VStack } from '@astryx-vue/core/Stack'
import { Toast, ToastViewport, useToast } from '@astryx-vue/core/Toast'

const toast = useToast()
</script>

<template>
  <VStack :gap="3">
    <Toast :is-auto-hide="false" body="Changes saved successfully." type="info">
      <template #end>
        <Button
          label="Show toast"
          size="sm"
          variant="ghost"
          @click="toast({ body: 'Changes saved successfully.', type: 'info' })"
        />
      </template>
    </Toast>
    <Toast :is-auto-hide="false" body="Failed to save changes." type="error">
      <template #end>
        <Button
          label="Show toast"
          size="sm"
          variant="ghost"
          @click="toast({ body: 'Failed to save changes.', type: 'error' })"
        />
      </template>
    </Toast>
    <ToastViewport />
  </VStack>
</template>
```

## Toast Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `type` | `ToastType` | `'info'` | 提示的类型，可选 info、success、warning、error；error 类型会自动应用 `role="alert"`。 |
| `body` | `string` | - | 提示的正文文本，默认渲染在提示内容区。 |
| `isAutoHide` | `boolean` | `error` 以外为 `true` | 是否自动关闭。error 类型默认一直留着，直到被关掉。 |
| `autoHideDuration` | `number` | `5000` | 自动关闭前的停留时长，单位毫秒。悬停、聚焦或窗口失焦会暂停计时，恢复后至少还剩一秒。 |
| `autoClose` | `boolean` | - | `isAutoHide` 的旧名字，写哪个都行，同名时以 `isAutoHide` 为准。 |
| `duration` | `number` | - | `autoHideDuration` 的旧名字，写哪个都行，同名时以 `autoHideDuration` 为准。 |
| `uniqueID` | `string` | - | 用来把同一条提示合并成一个的标识。 |
| `collisionBehavior` | `'ignore' \| 'overwrite'` | `'overwrite'` | 屏幕上已有同 `uniqueID` 的提示时怎么办。 |
| `endContent` | `Component` | - | 末尾动作，例如撤销按钮。临时内容用 `end` 插槽。 |
| `onDismiss` | `(reason: 'auto' \| 'manual') => void` | - | 卡片自己关掉提示时触发：计时器、关闭按钮或自定义内容。`useToast()` 的参数里使用。 |
| `onHide` | `(reason: 'auto' \| 'manual') => void` | - | 提示被移除时触发，包括用 `useToast()` 返回的函数关掉的情况。`useToast()` 的参数里使用。 |

## Toast 事件

| 名称 | 说明 |
| --- | --- |
| `dismiss` | 卡片自己关闭提示时触发，参数是原因（`'auto'` 或 `'manual'`）。 |
| `close` | `dismiss` 的旧名字，同时触发，不带原因。 |

## Toast Slots

| 名称 | 说明 |
| --- | --- |
| `default` | 自定义提示的内容区域，未提供时默认显示 `body` 文本。 |
| `end` | 末尾内容，替代 `endContent`。 |
| `content` | 替换整块卡片内容，参数是 `{ body, endContent, type, isAutoHide, autoHideDuration, dismiss }`。这时不再渲染自带的关闭按钮，控件全部由自定义布局负责。 |

## ToastViewport Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `placement` | `ToastPlacement` | `'bottom-end'` | 提示在屏幕上的弹出位置，可选 top-start、top-center、top-end、bottom-start、bottom-center、bottom-end。 |

## useToast

```ts
const toast = useToast()

const dismiss = toast({
  body: 'Hello',
  type: 'info',
  autoHideDuration: 3000,
  onDismiss: reason => console.log('关闭原因', reason),
  onHide: reason => console.log('已移除', reason),
})
// 手动关闭
dismiss()
// 关闭全部
toast.clear()
```
