13 Commits
Author SHA1 Message Date
timi cd5f0cce9f Merge pull request 'v2.1.0' (#15) from dev into master
Reviewed-on: #15
2026-11-25 09:15:31 +00:00
timi ecdb1a4948 Merge pull request 'v2.0.0' (#14) from dev into master
Reviewed-on: #14
2026-11-23 12:41:57 +00:00
timi d8487807cd Merge pull request 'v1.5.0' (#13) from dev into master
Reviewed-on: #13
2026-11-19 06:38:26 +00:00
timi 6885015825 Merge pull request 'v1.4.0' (#12) from dev into master
Reviewed-on: #12
2026-11-18 07:19:12 +00:00
timi 38038b9461 Merge pull request 'v1.3.1' (#11) from dev into master
Reviewed-on: #11
2026-11-16 09:47:26 +00:00
timi 9e06f1e9b8 Merge pull request 'v1.3.0' (#10) from dev into master
Reviewed-on: #10
2026-11-14 09:01:42 +00:00
timi 0f369dc42d Merge pull request 'v1.2.0' (#9) from dev into master
Reviewed-on: #9
2026-11-13 06:05:10 +00:00
timi 5f4c35cdd3 Merge pull request 'v1.1.1' (#8) from dev into master
Reviewed-on: #8
2026-11-11 17:27:20 +00:00
timi 35885b6e9d Merge pull request 'v1.1.0' (#7) from dev into master
Reviewed-on: #7
2026-11-11 16:18:39 +00:00
timi a0a978f58b Merge pull request 'v1.0.3' (#6) from dev into master
Reviewed-on: #6
2026-11-10 09:30:55 +00:00
timi 986f8c75db Merge pull request 'v1.0.2' (#5) from dev into master
Reviewed-on: #5
2026-11-07 17:59:18 +00:00
timi 13db8077f4 Merge pull request 'v1.0.2' (#4) from dev into master
Reviewed-on: #4
2026-11-07 17:50:22 +00:00
timi 7c8d2566d7 Merge pull request 'v1.0.1' (#3) from dev into master
Reviewed-on: #3
2026-11-06 09:33:01 +00:00
8 changed files with 186 additions and 781 deletions
@@ -209,13 +209,6 @@ onUnmounted(() => {
// 文档预览里的过渡组件就是用来验证转场的,因此在预览范围内恢复原定时长。
@media (prefers-reduced-motion: reduce) {
.tui-demo {
// 语音输入的呼吸边框是交互反馈的一部分,预览中恢复动画
:deep(.composer.voice-active .form::after) {
animation-delay: 0s !important;
animation-duration: 1.6s !important;
animation-iteration-count: infinite !important;
}
:deep(.page-transition .push-left-enter-active) {
transition-duration: 520ms, 200ms !important;
}
+5 -87
View File
@@ -10,97 +10,18 @@ demo-preview=../demos/ai-chat-composer/basic.vue
:::
## 语音输入
开启 `voice-enabled` 后,输入框为空时右侧发送按钮会变成语音按钮(图标 `voice-wave`,文案「语音」)。点击后输入区切换为「按住说话」,右侧按钮变为键盘按钮(图标 `keyboard-1`,文案「输入」);点击键盘按钮回到文本输入。组件只负责手势与状态展示,识别能力由业务侧接入。
:::preview 语音输入 || 点击语音按钮进入按住说话,识别文本实时显示在整个控件上方;松手发送,移出按住按钮后松开取消;示例接入浏览器 Web Speech API,不支持时可勾选「模拟识别」
demo-preview=../demos/ai-chat-composer/voice.vue
:::
### 交互约定
- 输入框有内容时右侧仍是发送按钮;只有内容为空且 `voiceState` 为 `idle` 时才显示语音入口
- 点击语音按钮进入语音模式,输入区替换为「按住说话」按钮;按住立即触发 `voice-start`,没有长按等待
- 按住期间整个输入卡片显示主题色呼吸边框,识别文本实时浮在整个输入卡片上方,最多两行
- 按住时按钮文案使用 `voiceSendHint`,默认「松开发送」;指针移出按住按钮后改用 `voiceCancelHint`,默认「松开取消」
- 松手时指针仍在按住按钮内:触发 `voice-stop`,由业务侧停止识别、取最终结果并发送
- 松手时指针已移出按住按钮:触发 `voice-cancel`,业务侧应中断识别并丢弃本次结果
- 指针被系统取消时同样触发 `voice-cancel`
- 语音模式右侧固定为键盘按钮(图标 `keyboard-1`,文案「输入」),识别中和按住时禁用;点击回到文本输入
- 文本输入与按住说话共用同一输入区高度,切换模式时组件不跳动;文本域按内容换行,最少 3 行、最多 6 行,超出后在文本域内滚动
- `voiceEnabled` 默认关闭,需要显式开启
`voiceState` 由业务侧驱动:
| 状态 | 含义 |
| --- | --- |
| `idle` | 未在识别,可以切换模式或按住说话 |
| `listening` | 正在聆听,实时回写 `voiceText`,组件显示在整个控件上方 |
| `processing` | 已松手,等待最终识别结果 |
识别完成或失败后回到 `idle`。组件不会自动发送;正常松手由业务侧在 `voice-stop` 后自行处理。想换文案时用 `voiceHoldText`、`voiceSendHint`、`voiceCancelHint`、`voiceListeningText`、`voiceProcessingText`。
### 组件边界与兼容性
`AiChatComposer` 不包含 ASR,也不依赖 Web Speech API。`voice-start`、`voice-stop`、`voice-cancel` 只表达手势,录音、识别和失败降级全部由调用方决定。上面的 demo 使用 Web Speech API 只是演示适配器,可以整体换成服务端流式识别或原生桥接。
Web Speech API 的实际兼容性(2026-11):
| 平台 | 情况 |
| --- | --- |
| Windows / macOS Chrome、Edge | 可用;Chromium 系通常依赖厂商在线语音服务,国内网络或离线可能报 `network` |
| macOS Safari 14.1+ | 可用(`webkitSpeechRecognition`),需要启用 Siri / 听写 |
| iOS Safari 14.5+ | 可用,需要启用 Siri;`continuous` 从 Safari 17 起才完整,之前停顿后容易提前结束 |
| Android Chrome | 可用,但 `continuous = true` 无效,停顿会结束识别;通常依赖 Google 语音服务,国内网络可能不可用 |
| Android 厂商浏览器 / 微信 / App WebView | 多数不支持或没有可用的语音服务 |
| Firefox 桌面 160+ | 有实现,但生态较新,建议实测;Firefox Android 不支持 |
| SafariViewController / iOS App 内嵌页 | Web Speech API 不可用或不可靠,改用原生桥接 |
Web Speech API 还需要 HTTPS(localhost 除外)和麦克风授权;音频会交给浏览器厂商的服务,隐私敏感或企业内网场景不建议使用。组件在 `pointerdown` 时立即触发 `voice-start`,iOS 上应在这个事件里同步调用 `SpeechRecognition.start()`;等异步连接建立后再启动容易被用户手势策略拒绝。
生产环境建议把识别放到服务端流式 ASR(WebSocket)或原生语音插件。业务侧只需要按组件契约驱动状态:
```ts
const voiceState = ref<"idle" | "listening" | "processing">("idle");
const voiceText = ref("");
function onVoiceStart() {
voiceState.value = "listening";
// 开始录音或连接 ASR;中间结果持续写入 voiceText
}
function onVoiceStop() {
voiceState.value = "processing";
// 停止录音,等待最终结果;拿到结果后发送
}
function onVoiceCancel() {
voiceState.value = "idle";
voiceText.value = "";
// 中断录音或识别,丢弃本次结果
}
```
`voiceText` 只在按住说话区上方展示,不回写 `v-model`;语音结果由业务侧在 `voice-stop` 后取出并发送。识别不可用时退回文字输入,不要阻塞发送。
## 何时使用
需要单独摆放输入框时使用。多数情况下直接用 [AiChatPanel](/components/ai-chat-panel) 更省事。
## 输入区与操作按钮
文本域占满整行并随内容自动增高。下一行左侧是新开会话(`chat-add`)和添加附件(`file-add`),右侧根据状态显示语音、键盘、发送或停止按钮。
文本域占满整行并随内容自动增高。下一行左侧是新开会话(`chat-add`)和添加附件(`file-add`),右侧根据状态显示纯文本发送或停止按钮。
| 状态 | 按钮 |
| --- | --- |
| 空闲、输入框为空且启用 `voiceEnabled` | 语音(`voice-wave`),点击进入语音模式 |
| 语音模式且未在识别 | 键盘(`keyboard-1`),点击回到文本输入 |
| 语音模式正在识别或处理 | 键盘按钮禁用 |
| 文本模式且有内容 | 发送(`sendText`) |
| `isGenerating` 为真 | 停止(`stopText`,危险色),优先于语音模式 |
| 空闲且未禁用 | 新开会话、添加附件、发送(`sendText`) |
| `isGenerating` 为真 | 停止(`stopText`,危险色) |
| 有 `lastError` 且 `canRetry` | 错误条 + 重试(`retryText`) |
生成中或 `disabled` 为真时输入框不可编辑,新开会话、添加附件和 `send` 事件不会触发。
@@ -112,15 +33,12 @@ function onVoiceCancel() {
- `retry`:点错误条上的重试
- `new-conversation`:清空输入框并请求业务侧开始一个新会话
- `add-attachment`:请求业务侧添加附件
- `voice-start`:按住「按住说话」按钮时立即触发,可以开始录音或启动识别
- `voice-stop`:松手且不在取消区,可以停止识别并取最终结果
- `voice-cancel`:松手时指针已移出按住按钮,或指针被系统取消;业务侧应中断识别并丢弃本次结果
输入框内容用 `v-model` 绑定,`maxLength` 默认 2000。语音识别结果只通过 `voiceText` 展示,不写入 `v-model`。
输入框内容用 `v-model` 绑定,`maxLength` 默认 2000。
## 自定义插槽
`send`、`stop`、`error` 三个插槽可以替换对应区域的渲染,都带作用域参数(`disabled`、`onSend`、`onStop`、`error`、`canRetry`)。`send` 插槽只用于文本发送;语音入口和键盘切换按钮由组件内置。
`send`、`stop`、`error` 三个插槽可以替换对应区域的渲染,都带作用域参数(`disabled`、`onSend`、`onStop`、`error`、`canRetry`)。
## API
-353
View File
@@ -1,353 +0,0 @@
<template>
<div class="demo">
<p
class="voice-placeholder"
:class="{ hidden: voiceState !== 'idle' }"
v-text="'点击语音按钮,按住下方按钮说话;移出按钮后松开取消'"
/>
<ai-chat-composer
v-model="draft"
:is-generating="generating"
voice-enabled
:voice-state="voiceState"
:voice-text="voiceText"
@send="sendMessage"
@voice-start="onVoiceStart"
@voice-stop="onVoiceStop"
@voice-cancel="onVoiceCancel"
/>
<div class="bar">
<label class="mock">
<input v-model="mockEnabled" type="checkbox" />
<span v-text="'模拟识别'" />
</label>
<span class="hint" v-text="hint" />
</div>
<ol class="log">
<li v-for="(item, index) in log" :key="index" v-text="item" />
</ol>
</div>
</template>
<script lang="ts" setup>
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { AiChatComposer } from "timi-tdesign-mobile";
/**
* 注意:下面的 Web Speech API 只是文档演示用的适配器,不属于 AiChatComposer。
* 组件本身不包含 ASR;换成服务端流式识别或原生桥接时,只需回写 voiceState / voiceText。
*/
type VoiceState = "idle" | "listening" | "processing";
/** Web Speech API 的主入口不在 lib.dom 里,这里只声明演示用到的部分。 */
interface SpeechRecognitionLike {
lang: string;
continuous: boolean;
interimResults: boolean;
onresult: ((event: SpeechResultEvent) => void) | null;
onerror: ((event: SpeechErrorEvent) => void) | null;
onend: (() => void) | null;
start: () => void;
stop: () => void;
abort: () => void;
}
interface SpeechResultEvent {
resultIndex: number;
results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>;
}
interface SpeechErrorEvent {
error: string;
}
type SpeechRecognitionConstructor = new () => SpeechRecognitionLike;
/** 模拟识别逐段吐出的文本,用来预览不说话也能看到的完整交互。 */
const MOCK_STEPS = [
"帮我",
"帮我整理一下",
"帮我整理一下上周的订单数据",
"帮我整理一下上周的订单数据,并总结三条结论"
];
const draft = ref("");
const generating = ref(false);
const log = ref<string[]>([]);
const supported = ref(false);
const mockEnabled = ref(false);
const voiceState = ref<VoiceState>("idle");
const voiceText = ref("");
let recognition: SpeechRecognitionLike | undefined;
let finalText = "";
let mockStepTimer: number | undefined;
let mockFinishTimer: number | undefined;
const hint = computed(() => {
if (mockEnabled.value) {
return "模拟模式:按住按钮说话,松手发送;移出按钮后松开取消。";
}
if (!supported.value) {
return "当前浏览器不支持语音识别,已切换为模拟。";
}
return "按住按钮说话,识别文本显示在整个控件上方;松手发送,移出按钮后松开取消。";
});
/** 获取浏览器实现;Chrome 与 Edge 需要 webkit 前缀。 */
function getSpeechRecognition(): SpeechRecognitionConstructor | undefined {
if (typeof window === "undefined") {
return undefined;
}
const speechWindow = window as Window & {
SpeechRecognition?: SpeechRecognitionConstructor;
webkitSpeechRecognition?: SpeechRecognitionConstructor;
};
return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition;
}
function push(message: string): void {
log.value = [`${new Date().toLocaleTimeString()} ${message}`, ...log.value].slice(0, 5);
}
/** 所有发送入口共用:录音结果与手动输入都走这里。 */
function sendMessage(message: string): void {
const content = message.trim();
if (!content) {
push("没有识别到内容,请再试一次");
return;
}
draft.value = "";
generating.value = true;
push(`send("${content}")`);
setTimeout(() => {
generating.value = false;
push("生成结束");
}, 1500);
}
function onVoiceStart(): void {
voiceText.value = "";
finalText = "";
if (mockEnabled.value || !supported.value) {
startMock();
return;
}
const SpeechRecognition = getSpeechRecognition();
if (!SpeechRecognition) {
startMock();
return;
}
try {
const instance = new SpeechRecognition();
instance.lang = "zh-CN";
instance.continuous = true;
instance.interimResults = true;
instance.onresult = handleResult;
instance.onerror = handleError;
instance.onend = handleEnd;
instance.start();
recognition = instance;
voiceState.value = "listening";
} catch {
push("语音识别启动失败,已切换模拟识别");
startMock();
}
}
function onVoiceStop(): void {
stopVoice();
}
function stopVoice(): void {
if (voiceState.value !== "listening") {
return;
}
if (mockStepTimer !== undefined) {
stopMock();
return;
}
if (!recognition) {
finishVoice();
return;
}
voiceState.value = "processing";
try {
recognition.stop();
} catch {
finishVoice();
}
}
function onVoiceCancel(): void {
push("已取消语音输入");
draft.value = "";
resetVoice();
}
/** 实时拼接最终结果与临时结果,组件在按住说话区上方展示。 */
function handleResult(event: SpeechResultEvent): void {
let interim = "";
for (let index = event.resultIndex; index < event.results.length; index += 1) {
const result = event.results[index];
const transcript = result[0]?.transcript ?? "";
if (result.isFinal) {
finalText += transcript;
} else {
interim += transcript;
}
}
voiceText.value = (finalText + interim).trim();
}
function handleError(event: SpeechErrorEvent): void {
if (event.error === "aborted") {
return;
}
const messages: Record<string, string> = {
"not-allowed": "麦克风权限被拒绝,可勾选「模拟识别」再试",
"service-not-allowed": "当前环境不允许语音识别,可勾选「模拟识别」再试",
"audio-capture": "没有找到可用的麦克风",
network: "语音服务不可用,可勾选「模拟识别」再试",
"no-speech": "没有听到声音,请再试一次"
};
push(messages[event.error] ?? `语音识别失败:${event.error}`);
draft.value = "";
resetVoice();
}
function handleEnd(): void {
recognition = undefined;
voiceState.value = "processing";
finishVoice();
}
function finishVoice(): void {
const message = voiceText.value.trim();
resetVoice();
sendMessage(message);
}
function startMock(): void {
voiceState.value = "listening";
voiceText.value = MOCK_STEPS[0];
let step = 1;
mockStepTimer = window.setInterval(() => {
voiceText.value = MOCK_STEPS[Math.min(step, MOCK_STEPS.length - 1)];
step += 1;
}, 500);
}
function stopMock(): void {
if (mockStepTimer !== undefined) {
window.clearInterval(mockStepTimer);
mockStepTimer = undefined;
}
voiceState.value = "processing";
mockFinishTimer = window.setTimeout(() => {
mockFinishTimer = undefined;
finishVoice();
}, 600);
}
/** 释放识别实例与定时器;abort 用于取消,正常结束则只解绑回调。 */
function resetVoice(): void {
if (recognition) {
const instance = recognition;
recognition = undefined;
instance.onresult = null;
instance.onerror = null;
instance.onend = null;
try {
instance.abort();
} catch {
// 实例可能已自行结束,忽略
}
}
if (mockStepTimer !== undefined) {
window.clearInterval(mockStepTimer);
mockStepTimer = undefined;
}
if (mockFinishTimer !== undefined) {
window.clearTimeout(mockFinishTimer);
mockFinishTimer = undefined;
}
voiceState.value = "idle";
voiceText.value = "";
finalText = "";
}
onMounted(() => {
supported.value = Boolean(getSpeechRecognition());
mockEnabled.value = !supported.value;
});
onBeforeUnmount(() => {
resetVoice();
});
</script>
<style lang="less" scoped>
.demo {
.voice-placeholder {
display: flex;
height: 5.5rem;
margin: 0 0 .5rem;
color: var(--vp-c-text-3);
font-size: .75rem;
border: 1px dashed var(--vp-c-divider);
border-radius: 1rem;
align-items: center;
justify-content: center;
&.hidden {
visibility: hidden;
}
}
.bar {
display: flex;
gap: .5rem;
align-items: center;
margin-top: .75rem;
}
.mock {
gap: .25rem;
flex: none;
display: inline-flex;
font-size: .75rem;
cursor: pointer;
color: var(--vp-c-text-2);
white-space: nowrap;
align-items: center;
input {
cursor: pointer;
accent-color: var(--vp-c-brand-1);
}
}
.hint {
font-size: .75rem;
line-height: 1.4;
color: var(--vp-c-text-2);
}
.log {
margin: .75rem 0 0;
padding-left: 1.25rem;
font-size: .75rem;
font-family: monospace;
color: var(--vp-c-text-2);
li {
margin-bottom: .25rem;
word-break: break-all;
}
}
}
</style>
+1 -1
View File
@@ -10,7 +10,7 @@
"preview": "vitepress preview ."
},
"dependencies": {
"tdesign-mobile-vue": "^1.17.2",
"tdesign-mobile-vue": "^1.17.1",
"timi-web": "^1.0.2",
"vue": "^3.5.26",
"vue-router": "^4.5.0"
+16 -23
View File
@@ -9,8 +9,8 @@ importers:
.:
dependencies:
tdesign-mobile-vue:
specifier: ^1.17.2
version: 1.17.2(vue@3.5.43(typescript@5.9.3))
specifier: ^1.17.1
version: 1.17.1(vue@3.5.43(typescript@5.9.3))
timi-web:
specifier: ^1.0.2
version: 1.0.2(@floating-ui/dom@1.8.0)(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/extensions@3.33.0(@tiptap/core@3.33.0(@tiptap/pm@3.33.0))(@tiptap/pm@3.33.0))(typescript@5.9.3)(vue@3.5.43(typescript@5.9.3))
@@ -26,7 +26,7 @@ importers:
version: 25.9.8
'@vitepress-demo-preview/plugin':
specifier: ^1.4.1
version: 1.4.1(markdown-it-container@3.0.0)(vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(sortablejs@1.15.7)(terser@5.51.2)(typescript@5.9.3))(vue@3.5.43(typescript@5.9.3))
version: 1.4.1(markdown-it-container@3.0.0)(vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(terser@5.51.2)(typescript@5.9.3))(vue@3.5.43(typescript@5.9.3))
less:
specifier: ^4.5.1
version: 4.9.1
@@ -41,7 +41,7 @@ importers:
version: 21.1.0(@vueuse/core@12.8.2(typescript@5.9.3))(esbuild@0.21.5)(rollup@4.63.4)(vite@5.4.21(@types/node@25.9.8)(less@4.9.1)(terser@5.51.2))
vitepress:
specifier: ^1.6.4
version: 1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(sortablejs@1.15.7)(terser@5.51.2)(typescript@5.9.3)
version: 1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(terser@5.51.2)(typescript@5.9.3)
vue-docgen-api:
specifier: ^4.79.2
version: 4.79.2(vue@3.5.43(typescript@5.9.3))
@@ -1648,9 +1648,6 @@ packages:
shiki@2.5.0:
resolution: {integrity: sha512-mI//trrsaiCIPsja5CNfsyNOqgAZUb6VpJA+340toL42UpzQlXpwRV9nch69X6gaUxrr9kaOOa6e3y3uAkGFxQ==}
sortablejs@1.15.7:
resolution: {integrity: sha512-Kk8wLQPlS+yi1ZEf48a4+fzHa4yxjC30M/Sr2AnQu+f/MPwvvX9XjZ6OWejiz8crBsLwSq8GHqaxaET7u6ux0A==}
source-map-js@1.2.1:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
@@ -1696,13 +1693,13 @@ packages:
tabbable@6.5.0:
resolution: {integrity: sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA==}
tdesign-icons-vue-next@0.4.12:
resolution: {integrity: sha512-isuKOIBdOdQCCeWDiOfvdZSucXa0KC6wLBy2YvNLpRZhVxL7SjDVTulCncehzt4JFzi81LI0+dCVohw6GbfjPA==}
tdesign-icons-vue-next@0.4.11:
resolution: {integrity: sha512-lBkRUy8bdb6lQLFOOkSb1LPdl4CmZRewrc8SOUlmWkDD/DG3BTsSd/ZQ4Z767pPSlypyvxwSwcJgRv6+zjubAQ==}
peerDependencies:
vue: ^3.0.0
tdesign-mobile-vue@1.17.2:
resolution: {integrity: sha512-/MH+eNnySvMlEMwIlG0sMPOuwUuhWyOHn6HdS79ct9/+ZP+gCDzGH/usgcahZHM1l0ulY2NTlUp32opimlSZkQ==}
tdesign-mobile-vue@1.17.1:
resolution: {integrity: sha512-gCmhaNCc2xhSkbITHiXnE/UGs6GHLe9LTE7T26ELOENC5Cqpa+j4KYU9wz6uqFV+Ro10RkG3DFikYHnq0gNN0A==}
engines: {node: '>=18.0.0'}
peerDependencies:
vue: ^3.2.6
@@ -2713,12 +2710,12 @@ snapshots:
vite: 5.4.21(@types/node@25.9.8)(less@4.9.1)(terser@5.51.2)
vue: 3.5.43(typescript@5.9.3)
'@vitepress-demo-preview/plugin@1.4.1(markdown-it-container@3.0.0)(vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(sortablejs@1.15.7)(terser@5.51.2)(typescript@5.9.3))(vue@3.5.43(typescript@5.9.3))':
'@vitepress-demo-preview/plugin@1.4.1(markdown-it-container@3.0.0)(vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(terser@5.51.2)(typescript@5.9.3))(vue@3.5.43(typescript@5.9.3))':
dependencies:
'@flypeng/tool': 5.7.5
markdown-it: 14.3.2
markdown-it-container: 3.0.0
vitepress: 1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(sortablejs@1.15.7)(terser@5.51.2)(typescript@5.9.3)
vitepress: 1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(terser@5.51.2)(typescript@5.9.3)
vue: 3.5.43(typescript@5.9.3)
'@vue/compiler-core@3.5.43':
@@ -2814,14 +2811,13 @@ snapshots:
transitivePeerDependencies:
- typescript
'@vueuse/integrations@12.8.2(focus-trap@7.8.0)(sortablejs@1.15.7)(typescript@5.9.3)':
'@vueuse/integrations@12.8.2(focus-trap@7.8.0)(typescript@5.9.3)':
dependencies:
'@vueuse/core': 12.8.2(typescript@5.9.3)
'@vueuse/shared': 12.8.2(typescript@5.9.3)
vue: 3.5.43(typescript@5.9.3)
optionalDependencies:
focus-trap: 7.8.0
sortablejs: 1.15.7
transitivePeerDependencies:
- typescript
@@ -3660,8 +3656,6 @@ snapshots:
'@shikijs/vscode-textmate': 10.0.2
'@types/hast': 3.0.5
sortablejs@1.15.7: {}
source-map-js@1.2.1: {}
source-map-support@0.5.21:
@@ -3703,20 +3697,19 @@ snapshots:
tabbable@6.5.0: {}
tdesign-icons-vue-next@0.4.12(vue@3.5.43(typescript@5.9.3)):
tdesign-icons-vue-next@0.4.11(vue@3.5.43(typescript@5.9.3)):
dependencies:
'@babel/runtime': 7.29.7
vue: 3.5.43(typescript@5.9.3)
tdesign-mobile-vue@1.17.2(vue@3.5.43(typescript@5.9.3)):
tdesign-mobile-vue@1.17.1(vue@3.5.43(typescript@5.9.3)):
dependencies:
'@babel/runtime': 7.29.7
'@use-gesture/vanilla': 10.3.1
'@vueuse/core': 10.7.0(vue@3.5.43(typescript@5.9.3))
dayjs: 1.11.23
lodash-es: 4.18.1
sortablejs: 1.15.7
tdesign-icons-vue-next: 0.4.12(vue@3.5.43(typescript@5.9.3))
tdesign-icons-vue-next: 0.4.11(vue@3.5.43(typescript@5.9.3))
tinycolor2: 1.6.0
validator: 13.15.35
vue: 3.5.43(typescript@5.9.3)
@@ -3904,7 +3897,7 @@ snapshots:
less: 4.9.1
terser: 5.51.2
vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(sortablejs@1.15.7)(terser@5.51.2)(typescript@5.9.3):
vitepress@1.6.4(@algolia/client-search@5.59.0)(@types/node@25.9.8)(less@4.9.1)(postcss@8.5.28)(search-insights@2.17.3)(terser@5.51.2)(typescript@5.9.3):
dependencies:
'@docsearch/css': 3.8.2
'@docsearch/js': 3.8.2(@algolia/client-search@5.59.0)(search-insights@2.17.3)
@@ -3917,7 +3910,7 @@ snapshots:
'@vue/devtools-api': 7.7.10
'@vue/shared': 3.5.43
'@vueuse/core': 12.8.2(typescript@5.9.3)
'@vueuse/integrations': 12.8.2(focus-trap@7.8.0)(sortablejs@1.15.7)(typescript@5.9.3)
'@vueuse/integrations': 12.8.2(focus-trap@7.8.0)(typescript@5.9.3)
focus-trap: 7.8.0
mark.js: 8.11.1
minisearch: 7.2.0
+1 -1
View File
@@ -9,7 +9,7 @@
"**/*.css"
],
"private": false,
"version": "2.1.1",
"version": "2.1.0",
"license": "MIT",
"scripts": {
"dev": "pnpm run -C docs dev",
+4 -4
View File
@@ -4829,8 +4829,8 @@ packages:
resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==}
engines: {node: '>=6'}
tdesign-icons-vue-next@0.4.12:
resolution: {integrity: sha512-isuKOIBdOdQCCeWDiOfvdZSucXa0KC6wLBy2YvNLpRZhVxL7SjDVTulCncehzt4JFzi81LI0+dCVohw6GbfjPA==}
tdesign-icons-vue-next@0.4.11:
resolution: {integrity: sha512-lBkRUy8bdb6lQLFOOkSb1LPdl4CmZRewrc8SOUlmWkDD/DG3BTsSd/ZQ4Z767pPSlypyvxwSwcJgRv6+zjubAQ==}
peerDependencies:
vue: ^3.0.0
@@ -10629,7 +10629,7 @@ snapshots:
tapable@2.2.1: {}
tdesign-icons-vue-next@0.4.12(vue@3.5.26(typescript@5.8.3)):
tdesign-icons-vue-next@0.4.11(vue@3.5.26(typescript@5.8.3)):
dependencies:
'@babel/runtime': 7.26.9
vue: 3.5.26(typescript@5.8.3)
@@ -10642,7 +10642,7 @@ snapshots:
dayjs: 1.11.13
lodash-es: 4.17.21
sortablejs: 1.15.7
tdesign-icons-vue-next: 0.4.12(vue@3.5.26(typescript@5.8.3))
tdesign-icons-vue-next: 0.4.11(vue@3.5.26(typescript@5.8.3))
tinycolor2: 1.6.0
validator: 13.12.0
vue: 3.5.26(typescript@5.8.3)
+159 -305
View File
@@ -1,5 +1,5 @@
<template>
<div class="composer" :class="{ 'voice-active': voicePressing }">
<div class="composer">
<div v-if="props.lastError" class="error-bar">
<slot name="error" :error="props.lastError" :can-retry="props.canRetry">
<span class="error-text" v-text="props.lastError" />
@@ -13,38 +13,34 @@
</slot>
</div>
<t-form class="form glass-white" @submit="submitMessage">
<div v-if="voiceMode && (voiceTranscript || voiceTranscriptHint)" class="voice-transcript" aria-live="polite">
<div class="voice-wave" aria-hidden="true">
<span v-for="index in 5" :key="index" :style="`--i: ${index}`" />
</div>
<p v-if="voiceTranscript" class="voice-text" v-text="voiceTranscript" />
<p v-else class="voice-placeholder" v-text="voiceTranscriptHint" />
</div>
<div class="input-wrap">
<t-textarea
ref="textareaRef"
v-model="draft"
class="input"
:class="{ 'voice-input-hidden': voiceMode }"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="voiceMode || props.isGenerating || props.disabled"
:autosize="{ minRows: 3, maxRows: 6 }"
:disabled="props.isGenerating || props.disabled"
:maxlength="props.maxLength"
:placeholder="props.placeholder"
:aria-hidden="voiceMode"
@focus="inputFocused = true"
@blur="inputFocused = false"
/>
<button
v-if="voiceMode"
ref="holdRef"
class="voice-hold"
:class="{ active: voicePressing, cancel: willCancel }"
type="button"
:disabled="props.disabled || props.isGenerating"
<div
v-if="voiceHitVisible"
class="voice-hit"
@pointerdown="handleVoicePointerDown"
@pointermove="handleVoicePointerMove"
@pointerup="handleVoicePointerUp"
@pointercancel="handleVoicePointerCancel"
@contextmenu.prevent
>
<t-icon name="voice-wave" size="small" />
<span v-text="voiceHoldLabel" />
</button>
/>
<div v-if="voicePanelVisible" class="voice-panel" :class="{ cancel: willCancel }">
<div class="voice-wave" aria-hidden="true">
<span v-for="index in 5" :key="index" :style="`--i: ${index}`" />
</div>
<p class="voice-text" v-text="voicePanelText" />
<p class="voice-hint" v-text="willCancel ? props.voiceCancelHint : props.voiceSendHint" />
</div>
</div>
<div class="actions">
<div class="tools">
@@ -86,49 +82,13 @@
<t-button
class="send"
type="button"
size="small"
size="extra-small"
theme="danger"
:disabled="props.disabled"
:content="props.stopText"
@click="emit('stop')"
>
<template #icon>
<t-icon name="stop" />
</template>
</t-button>
/>
</slot>
<template v-else-if="props.voiceEnabled && voiceMode">
<t-button
class="send voice-toggle"
type="button"
size="small"
theme="primary"
aria-label="切换到键盘输入"
:disabled="props.disabled || voicePressing || props.voiceState !== 'idle'"
content="输入"
@click="exitVoiceMode"
>
<template #icon>
<t-icon name="keyboard-1" />
</template>
</t-button>
</template>
<template v-else-if="props.voiceEnabled && !draft.trim()">
<t-button
class="send voice-toggle"
type="button"
size="small"
theme="primary"
aria-label="语音输入"
:disabled="props.disabled || props.voiceState !== 'idle'"
content="语音"
@click="enterVoiceMode"
>
<template #icon>
<t-icon name="voice-wave" />
</template>
</t-button>
</template>
<slot
v-else
name="send"
@@ -138,15 +98,11 @@
<t-button
class="send"
type="submit"
size="small"
size="extra-small"
theme="primary"
:disabled="props.disabled"
:content="props.sendText"
>
<template #icon>
<t-icon name="send-1" />
</template>
</t-button>
/>
</slot>
</div>
</t-form>
@@ -154,7 +110,7 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, useTemplateRef, watch } from "vue";
import { computed, onBeforeUnmount, ref, useTemplateRef } from "vue";
defineOptions({
name: "AiChatComposer"
@@ -170,17 +126,15 @@ export interface Props {
stopText?: string;
retryText?: string;
maxLength?: number;
/** 是否启用语音输入 */
/** 是否启用长按输入框语音输入 */
voiceEnabled?: boolean;
/** 语音识别状态,由业务侧驱动 */
voiceState?: "idle" | "listening" | "processing";
/** 语音中间结果 */
voiceText?: string;
/** 按住说话提示 */
voiceHoldText?: string;
/** 按住时的提示 */
/** 松开发送提示 */
voiceSendHint?: string;
/** 移出按住按钮时的提示 */
/** 上滑取消提示 */
voiceCancelHint?: string;
/** 正在聆听提示 */
voiceListeningText?: string;
@@ -200,9 +154,8 @@ const props = withDefaults(defineProps<Props>(), {
voiceEnabled: false,
voiceState: "idle",
voiceText: "",
voiceHoldText: "按住 说话",
voiceSendHint: "松开 发送",
voiceCancelHint: "松开 取消",
voiceSendHint: "松开发送",
voiceCancelHint: "松开取消",
voiceListeningText: "正在听你说…",
voiceProcessingText: "正在识别…"
});
@@ -219,52 +172,37 @@ const emit = defineEmits<{
"voice-cancel": [];
}>();
/** 长按触发语音的阈值,短按仍然聚焦输入 */
const VOICE_HOLD_DELAY = 300;
/** 上滑取消的位移阈值 */
const VOICE_CANCEL_DISTANCE = 48;
/** 未触发语音时,手指移动超过该距离视为滑动 */
const VOICE_MOVE_TOLERANCE = 12;
const textareaRef = useTemplateRef<{ focus: () => void }>("textareaRef");
const holdRef = useTemplateRef<HTMLElement>("holdRef");
const voiceMode = ref(false);
const inputFocused = ref(false);
const voicePressing = ref(false);
const voiceTriggered = ref(false);
const willCancel = ref(false);
let voiceTimer: number | undefined;
let voiceStartY = 0;
let voicePointerId: number | undefined;
const voiceTranscript = computed(() => props.voiceText.trim());
/** 输入框为空且未聚焦时才接管长按,避免影响选择和编辑 */
const voiceHitVisible = computed(() => props.voiceEnabled
&& !props.disabled
&& !props.isGenerating
&& !draft.value.trim()
&& !inputFocused.value
&& (props.voiceState === "idle" || voicePressing.value));
const voiceHoldLabel = computed(() => {
if (willCancel.value) {
return props.voiceCancelHint;
}
if (props.voiceState === "processing") {
return props.voiceProcessingText;
}
if (voicePressing.value) {
return props.voiceSendHint;
}
if (props.voiceState === "listening") {
return props.voiceListeningText;
}
return props.voiceHoldText;
});
const voicePanelVisible = computed(() => props.voiceEnabled && (voiceTriggered.value || props.voiceState !== "idle"));
const voiceTranscriptHint = computed(() => {
if (voiceTranscript.value) {
return "";
const voicePanelText = computed(() => {
if (props.voiceText) {
return props.voiceText;
}
if (props.voiceState === "processing") {
return props.voiceProcessingText;
}
if (voicePressing.value || props.voiceState === "listening") {
return props.voiceListeningText;
}
return "";
});
watch(() => props.voiceEnabled, (enabled) => {
if (enabled) {
return;
}
if (voicePressing.value) {
cancelVoice();
}
voiceMode.value = false;
return props.voiceState === "processing" ? props.voiceProcessingText : props.voiceListeningText;
});
function startNewConversation(): void {
@@ -294,94 +232,88 @@ function submitMessage(): void {
emit("send", message);
}
function enterVoiceMode(): void {
function handleVoicePointerDown(event: PointerEvent): void {
if (!props.voiceEnabled || props.disabled || props.isGenerating || props.voiceState !== "idle" || draft.value.trim()) {
return;
}
voiceMode.value = true;
}
function exitVoiceMode(): void {
if (voicePressing.value) {
return;
}
voiceMode.value = false;
nextTick(() => textareaRef.value?.focus());
}
function handleVoicePointerDown(event: PointerEvent): void {
if (!props.voiceEnabled || !voiceMode.value || props.disabled || props.isGenerating || props.voiceState !== "idle" || voicePressing.value) {
return;
}
voicePressing.value = true;
voiceTriggered.value = false;
willCancel.value = false;
voiceStartY = event.clientY;
voicePointerId = event.pointerId;
event.preventDefault();
// 监听 window,手指移出按钮后仍能收到移动、释放和取消
window.addEventListener("pointermove", handleVoicePointerMove);
window.addEventListener("pointerup", handleVoicePointerUp);
window.addEventListener("pointercancel", handleVoicePointerCancel);
navigator.vibrate?.(15);
emit("voice-start");
try {
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
} catch {
// 指针捕获失败时仍可依赖冒泡事件,忽略
}
voiceTimer = window.setTimeout(() => {
if (!voicePressing.value) {
return;
}
voiceTriggered.value = true;
navigator.vibrate?.(15);
emit("voice-start");
}, VOICE_HOLD_DELAY);
}
function handleVoicePointerMove(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
return;
}
willCancel.value = !isPointInsideHold(event);
}
function isPointInsideHold(event: PointerEvent): boolean {
const element = holdRef.value;
if (!element) {
return false;
if (!voiceTriggered.value) {
if (Math.abs(event.clientY - voiceStartY) > VOICE_MOVE_TOLERANCE) {
resetVoicePress();
}
return;
}
const rect = element.getBoundingClientRect();
return event.clientX >= rect.left
&& event.clientX <= rect.right
&& event.clientY >= rect.top
&& event.clientY <= rect.bottom;
willCancel.value = voiceStartY - event.clientY > VOICE_CANCEL_DISTANCE;
}
function handleVoicePointerUp(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
return;
}
if (!isPointInsideHold(event)) {
cancelVoice();
const triggered = voiceTriggered.value;
const cancel = willCancel.value;
resetVoicePress();
if (!triggered) {
textareaRef.value?.focus();
return;
}
if (cancel) {
emit("voice-cancel");
return;
}
resetVoicePress();
emit("voice-stop");
}
function handleVoicePointerCancel(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
function handleVoicePointerCancel(): void {
if (!voicePressing.value) {
return;
}
cancelVoice();
}
function cancelVoice(): void {
const triggered = voiceTriggered.value;
resetVoicePress();
emit("voice-cancel");
if (triggered) {
emit("voice-cancel");
}
}
function resetVoicePress(): void {
window.removeEventListener("pointermove", handleVoicePointerMove);
window.removeEventListener("pointerup", handleVoicePointerUp);
window.removeEventListener("pointercancel", handleVoicePointerCancel);
if (voiceTimer !== undefined) {
window.clearTimeout(voiceTimer);
voiceTimer = undefined;
}
voicePressing.value = false;
voiceTriggered.value = false;
willCancel.value = false;
voicePointerId = undefined;
}
onBeforeUnmount(() => {
if (voicePressing.value) {
emit("voice-cancel");
if (voiceTimer !== undefined) {
window.clearTimeout(voiceTimer);
}
resetVoicePress();
});
</script>
@@ -420,20 +352,15 @@ onBeforeUnmount(() => {
margin: .5rem 0 0;
display: flex;
padding: .5rem;
position: relative;
box-shadow: 0 .5rem 1.5rem rgba(15, 23, 42, .12);
transition: border-color .2s, box-shadow .2s;
align-items: stretch;
border-radius: 1.25rem;
flex-direction: column;
.input-wrap {
gap: .375rem;
display: flex;
position: relative;
flex: 1;
min-width: 0;
flex-direction: column;
}
.input {
@@ -441,118 +368,80 @@ onBeforeUnmount(() => {
width: 100%;
padding: 0 .25rem;
min-width: 0;
&.voice-input-hidden {
visibility: hidden;
}
}
.voice-transcript {
left: 50%;
gap: .5rem;
width: 100%;
z-index: 3;
.voice-hit {
inset: 0;
z-index: 1;
position: absolute;
touch-action: none;
-webkit-tap-highlight-color: transparent;
}
.voice-panel {
inset: 0;
gap: .25rem;
display: flex;
z-index: 2;
padding: .5rem .75rem;
position: absolute;
box-sizing: border-box;
bottom: calc(100% + .5rem);
align-items: center;
pointer-events: none;
border: 1px solid var(--td-brand-color);
background: var(--td-bg-color-container);
box-shadow: 0 .5rem 1.5rem rgba(15, 23, 42, .16);
animation: voice-transcript-in .16s ease-out;
border-radius: 1rem;
transform: translateX(-50%);
}
.voice-wave {
gap: .1875rem;
height: 1rem;
display: flex;
flex: none;
align-items: center;
span {
width: .125rem;
height: 100%;
border-radius: .125rem;
background: var(--td-brand-color);
animation: voice-wave .9s ease-in-out infinite;
animation-delay: calc(var(--i) * .1s);
transform: scaleY(.3);
transform-origin: center;
}
}
.voice-text,
.voice-placeholder {
margin: 0;
flex: 1;
min-width: 0;
word-break: break-word;
}
.voice-text {
display: -webkit-box;
overflow: hidden;
color: var(--td-text-color-primary);
font-size: .875rem;
line-height: 1.4;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.voice-placeholder {
overflow: hidden;
color: var(--td-text-color-placeholder);
font-size: .75rem;
white-space: nowrap;
text-overflow: ellipsis;
}
.voice-hold {
inset: 0;
gap: .375rem;
z-index: 1;
display: flex;
padding: 0 .75rem;
position: absolute;
color: var(--td-brand-color);
font-size: .875rem;
font-weight: 500;
transition: color .15s, border-color .15s;
border: 0;
border-bottom: 1px solid var(--td-component-border);
background: transparent;
border-radius: 0;
align-items: center;
justify-content: center;
touch-action: none;
user-select: none;
-webkit-tap-highlight-color: transparent;
border-radius: .75rem;
pointer-events: none;
background: var(--td-bg-color-container);
align-items: center;
flex-direction: column;
justify-content: center;
&.active {
color: var(--td-brand-color);
border-bottom-color: var(--td-brand-color);
.voice-wave {
gap: .1875rem;
height: 1.25rem;
display: flex;
align-items: center;
span {
width: .1875rem;
height: 30%;
border-radius: .125rem;
background: var(--td-brand-color);
animation: voice-wave .9s ease-in-out infinite;
animation-delay: calc(var(--i) * .1s);
}
}
.voice-text {
overflow: hidden;
margin: .375rem 0 0;
font-size: .8125rem;
text-align: center;
line-height: 1.4;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
.voice-hint {
margin: .25rem 0 0;
color: var(--td-text-color-secondary);
font-size: .6875rem;
}
&.cancel {
color: var(--td-error-color);
border-bottom-color: var(--td-error-color);
}
.voice-text,
.voice-hint {
color: var(--td-error-color);
}
&:disabled {
opacity: .55;
.voice-wave span {
background: var(--td-error-color);
}
}
}
.actions {
--td-button-border-radius: 1rem;
--td-button-border-radius: .75rem;
gap: .5rem;
min-height: 2rem;
margin-top: .375rem;
display: flex;
align-items: center;
@@ -563,58 +452,23 @@ onBeforeUnmount(() => {
display: flex;
align-items: center;
}
.send {
padding: 0 1rem;
}
}
}
&.voice-active .form {
border-color: var(--td-brand-color);
&::after {
content: "";
inset: -.125rem;
border: 1px solid var(--td-brand-color);
position: absolute;
animation: voice-breathe 1s ease-in-out 0s infinite;
will-change: transform, opacity;
border-radius: inherit;
pointer-events: none;
transform-origin: center;
}
}
}
@keyframes voice-breathe {
0%,
100% {
opacity: .6;
transform: scaleX(1) scaleY(1);
}
50% {
opacity: .2;
transform: scaleX(1.02) scaleY(1.08);
}
}
@keyframes voice-wave {
0%,
100% {
height: 25%;
opacity: .5;
transform: scaleY(.3);
}
50% {
opacity: 1;
transform: scaleY(1);
}
}
@keyframes voice-transcript-in {
from {
opacity: 0;
}
to {
height: 100%;
opacity: 1;
}
}