搭建页面内容

This commit is contained in:
huangzhe
2025-07-28 10:17:29 +08:00
parent 77d8507d3b
commit dced4d6ca5
12 changed files with 1660 additions and 32 deletions

View File

@@ -0,0 +1,601 @@
<template>
<div>
<div class="new-session">
<button @click="startNewConversation" class="active">
<svg-icon icon-class="add" class-name="chat-icon" style="color: #000;"></svg-icon>
开启新会话
</button>
</div>
<div v-if="isVoiceMode && newMessage" class="isVoiceModeText">
<textarea class="textarea" placeholder="请输入内容" v-model="newMessage"></textarea>
</div>
<footer class="chat-footer">
<!-- 输入框 or 按住说话提示 -->
<div class="input-wrapper ml10">
<input v-if="!isVoiceMode" type="text" v-model="newMessage" placeholder="请简短描述您的问题"
@keyup.enter="sendMessage" />
<div v-else class="voice-hint-container" :class="{ disabled: messageStatus === 'send' }"
@mousedown="startRecording" @selectstart="() => false" @mouseup="stopRecording" @mouseleave="stopRecording"
@touchend="stopRecording" @touchstart="startRecording">
<div class="waveform" :class="{ active: isRecording }">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</div>
<!-- <div class="hint-text" v-if='!isRecording'>按住说话</div>-->
</div>
</div>
<!-- 语音按钮按住说话 -->
<button @click="isVoiceMode = !isVoiceMode" class="mic-button ml10 mr10">
<!-- <svg-icon v-if="!isVoiceMode" icon-class="voice" class-name="chat-icon ml10 wh25"></svg-icon>
<span v-else class="ml15 mr5 input-icon"></span> -->
</button>
<!-- 发送按钮 -->
<button @click="sendMessage" :disabled="messageStatus === 'send'" :class="{ disabled: messageStatus === 'send' }"
class="mr10 fs16">发送</button>
</footer>
<section class="section pb10">
<!-- <button @click="searchInternet" :class="{ active: isSearching }" class="ml10">
<svg-icon icon-class="earth" class-name="chat-icon"></svg-icon>
联网搜索
</button> -->
<button @click="deepInternet" :class="{ active: isDeep }">
<svg-icon icon-class="think" class-name="chat-icon"></svg-icon>
深度思考
</button>
<!-- <button @click="startNewConversation" class="active">
<svg-icon icon-class="add" class-name="chat-icon"></svg-icon>
新建会话
</button> -->
</section>
</div>
</template>
<script>
import SvgIcon from '@/components/svg-icon/index.vue'
import { audioToText, chat, chatProduct } from '@/api/generatedApi'
export default {
components: {
SvgIcon,
},
props: {
messages: {
type: Array,
default: () => [],
},
messageStatus: {
type: String,
default: 'stop',
},
isDeep: {
type: Boolean,
default: false,
},
isSearching: {
type: Boolean,
default: false,
},
conversationId: {
type: String,
default: '',
},
productName: {
type: String,
default: '',
},
autoScrollEnabled: {
type: Boolean,
default: false,
},
chatData: {
type: Object,
default: () => ({}),
},
},
data() {
return {
isThink: false,
newMessage: '',
isRecording: false,
mediaRecorder: null,
audioChunks: [],
isRecognizing: false,
isVoiceMode: false,
answerMap: '',
currentMessage: null,
// 打字机相关
typingText: '',
typingQueue: [],
typingQueueText: [],
isTyping: false,
typingSpeed: 30,
typingTimeout: null,
}
},
methods: {
deepInternet() {
this.$emit('update:isDeep', !this.isDeep)
},
searchInternet() {
this.$emit('update:isSearching', !this.isSearching)
},
startNewConversation() {
this.$emit('update:messages', [])
this.$emit('update:conversationId', '')
this.$emit('update:productName', '')
},
async startRecording() {
if (this.messageStatus === 'send') return
if (this.isRecognizing) return
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
this.mediaRecorder = new MediaRecorder(stream)
this.audioChunks = []
this.mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
this.audioChunks.push(event.data)
}
}
this.mediaRecorder.onstop = () => {
this.handleStopRecording()
}
this.mediaRecorder.start()
this.isRecording = true
} catch (err) {
alert('无法访问麦克风,请检查权限')
console.error(err)
}
},
hasTreasureBox() {
chatProduct({ query: this.newMessage })
.then((res) => {
if (res) {
this.messageStatus = 'stop'
this.messages.push({ type: 'box', text: this.newMessage, detail: res.content })
this.newMessage = ''
}
})
.catch(() => {
this.messageStatus = 'stop'
})
},
stopRecording() {
if (this.mediaRecorder && this.isRecording) {
this.mediaRecorder.stop()
this.isRecording = false
}
},
async handleStopRecording() {
this.isRecognizing = true
const blob = new Blob(this.audioChunks, { type: 'audio/webm' })
try {
const text = await this.callVoiceRecognitionAPI(blob)
if (text) {
this.newMessage = text
this.$emit('update:messageStatus', 'stop')
}
} catch (error) {
console.error('语音识别失败:', error)
this.newMessage = ''
} finally {
this.isRecognizing = false
}
},
callVoiceRecognitionAPI(blob) {
return new Promise((resolve, reject) => {
const formData = new FormData()
formData.append('file', blob)
formData.append('appType', 'haslBigHelper')
formData.append('user', 'chenyuda')
audioToText(formData)
.then((res) => {
if (res) {
resolve(res.content)
}
})
.catch((err) => {
reject(err)
})
})
},
axiosGetAiChat() {
const abortController = new AbortController()
this.currentMessage = JSON.parse(
JSON.stringify({
type: 'bot',
text: '',
isThink: this.isDeep,
showThink: true,
think: '',
isLike: false,
isDisLike: false,
})
)
this.messages.push(this.currentMessage)
let params = {
query: this.newMessage,
isDeep: this.isDeep ? 1 : 0,
isOnline: this.isSearching ? 1 : 0,
user: 'chenyuda',
conversationId: this.conversationId,
productName: this.productName,
}
// 如果有自定义参数
if (this.chatData) {
for (let k in this.chatData) {
params[k] = this.chatData[k]
}
}
if (this.$route.query.compareId) {
params.compareResult = JSON.parse(sessionStorage.getItem('results'))
}
fetch(chat(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: abortController.signal,
body: JSON.stringify(params),
})
.then(async (res) => {
this.newMessage = ''
await this.processStreamResponse(res)
})
.catch((err) => {
this.$emit('update:messageStatus', 'stop')
})
},
async processStreamResponse(response) {
if (!response.ok) throw new Error(`HTTP错误: ${response.status}`)
if (!response.body) {
console.error('响应体不存在:', response)
return
}
const reader = response.body.getReader()
let buffer = ''
while (true) {
try {
const { done, value } = await reader.read()
if (done) break
buffer += new TextDecoder().decode(value)
const lines = buffer.split('\n')
lines.slice(0, -1).forEach((line) => {
const parsed = this.parseStreamLine(line)
if (parsed) this.updateMessageContent(parsed)
})
buffer = lines[lines.length - 1] || ''
} catch (error) {
console.error('读取流数据时发生错误:', error)
break
}
}
},
parseStreamLine(line) {
try {
const cleanLine = line.replace(/^data:\s*/, '')
if (!cleanLine) return null
const data = JSON.parse(cleanLine)
if (data.answer) {
this.answerMap += data.answer
}
return this.updateConversationState(data)
} catch (error) {
console.error('流数据解析失败:', error)
return null
}
},
updateConversationState(data) {
this.$emit('update:conversationId', data.conversation_id || '')
if (data.answer && data.answer.indexOf('<think>') !== -1) {
data.isThink = true
this.isThink = true
this.$emit('getIsThink', true)
}
if (data.answer && data.answer.indexOf('</think>') !== -1) {
data.isThink = true
this.isThink = false
this.$emit('getIsThink', false)
}
if (data.answer && this.isThink) {
data.isThink = true
}
if (data.answer && !this.isThink) {
data.isThink = false
}
return data
},
updateMessageContent(parse) {
let { event, answer, isThink } = parse
if (event === 'message_end') {
this.$emit('update:messageStatus', 'stop')
}
if (!this.currentMessage || !answer) return
const mode = isThink ? 'think' : 'text'
const chars = {
answer: answer,
isThink: isThink,
}
this.typingQueue.push(chars)
if (!this.isTyping) {
this.startTypingAnimation(mode)
}
},
startTypingAnimation() {
this.isTyping = true
const typeNextChar = () => {
if (this.typingQueue.length === 0) {
this.isTyping = false
return
}
// 取出一个完整文本块
const chunk = this.typingQueue.shift()
const chars = chunk.answer.split('')
const isThink = chunk.isThink
// 内部递归函数,用于逐字输出当前块
const outputChar = () => {
if (chars.length === 0) {
// 当前块输出完毕,继续处理下一个
setTimeout(typeNextChar, 10)
return
}
const char = chars.shift()
this.currentMessage[isThink ? 'think' : 'text'] += char
const delay = this.getTypingDelay(char)
setTimeout(outputChar, delay)
}
outputChar()
}
typeNextChar()
},
getTypingDelay(char) {
if (['。', '', '', '', '\n'].includes(char)) {
return this.typingSpeed * 3
}
return this.typingSpeed
},
sendMessage() {
if (this.messageStatus === 'send') return
if (this.newMessage.trim() === '') return
this.newMessage = this.newMessage.replace(/<[^>]+>/g, '')
this.messages.push({ type: 'user', text: this.newMessage })
this.$emit('update:messageStatus', 'send')
if (this.newMessage.includes('工具箱')) {
this.hasTreasureBox()
return
}
this.$emit('update:autoScrollEnabled', true)
this.axiosGetAiChat()
},
cellClick(item) {
console.log(item);
const productName = item.title
this.messages.push({ type: 'user', text: productName })
this.$emit('update:messageStatus', 'send')
this.$emit('update:autoScrollEnabled', true)
this.axiosGetAiChat()
}
}
}
</script>
<style lang="scss" scoped>
$primary-color: #2e5ca9;
$primary-text-color: #f6aa21;
$primary-trans-color: rgba(135, 162, 208, 0.5);
.input-icon {
font-size: 20px;
color: #707070;
}
.wh25 {
width: 25px;
height: 25px;
}
.isVoiceModeText {
display: flex;
textarea {
flex: 1;
max-height: 80px;
resize: none;
background: #fff;
outline: none;
overflow-y: auto;
padding: 10px;
border: none;
}
}
.section {
font-size: 13px;
display: flex;
align-items: center;
padding: 10px 10px 0 10px;
background-color: #fff;
gap: 10px;
button {
padding: 4px 8px;
border: none;
background-color: $primary-trans-color;
color: #fff;
font-weight: 600;
border-radius: 20px;
cursor: pointer;
}
}
.new-session {
position: absolute;
width: fit-content;
background-color: transparent;
left: 50%;
transform: translateX(-50%);
bottom: 80px;
button{
border-radius: 10px;
border: 1px solid #090909;
margin-bottom: 15px;
padding: 5px 10px;
}
}
.chat-footer {
display: flex;
align-items: center;
padding: 10px 10px 0 10px;
//padding-bottom: constant(safe-area-inset-bottom);
//padding-bottom: env(safe-area-inset-bottom);
background-color: #fff;
.input-wrapper {
flex: 1;
margin-right: 10px;
input {
width: 100%;
padding: 10px;
border: none;
background: #f5f5f5;
border-radius: 5px;
font-size: 14px;
}
.voice-hint-container {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 10px;
background-color: #f5f5f5;
border-radius: 5px;
color: #888;
font-size: 14px;
//-webkit-user-select: none;
//-moz-user-select: none;
//-ms-user-select: none;
//user-select: none;
&:active {
background-color: #eaeaea;
}
.waveform {
display: flex;
align-items: flex-end;
align-items: center;
//height: 30px;
//width: 60px;
gap: 2px;
&.disabled {
cursor: not-allowed;
background: red;
}
&.active .bar {
animation: wave-animation 1s infinite ease-in-out;
}
.bar {
width: 4px;
background-color: $primary-color;
margin: 0 1px;
&:nth-child(1) {
height: 10px;
animation-delay: 0s;
}
&:nth-child(2) {
height: 16px;
animation-delay: 0.1s;
}
&:nth-child(3) {
height: 12px;
animation-delay: 0.2s;
}
&:nth-child(4) {
height: 18px;
animation-delay: 0.3s;
}
&:nth-child(5) {
height: 14px;
animation-delay: 0.4s;
}
}
}
.hint-text {
margin-top: 4px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
}
}
.mic-button {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
border: none;
background: transparent;
color: $primary-color;
cursor: pointer;
font-size: 12px;
margin-left: 5px;
&:active {
color: #e6454a;
/* 按下变红 */
}
}
button {
border: none;
outline: none;
color: $primary-text-color;
border-radius: 5px;
background: transparent;
font-weight: 600;
cursor: pointer;
}
.disabled {
pointer-events: none;
opacity: 0.5;
}
}
@keyframes wave-animation {
0%,
100% {
transform: scaleY(1);
}
50% {
transform: scaleY(1.5);
}
}
</style>