feat(ai): refine voice input layout and cancellation

This commit is contained in:
Timi
2026-11-26 15:51:26 +08:00
parent 88e83415b6
commit 9d2faf3440
4 changed files with 302 additions and 333 deletions
+263 -281
View File
@@ -1,5 +1,5 @@
<template>
<div class="composer" :class="{ 'voice-active': voiceActive }">
<div class="composer" :class="{ 'voice-active': voicePressing }">
<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,45 +13,38 @@
</slot>
</div>
<t-form class="form glass-white" @submit="submitMessage">
<div v-if="voiceActionsVisible" class="voice-actions" role="group" aria-label="语音操作">
<div class="voice-status" aria-live="polite">
<div class="voice-wave" aria-hidden="true">
<span v-for="index in 5" :key="index" :style="`--i: ${index}`" />
</div>
<span class="voice-status-text" v-text="voiceStatusText" />
</div>
<div class="voice-buttons">
<div ref="cancelActionRef" class="voice-action cancel" :class="{ active: willCancel }">
<t-icon name="close" size="small" />
<span v-text="props.voiceCancelText" />
</div>
<div ref="keepActionRef" class="voice-action keep" :class="{ active: willKeep }">
<t-icon name="check" size="small" />
<span v-text="props.voiceKeepText" />
</div>
<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"
:autosize="{ minRows: 3, maxRows: 6 }"
:disabled="props.isGenerating || props.disabled"
:class="{ 'voice-input-hidden': voiceMode }"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="voiceMode || props.isGenerating || props.disabled"
:maxlength="props.maxLength"
:placeholder="props.placeholder"
@focus="inputFocused = true"
@blur="inputFocused = false"
:aria-hidden="voiceMode"
/>
<div
v-if="voiceHitVisible"
class="voice-hit"
<button
v-if="voiceMode"
ref="holdRef"
class="voice-hold"
:class="{ active: voicePressing, cancel: willCancel }"
type="button"
:disabled="props.disabled || props.isGenerating"
@pointerdown="handleVoicePointerDown"
@pointermove="handleVoicePointerMove"
@pointerup="handleVoicePointerUp"
@pointercancel="handleVoicePointerCancel"
@contextmenu.prevent
/>
>
<t-icon name="voice-wave" size="small" />
<span v-text="voiceHoldLabel" />
</button>
</div>
<div class="actions">
<div class="tools">
@@ -93,13 +86,49 @@
<t-button
class="send"
type="button"
size="extra-small"
size="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"
@@ -109,11 +138,15 @@
<t-button
class="send"
type="submit"
size="extra-small"
size="small"
theme="primary"
:disabled="props.disabled"
:content="sendButtonText"
/>
:content="props.sendText"
>
<template #icon>
<t-icon name="send-1" />
</template>
</t-button>
</slot>
</div>
</t-form>
@@ -121,7 +154,7 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, useTemplateRef, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, ref, useTemplateRef, watch } from "vue";
defineOptions({
name: "AiChatComposer"
@@ -137,22 +170,18 @@ export interface Props {
stopText?: string;
retryText?: string;
maxLength?: number;
/** 是否启用长按输入框语音输入 */
/** 是否启用语音输入 */
voiceEnabled?: boolean;
/** 语音识别状态,由业务侧驱动 */
voiceState?: "idle" | "listening" | "processing";
/** 语音中间结果 */
voiceText?: string;
/** 松开发送提示,同时作为按住时的发送按钮文案 */
/** 按住说话提示 */
voiceHoldText?: string;
/** 按住时的提示 */
voiceSendHint?: string;
/** 上滑到取消按钮时的提示 */
/** 移出按住按钮时的提示 */
voiceCancelHint?: string;
/** 上滑到保留按钮时的提示 */
voiceKeepHint?: string;
/** 取消发送按钮文案 */
voiceCancelText?: string;
/** 保留识别按钮文案 */
voiceKeepText?: string;
/** 正在聆听提示 */
voiceListeningText?: string;
/** 正在识别提示 */
@@ -171,11 +200,9 @@ const props = withDefaults(defineProps<Props>(), {
voiceEnabled: false,
voiceState: "idle",
voiceText: "",
voiceSendHint: "松开发送",
voiceCancelHint: "松开取消",
voiceKeepHint: "松开保留",
voiceCancelText: "取消发送",
voiceKeepText: "保留识别",
voiceHoldText: "按住 说话",
voiceSendHint: "松开 发送",
voiceCancelHint: "松开 取消",
voiceListeningText: "正在听你说…",
voiceProcessingText: "正在识别…"
});
@@ -189,71 +216,55 @@ const emit = defineEmits<{
"add-attachment": [];
"voice-start": [];
"voice-stop": [];
"voice-keep": [];
"voice-cancel": [];
}>();
/** 长按触发语音的阈值,短按仍然聚焦输入 */
const VOICE_HOLD_DELAY = 300;
/** 未触发语音时,手指移动超过该距离视为滑动 */
const VOICE_MOVE_TOLERANCE = 12;
/** 按钮命中区域外扩,避免边缘难以对准;需小于按钮间距,防止两个按钮重叠 */
const VOICE_ACTION_HIT_PADDING = 4;
type VoiceAction = "cancel" | "keep" | "send";
const textareaRef = useTemplateRef<{ focus: () => void }>("textareaRef");
const cancelActionRef = useTemplateRef<HTMLElement>("cancelActionRef");
const keepActionRef = useTemplateRef<HTMLElement>("keepActionRef");
const inputFocused = ref(false);
const holdRef = useTemplateRef<HTMLElement>("holdRef");
const voiceMode = ref(false);
const voicePressing = ref(false);
const voiceTriggered = ref(false);
const willCancel = ref(false);
const willKeep = ref(false);
const voiceSessionActive = ref(false);
const voiceKeepPending = ref(false);
let voiceTimer: number | undefined;
let voiceStartY = 0;
let voicePointerId: number | undefined;
/** 输入框为空且未聚焦时才接管长按;识别中保持覆盖层以持续接收指针事件 */
const voiceHitVisible = computed(() => props.voiceEnabled
&& !props.disabled
&& !props.isGenerating
&& (voicePressing.value || (!draft.value.trim() && !inputFocused.value && props.voiceState === "idle")));
const voiceTranscript = computed(() => props.voiceText.trim());
const voiceActive = computed(() => voicePressing.value && voiceTriggered.value);
const voiceActionsVisible = computed(() => voiceActive.value);
const voiceStatusText = computed(() => {
const voiceHoldLabel = computed(() => {
if (willCancel.value) {
return props.voiceCancelHint;
}
if (willKeep.value) {
return props.voiceKeepHint;
if (props.voiceState === "processing") {
return props.voiceProcessingText;
}
return props.voiceState === "processing" ? props.voiceProcessingText : props.voiceListeningText;
if (voicePressing.value) {
return props.voiceSendHint;
}
if (props.voiceState === "listening") {
return props.voiceListeningText;
}
return props.voiceHoldText;
});
const sendButtonText = computed(() => voiceActive.value ? props.voiceSendHint : props.sendText);
/** ASR 结果直接写进输入框;取消后停止同步,保留后忽略调用方清空 voiceText 的动作 */
watch(() => props.voiceText, (text) => {
if (!voiceSessionActive.value) {
return;
const voiceTranscriptHint = computed(() => {
if (voiceTranscript.value) {
return "";
}
if (voiceKeepPending.value && !text) {
return;
if (props.voiceState === "processing") {
return props.voiceProcessingText;
}
draft.value = text;
if (voicePressing.value || props.voiceState === "listening") {
return props.voiceListeningText;
}
return "";
});
watch(() => props.voiceState, (state) => {
if (state === "idle" && voiceSessionActive.value) {
voiceSessionActive.value = false;
voiceKeepPending.value = false;
watch(() => props.voiceEnabled, (enabled) => {
if (enabled) {
return;
}
if (voicePressing.value) {
cancelVoice();
}
voiceMode.value = false;
});
function startNewConversation(): void {
@@ -283,130 +294,94 @@ function submitMessage(): void {
emit("send", message);
}
function handleVoicePointerDown(event: PointerEvent): void {
function enterVoiceMode(): 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;
willKeep.value = false;
voiceSessionActive.value = false;
voiceKeepPending.value = false;
voiceStartY = event.clientY;
voicePointerId = event.pointerId;
event.preventDefault();
try {
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
} catch {
// 指针捕获失败时仍可依赖冒泡事件,忽略
}
voiceTimer = window.setTimeout(() => {
if (!voicePressing.value) {
return;
}
voiceTriggered.value = true;
voiceSessionActive.value = true;
voiceKeepPending.value = false;
draft.value = "";
navigator.vibrate?.(15);
emit("voice-start");
}, VOICE_HOLD_DELAY);
// 监听 window,手指移出按钮后仍能收到移动、释放和取消
window.addEventListener("pointermove", handleVoicePointerMove);
window.addEventListener("pointerup", handleVoicePointerUp);
window.addEventListener("pointercancel", handleVoicePointerCancel);
navigator.vibrate?.(15);
emit("voice-start");
}
function handleVoicePointerMove(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
return;
}
if (!voiceTriggered.value) {
if (Math.abs(event.clientY - voiceStartY) > VOICE_MOVE_TOLERANCE) {
resetVoicePress();
}
return;
}
const action = resolveVoiceAction(event);
willCancel.value = action === "cancel";
willKeep.value = action === "keep";
willCancel.value = !isPointInsideHold(event);
}
function resolveVoiceAction(event: PointerEvent): VoiceAction {
if (isPointInsideAction(event, cancelActionRef.value)) {
return "cancel";
}
if (isPointInsideAction(event, keepActionRef.value)) {
return "keep";
}
return "send";
}
function isPointInsideAction(event: PointerEvent, element: HTMLElement | null): boolean {
function isPointInsideHold(event: PointerEvent): boolean {
const element = holdRef.value;
if (!element) {
return false;
}
const rect = element.getBoundingClientRect();
return event.clientX >= rect.left - VOICE_ACTION_HIT_PADDING
&& event.clientX <= rect.right + VOICE_ACTION_HIT_PADDING
&& event.clientY >= rect.top - VOICE_ACTION_HIT_PADDING
&& event.clientY <= rect.bottom + VOICE_ACTION_HIT_PADDING;
return event.clientX >= rect.left
&& event.clientX <= rect.right
&& event.clientY >= rect.top
&& event.clientY <= rect.bottom;
}
function handleVoicePointerUp(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
return;
}
const triggered = voiceTriggered.value;
const action = resolveVoiceAction(event);
resetVoicePress();
if (!triggered) {
textareaRef.value?.focus();
return;
}
if (action === "cancel") {
if (!isPointInsideHold(event)) {
cancelVoice();
return;
}
if (action === "keep") {
voiceKeepPending.value = true;
emit("voice-keep");
return;
}
resetVoicePress();
emit("voice-stop");
}
function handleVoicePointerCancel(): void {
if (!voicePressing.value) {
function handleVoicePointerCancel(event: PointerEvent): void {
if (!voicePressing.value || event.pointerId !== voicePointerId) {
return;
}
const triggered = voiceTriggered.value;
resetVoicePress();
if (triggered) {
cancelVoice();
}
cancelVoice();
}
function cancelVoice(): void {
voiceSessionActive.value = false;
voiceKeepPending.value = false;
draft.value = "";
resetVoicePress();
emit("voice-cancel");
}
function resetVoicePress(): void {
if (voiceTimer !== undefined) {
window.clearTimeout(voiceTimer);
voiceTimer = undefined;
}
window.removeEventListener("pointermove", handleVoicePointerMove);
window.removeEventListener("pointerup", handleVoicePointerUp);
window.removeEventListener("pointercancel", handleVoicePointerCancel);
voicePressing.value = false;
voiceTriggered.value = false;
willCancel.value = false;
willKeep.value = false;
voicePointerId = undefined;
}
onBeforeUnmount(() => {
if (voiceTimer !== undefined) {
window.clearTimeout(voiceTimer);
if (voicePressing.value) {
emit("voice-cancel");
}
resetVoicePress();
});
</script>
@@ -453,9 +428,12 @@ onBeforeUnmount(() => {
flex-direction: column;
.input-wrap {
gap: .375rem;
display: flex;
position: relative;
flex: 1;
min-width: 0;
flex-direction: column;
}
.input {
@@ -463,115 +441,118 @@ onBeforeUnmount(() => {
width: 100%;
padding: 0 .25rem;
min-width: 0;
&.voice-input-hidden {
visibility: hidden;
}
}
.voice-hit {
inset: 0;
z-index: 1;
position: absolute;
touch-action: none;
-webkit-tap-highlight-color: transparent;
}
.voice-actions {
gap: .375rem;
.voice-transcript {
left: 50%;
gap: .5rem;
width: 100%;
z-index: 3;
display: flex;
padding: .5rem;
padding: .5rem .75rem;
position: absolute;
box-sizing: border-box;
bottom: calc(100% + .5rem);
user-select: none;
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-actions-in .16s ease-out;
animation: voice-transcript-in .16s ease-out;
border-radius: 1rem;
flex-direction: column;
transform: translateX(-50%);
}
.voice-status {
gap: .375rem;
display: flex;
min-height: 1.25rem;
color: var(--td-text-color-secondary);
font-size: .75rem;
align-items: center;
justify-content: center;
.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;
&.active {
color: var(--td-brand-color);
border-bottom-color: var(--td-brand-color);
}
.voice-wave {
gap: .1875rem;
height: .875rem;
display: flex;
align-items: center;
span {
width: .125rem;
height: 30%;
border-radius: .125rem;
background: var(--td-brand-color);
animation: voice-wave .9s ease-in-out infinite;
animation-delay: calc(var(--i) * .1s);
}
&.cancel {
color: var(--td-error-color);
border-bottom-color: var(--td-error-color);
}
.voice-status-text {
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.voice-buttons {
gap: .5rem;
display: flex;
}
.voice-action {
gap: .25rem;
flex: 1;
display: flex;
padding: .4375rem .5rem;
font-size: .75rem;
transition: color .15s, background .15s, border-color .15s, transform .15s;
border: 1px solid var(--td-component-border);
border-radius: .625rem;
align-items: center;
justify-content: center;
&.cancel {
color: var(--td-error-color);
}
&.keep {
color: var(--td-brand-color);
}
&.active {
color: #fff;
transform: translateY(-.0625rem);
}
&.cancel.active {
border-color: var(--td-error-color);
background: var(--td-error-color);
}
&.keep.active {
border-color: var(--td-brand-color);
background: var(--td-brand-color);
}
&:disabled {
opacity: .55;
}
}
.actions {
--td-button-border-radius: .75rem;
--td-button-border-radius: 1rem;
gap: .5rem;
min-height: 2rem;
margin-top: .375rem;
display: flex;
align-items: center;
@@ -582,44 +563,53 @@ onBeforeUnmount(() => {
display: flex;
align-items: center;
}
.send {
padding: 0 1rem;
}
}
}
&.voice-active .form {
border-color: var(--td-brand-color);
animation: voice-breathe 1.8s ease-in-out infinite;
}
}
@keyframes voice-wave {
0%,
100% {
height: 25%;
opacity: .5;
}
50% {
height: 100%;
opacity: 1;
&::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% {
box-shadow: 0 0 0 .125rem var(--td-brand-color-light, rgba(0, 82, 217, .16)), 0 .5rem 1.5rem rgba(15, 23, 42, .12);
opacity: .6;
transform: scaleX(1) scaleY(1);
}
50% {
box-shadow: 0 0 0 .375rem var(--td-brand-color-light, rgba(0, 82, 217, .16)), 0 .5rem 1.5rem rgba(15, 23, 42, .12);
opacity: .2;
transform: scaleX(1.02) scaleY(1.08);
}
}
@keyframes voice-actions-in {
@keyframes voice-wave {
0%,
100% {
opacity: .5;
transform: scaleY(.3);
}
50% {
opacity: 1;
transform: scaleY(1);
}
}
@keyframes voice-transcript-in {
from {
opacity: 0;
}
@@ -629,14 +619,6 @@ onBeforeUnmount(() => {
}
}
@media (prefers-reduced-motion: reduce) {
.composer.voice-active .form,
.voice-actions,
.voice-actions .voice-wave span {
animation: none;
}
}
:global(html.theme-dark) {
.error-bar {
color: var(--ai-chat-error-color-dark, #fda29b);