feat(小程序): 优化玩伴会话与家长发消息

This commit is contained in:
stu2not
2026-04-22 17:25:49 +08:00
parent f21e0afcd0
commit 6947ead855
5 changed files with 969 additions and 390 deletions

View File

@@ -70,6 +70,7 @@
flex: 1;
overflow-y: auto;
padding: 24px;
box-sizing: border-box;
}
.time-divider {
@@ -92,16 +93,33 @@
&.user {
flex-direction: row-reverse;
.message-main {
align-items: flex-end;
}
}
&.ai {
.ai-avatar {
&.peer {
.peer-avatar {
margin-right: 14px;
flex-shrink: 0;
}
}
}
.message-main {
display: flex;
flex-direction: column;
max-width: 76%;
}
.message-meta {
display: block;
font-size: 22px;
color: #999999;
margin-bottom: 8px;
}
.user-avatar {
width: 68px;
height: 68px;
@@ -117,7 +135,7 @@
}
}
.ai-avatar {
.peer-avatar {
width: 68px;
height: 68px;
background: #FEF3E8;
@@ -132,7 +150,7 @@
}
.message-bubble {
max-width: 68%;
max-width: 100%;
padding: 18px 22px;
font-size: 30px;
line-height: 1.5;
@@ -148,7 +166,7 @@
margin-right: 14px;
}
.ai & {
.peer & {
background: #FFFFFF;
color: #1A1A1A;
border-radius: 20px 20px 20px 6px;
@@ -156,51 +174,53 @@
}
}
.audio-message {
.empty-chat {
min-height: 320px;
display: flex;
align-items: center;
justify-content: center;
}
.audio-icon {
width: 48px;
height: 48px;
background: rgba(255, 255, 255, 0.3);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
color: inherit;
margin-right: 14px;
flex-shrink: 0;
transition: background 0.2s;
.empty-chat-text {
font-size: 28px;
color: #999999;
}
&.playing {
background: rgba(255, 255, 255, 0.6);
}
.composer {
background: #FFFFFF;
border-top: 1px solid #EEEEEE;
padding: 18px 20px calc(18px + env(safe-area-inset-bottom));
display: flex;
align-items: center;
gap: 16px;
}
&.orange {
background: rgba(255, 140, 66, 0.2);
&.playing {
background: rgba(255, 140, 66, 0.4);
}
}
}
.composer-input {
flex: 1;
min-height: 76px;
background: #F5F7FA;
border-radius: 38px;
padding: 0 24px;
font-size: 28px;
color: #1A1A1A;
}
.audio-info {
display: flex;
flex-direction: column;
.composer-send {
min-width: 132px;
height: 76px;
border-radius: 38px;
background: #FF8C42;
display: flex;
align-items: center;
justify-content: center;
.audio-title {
font-size: 28px;
font-weight: 500;
color: inherit;
margin-bottom: 4px;
}
.audio-duration {
font-size: 24px;
opacity: 0.8;
}
&.disabled {
opacity: 0.55;
}
}
.composer-send-text {
font-size: 28px;
color: #FFFFFF;
font-weight: 600;
}

View File

@@ -1,83 +1,162 @@
import { View, Text, ScrollView, Image } from '@tarojs/components'
import { useState, useEffect, useRef } from 'react'
import { View, Text, ScrollView, Image, Input } from '@tarojs/components'
import { useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { getMessages, getCharacter, ChatMessage, Character } from '../../../services/chat'
import {
getMessages,
getCharacter,
sendParentMessage,
ChatMessage,
Character,
ConversationSource,
PeerKind,
} from '../../../services/chat'
import './index.scss'
function normalizePeerKind(value?: string): PeerKind {
if (value === 'child' || value === 'parent' || value === 'ai') return value
return 'ai'
}
function normalizeSource(value?: string): ConversationSource {
return value === 'im' ? 'im' : 'ai'
}
function normalizeNumericId(value?: string): number | null {
const normalized = Number(value)
if (!Number.isFinite(normalized) || normalized <= 0) return null
return normalized
}
function formatParticipantLabel(message: ChatMessage): string {
const senderType = message.senderType || 'unknown'
const senderId = message.senderId || '--'
const name = message.senderName || ''
if (senderType === 'parent') {
return name === '我' ? '我' : name || '家长'
}
if (senderType === 'child') {
return name || `儿童ID ${senderId}`
}
if (senderType === 'device') {
return name || `设备ID ${senderId}`
}
if (senderType === 'ai') {
return name || 'AI'
}
return `${senderType} ${senderId}`
}
export default function ChatDetail() {
const router = useRouter()
const { id } = router.params
const conversationId = parseInt(id || '1')
const params = router.params
const initialConversationId = normalizeNumericId(params.id) || 0
const conversationSource = normalizeSource(params.source)
const conversationPeerKind = normalizePeerKind(params.peerKind)
const decodedRoleKey = decodeURIComponent(params.roleKey || '')
const decodedName = decodeURIComponent(params.name || '玩伴')
const decodedConversationTypeName = decodeURIComponent(params.conversationTypeName || '')
const decodedPeerId = decodeURIComponent(params.peerId || '')
const decodedDeviceId = decodeURIComponent(params.deviceId || '')
const decodedChildName = decodeURIComponent(params.childName || '')
const childId = normalizeNumericId(params.childId)
const parentUserId = normalizeNumericId(params.parentUserId)
const canSend = params.canSend === '1'
const [activeConversationId, setActiveConversationId] = useState(initialConversationId)
const [character, setCharacter] = useState<Character>({
id: conversationId,
name: decodeURIComponent(router.params.name || 'AI 玩伴'),
description: '温柔音色 / 开朗耐心',
icon: '🎤'
id: initialConversationId,
name: decodedName,
description: '交流记录',
icon: '🤖',
source: conversationSource,
peerKind: conversationPeerKind,
conversationTypeName: decodedConversationTypeName,
childId,
childName: decodedChildName,
peerId: decodedPeerId,
parentUserId,
deviceId: decodedDeviceId,
channelLabel: '--',
canSend,
})
const [messages, setMessages] = useState<ChatMessage[]>([])
const [playingId, setPlayingId] = useState<number | null>(null)
const audioCtx = useRef<Taro.InnerAudioContext | null>(null)
const [loading, setLoading] = useState(true)
const [inputText, setInputText] = useState('')
const [sending, setSending] = useState(false)
useEffect(() => {
loadChatData()
return () => {
// 页面卸载时销毁音频
audioCtx.current?.destroy()
void loadChatData(activeConversationId)
}, [activeConversationId, conversationSource, conversationPeerKind])
const loadChatData = async (conversationId: number) => {
setLoading(true)
try {
const char = await getCharacter({
conversationId,
source: conversationSource,
peerKind: conversationPeerKind,
name: decodedName,
roleKey: decodedRoleKey,
conversationTypeName: decodedConversationTypeName,
childId,
childName: decodedChildName,
peerId: decodedPeerId,
parentUserId,
deviceId: decodedDeviceId,
canSend,
})
if (char) {
setCharacter(char)
Taro.setNavigationBarTitle({ title: char.name })
}
const msgs = await getMessages(conversationId, conversationSource, decodedConversationTypeName)
setMessages(msgs)
} catch (error: any) {
console.error('[chat-detail] load failed:', error)
Taro.showToast({
title: error?.message || '加载失败,请稍后重试',
icon: 'none',
})
} finally {
setLoading(false)
}
}, [conversationId])
const loadChatData = async () => {
const char = await getCharacter(conversationId)
if (char) {
setCharacter(char)
Taro.setNavigationBarTitle({ title: char.name })
}
const msgs = await getMessages(conversationId)
setMessages(msgs)
}
const handlePlayAudio = (msg: ChatMessage) => {
if (!msg.audioUrl) return
// 如果点的是正在播放的那条,就停止
if (playingId === msg.id) {
audioCtx.current?.stop()
audioCtx.current?.destroy()
audioCtx.current = null
setPlayingId(null)
return
}
// 停掉上一条
audioCtx.current?.stop()
audioCtx.current?.destroy()
const ctx = Taro.createInnerAudioContext()
ctx.src = msg.audioUrl
ctx.autoplay = true
ctx.onPlay(() => setPlayingId(msg.id))
ctx.onEnded(() => {
setPlayingId(null)
ctx.destroy()
audioCtx.current = null
})
ctx.onError(() => {
setPlayingId(null)
ctx.destroy()
audioCtx.current = null
Taro.showToast({ title: '播放失败', icon: 'none' })
})
audioCtx.current = ctx
}
const handleBack = () => {
audioCtx.current?.stop()
audioCtx.current?.destroy()
Taro.navigateBack()
}
const handleSend = async () => {
const normalizedContent = inputText.trim()
if (!normalizedContent || sending) return
if (!character.canSend || !character.childId) {
Taro.showToast({ title: '当前会话不支持发送', icon: 'none' })
return
}
setSending(true)
try {
const response = await sendParentMessage(character.childId, normalizedContent)
setInputText('')
if (response.conversation_id && response.conversation_id !== activeConversationId) {
setActiveConversationId(response.conversation_id)
} else {
await loadChatData(activeConversationId)
}
Taro.showToast({ title: '已发送', icon: 'success' })
} catch (error: any) {
console.error('[chat-detail] send failed:', error)
Taro.showToast({
title: error?.message || '发送失败,请重试',
icon: 'none',
})
} finally {
setSending(false)
}
}
return (
<View className='chat-detail-page'>
<View className='chat-header'>
@@ -95,62 +174,72 @@ export default function ChatDetail() {
</View>
</View>
<ScrollView className='chat-list' scrollY>
{messages.map((msg, index) => (
<View key={msg.id}>
{(index === 0 || messages[index - 1].type !== msg.type ||
messages[index - 1].time !== msg.time) && (
<View className='time-divider'>
<Text>{msg.time}</Text>
</View>
)}
{msg.type === 'user' ? (
<View className='message-item user'>
<View className='message-bubble'>
{msg.isAudio ? (
<View className='audio-message' onClick={() => handlePlayAudio(msg)}>
<View className={`audio-icon ${playingId === msg.id ? 'playing' : ''}`}>
{playingId === msg.id ? '⏸' : '▶'}
</View>
<View className='audio-info'>
<Text className='audio-title'></Text>
<Text className='audio-duration'>{msg.audioDuration}</Text>
</View>
</View>
) : (
<Text>{msg.content}</Text>
)}
</View>
<View className='user-avatar'>
<Text className='avatar-img'>👦</Text>
</View>
</View>
) : (
<View className='message-item ai'>
<View className='ai-avatar'>
<Text className='robot-emoji'>{character.icon}</Text>
</View>
<View className='message-bubble'>
{msg.isAudio ? (
<View className='audio-message' onClick={() => handlePlayAudio(msg)}>
<View className={`audio-icon orange ${playingId === msg.id ? 'playing' : ''}`}>
{playingId === msg.id ? '⏸' : '▶'}
</View>
<View className='audio-info'>
<Text className='audio-title'></Text>
<Text className='audio-duration'>{msg.audioDuration}</Text>
</View>
</View>
) : (
<Text>{msg.content}</Text>
)}
</View>
</View>
)}
<ScrollView className='chat-list' scrollY scrollWithAnimation>
{loading ? (
<View className='empty-chat'>
<Text className='empty-chat-text'>...</Text>
</View>
))}
) : messages.length === 0 ? (
<View className='empty-chat'>
<Text className='empty-chat-text'>
{character.canSend ? '还没有消息,发送第一条吧' : '这个会话还没有消息'}
</Text>
</View>
) : (
messages.map((msg, index) => (
<View key={msg.id}>
{(index === 0 || messages[index - 1].time !== msg.time) && (
<View className='time-divider'>
<Text>{msg.time}</Text>
</View>
)}
{msg.type === 'user' ? (
<View className='message-item user'>
<View className='message-main'>
<Text className='message-meta'>{formatParticipantLabel(msg)}</Text>
<View className='message-bubble'>
<Text>{msg.content}</Text>
</View>
</View>
<View className='user-avatar'>
<Text className='avatar-img'>{msg.senderType === 'parent' ? '👨' : '👦'}</Text>
</View>
</View>
) : (
<View className='message-item peer'>
<View className='peer-avatar'>
<Text className='robot-emoji'>{msg.senderType === 'child' ? '🧒' : character.icon}</Text>
</View>
<View className='message-main'>
<Text className='message-meta'>{formatParticipantLabel(msg)}</Text>
<View className='message-bubble'>
<Text>{msg.content}</Text>
</View>
</View>
</View>
)}
</View>
))
)}
</ScrollView>
{character.canSend && character.childId && (
<View className='composer'>
<Input
className='composer-input'
value={inputText}
placeholder='输入要发给孩子的消息'
maxlength={500}
confirmType='send'
onInput={(event) => setInputText(event.detail.value)}
onConfirm={handleSend}
/>
<View className={`composer-send ${sending ? 'disabled' : ''}`} onClick={handleSend}>
<Text className='composer-send-text'>{sending ? '发送中' : '发送'}</Text>
</View>
</View>
)}
</View>
)
}

View File

@@ -14,15 +14,8 @@
font-weight: 700;
color: #1A1A1A;
display: block;
margin-bottom: 12px;
line-height: 1.2;
}
.page-subtitle {
font-size: 28px;
color: #666666;
line-height: 1.4;
}
}
.conversation-list {
@@ -74,19 +67,49 @@
.conversation-header {
display: flex;
justify-content: space-between;
align-items: center;
align-items: flex-start;
margin-bottom: 12px;
.conversation-name {
font-size: 32px;
font-weight: 600;
color: #1A1A1A;
}
.conversation-time {
font-size: 24px;
color: #999999;
flex-shrink: 0;
margin-left: 16px;
}
}
.conversation-name-wrap {
display: flex;
align-items: center;
flex-wrap: wrap;
min-width: 0;
}
.conversation-name {
font-size: 32px;
font-weight: 600;
color: #1A1A1A;
margin-right: 12px;
}
.conversation-tag {
height: 40px;
padding: 0 14px;
border-radius: 999px;
font-size: 22px;
line-height: 40px;
color: #FFFFFF;
&.child {
background: #5B8FF9;
}
&.parent {
background: #36CFC9;
}
&.ai {
background: #FF8C42;
}
}
@@ -106,6 +129,13 @@
}
}
.conversation-meta {
display: block;
margin-top: 10px;
font-size: 24px;
color: #A0A0A0;
}
.unread-badge {
min-width: 36px;
height: 36px;
@@ -123,3 +153,31 @@
font-weight: 600;
}
}
.loading {
min-height: 50vh;
display: flex;
align-items: center;
justify-content: center;
text {
font-size: 30px;
color: #999999;
}
}
.empty-card {
background: #FFFFFF;
border-radius: 20px;
margin: 0 24px;
padding: 48px 32px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
text-align: center;
}
.empty-title {
display: block;
font-size: 34px;
font-weight: 700;
color: #1A1A1A;
}

View File

@@ -1,63 +1,102 @@
import { View, Text, ScrollView } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { getToken } from '@/services/auth'
import { getConversations, ChatConversation } from '../../services/chat'
import './index.scss'
export default function Chat() {
const [conversations, setConversations] = useState<ChatConversation[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
loadConversations()
}, [])
useDidShow(() => {
void loadConversations()
})
const loadConversations = async () => {
const data = await getConversations()
setConversations(data)
if (!getToken()) {
Taro.reLaunch({ url: '/pages/login/index' })
return
}
setLoading(true)
try {
const data = await getConversations()
setConversations(data)
} catch (error: any) {
console.error('[chat] load failed:', error)
Taro.showToast({
title: error?.message || '加载失败,请稍后重试',
icon: 'none',
})
} finally {
setLoading(false)
}
}
const handleConversationClick = (conversation: ChatConversation) => {
Taro.navigateTo({
url: `/pages/chat/detail/index?id=${conversation.id}&name=${encodeURIComponent(conversation.name)}`
url:
`/pages/chat/detail/index?id=${conversation.id}` +
`&source=${conversation.source}` +
`&name=${encodeURIComponent(conversation.name)}` +
`&peerKind=${conversation.peerKind}` +
`&roleKey=${encodeURIComponent(conversation.roleKey || '')}` +
`&conversationTypeName=${encodeURIComponent(conversation.conversationTypeName || '')}` +
`&peerId=${encodeURIComponent(conversation.peerId || '')}` +
`&childId=${conversation.childId || ''}` +
`&childName=${encodeURIComponent(conversation.childName || '')}` +
`&parentUserId=${conversation.parentUserId || ''}` +
`&deviceId=${encodeURIComponent(conversation.deviceId || '')}` +
`&channelLabel=${encodeURIComponent(conversation.channelLabel || '')}` +
`&canSend=${conversation.canSend ? '1' : '0'}`,
})
}
return (
<View className='chat-page'>
<View className='page-header'>
<Text className='page-title'>AI </Text>
<Text className='page-subtitle'></Text>
<Text className='page-title'></Text>
</View>
<ScrollView className='conversation-list' scrollY>
{conversations.map((conversation) => (
<View
key={conversation.id}
className='conversation-item'
onClick={() => handleConversationClick(conversation)}
>
<View className='conversation-avatar'>
<Text className='avatar-icon'>{conversation.avatar}</Text>
</View>
<View className='conversation-content'>
<View className='conversation-header'>
<Text className='conversation-name'>{conversation.name}</Text>
<Text className='conversation-time'>{conversation.time}</Text>
{loading ? (
<View className='loading'>
<Text>...</Text>
</View>
) : conversations.length === 0 ? (
<View className='empty-card'>
<Text className='empty-title'></Text>
</View>
) : (
<ScrollView className='conversation-list' scrollY>
{conversations.map((conversation) => (
<View
key={conversation.key}
className='conversation-item'
onClick={() => handleConversationClick(conversation)}
>
<View className='conversation-avatar'>
<Text className='avatar-icon'>{conversation.avatar}</Text>
</View>
<View className='conversation-footer'>
<Text className='last-message' numberOfLines={1}>
{conversation.lastMessage}
</Text>
{conversation.unreadCount && conversation.unreadCount > 0 && (
<View className='unread-badge'>
<Text className='unread-count'>{conversation.unreadCount}</Text>
<View className='conversation-content'>
<View className='conversation-header'>
<View className='conversation-name-wrap'>
<Text className='conversation-name'>{conversation.name}</Text>
<Text className={`conversation-tag ${conversation.peerKind}`}>{conversation.typeLabel}</Text>
</View>
)}
<Text className='conversation-time'>{conversation.time}</Text>
</View>
<View className='conversation-footer'>
<Text className='last-message' numberOfLines={1}>
{conversation.lastMessage}
</Text>
</View>
{conversation.childName && <Text className='conversation-meta'>{conversation.childName}</Text>}
</View>
</View>
</View>
))}
</ScrollView>
))}
</ScrollView>
)}
</View>
)
}