统一聊天排序并支持公众号跳转小程序

This commit is contained in:
stu2not
2026-06-24 14:59:44 +08:00
parent 31804a78ff
commit e75a9015fa
16 changed files with 668 additions and 72 deletions

View File

@@ -3,6 +3,7 @@ export default defineAppConfig({
"pages/login/index",
"pages/bind/index",
"pages/device/index",
"pages/notification/index",
"pages/chat/index",
"pages/chat/detail/index",
"pages/location/index",

View File

@@ -109,6 +109,7 @@ const RECORD_LONG_PRESS_DELAY_MS = 350
type LoadChatOptions = {
showLoading?: boolean
scrollToBottom?: 'jump' | 'animate' | false
}
function compareVersion(left: string, right: string): number {
@@ -232,6 +233,7 @@ export default function ChatDetail() {
const [playingMessageId, setPlayingMessageId] = useState<number | null>(null)
const [recordHint, setRecordHint] = useState('长按开始留言')
const [scrollTarget, setScrollTarget] = useState('')
const [scrollWithAnimation, setScrollWithAnimation] = useState(false)
const audioContextRef = useRef<Taro.InnerAudioContext | null>(null)
const recorderManagerRef = useRef<Taro.RecorderManager | null>(null)
const activeConversationIdRef = useRef(initialConversationId)
@@ -251,12 +253,14 @@ export default function ChatDetail() {
const recordStartPendingRef = useRef(false)
const recordingActiveRef = useRef(false)
const scrollToBottom = () => {
const scrollToBottom = (animated: boolean) => {
if (scrollTimerRef.current) {
clearTimeout(scrollTimerRef.current)
}
setScrollWithAnimation(animated)
setScrollTarget('')
scrollTimerRef.current = setTimeout(() => {
setScrollWithAnimation(animated)
setScrollTarget(CHAT_BOTTOM_ANCHOR_ID)
scrollTimerRef.current = null
}, 80)
@@ -373,8 +377,9 @@ export default function ChatDetail() {
}
const msgs = await getMessages(conversationId, conversationSource, decodedConversationTypeName)
setMessages(msgs)
if (msgs.length > 0) {
scrollToBottom()
const scrollMode = options.scrollToBottom ?? (!hasLoadedChatRef.current ? 'jump' : false)
if (msgs.length > 0 && scrollMode) {
scrollToBottom(scrollMode === 'animate')
}
hasLoadedChatRef.current = true
} catch (error: any) {
@@ -480,9 +485,15 @@ export default function ChatDetail() {
if (response.conversation_id && response.conversation_id !== activeConversationIdRef.current) {
skipNextAutoLoadRef.current = true
setActiveConversationId(response.conversation_id)
await latestLoadChatDataRef.current(response.conversation_id, { showLoading: false })
await latestLoadChatDataRef.current(response.conversation_id, {
showLoading: false,
scrollToBottom: 'animate',
})
} else {
await latestLoadChatDataRef.current(activeConversationIdRef.current, { showLoading: false })
await latestLoadChatDataRef.current(activeConversationIdRef.current, {
showLoading: false,
scrollToBottom: 'animate',
})
}
Taro.showToast({ title: '留言已发送', icon: 'success' })
} catch (error: any) {
@@ -752,7 +763,12 @@ export default function ChatDetail() {
</View>
</View>
<ScrollView className='chat-list' scrollY scrollWithAnimation scrollIntoView={scrollTarget}>
<ScrollView
className='chat-list'
scrollY
scrollWithAnimation={scrollWithAnimation}
scrollIntoView={scrollTarget}
>
{loading ? (
<View className='empty-chat'>
<Text className='empty-chat-text'>...</Text>

View File

@@ -0,0 +1,37 @@
.notification-page {
min-height: 100vh;
background: #f5f7fa;
display: flex;
align-items: center;
justify-content: center;
padding: 48px;
box-sizing: border-box;
}
.notification-panel {
width: 100%;
max-width: 520px;
background: #ffffff;
border-radius: 8px;
padding: 40px 32px;
box-sizing: border-box;
box-shadow: 0 10px 24px rgba(31, 41, 55, 0.08);
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
}
.notification-title {
color: #1f2937;
font-size: 34px;
font-weight: 700;
line-height: 1.3;
}
.notification-message {
color: #6b7280;
font-size: 28px;
line-height: 1.5;
text-align: center;
}

View File

@@ -0,0 +1,59 @@
import { View, Text } from '@tarojs/components'
import { useEffect, useState } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { getToken } from '@/services/auth'
import { resolveWechatMpNotificationLink } from '@/services/notification'
import './index.scss'
function buildQuery(params: Record<string, string | number | null | undefined>): string {
return Object.entries(params)
.filter(([, value]) => value !== undefined && value !== null && String(value) !== '')
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
.join('&')
}
function buildCurrentPageUrl(token: string): string {
return `/pages/notification/index?token=${encodeURIComponent(token)}`
}
export default function NotificationEntry() {
const router = useRouter()
const token = String(router.params.token || '').trim()
const [message, setMessage] = useState('正在打开留言...')
useEffect(() => {
const openNotification = async () => {
if (!token) {
setMessage('通知链接无效')
return
}
if (!getToken()) {
Taro.setStorageSync('postLoginRedirect', buildCurrentPageUrl(token))
Taro.reLaunch({ url: '/pages/login/index' })
return
}
try {
const result = await resolveWechatMpNotificationLink(token)
const query = buildQuery(result.params || {})
const route = result.route.startsWith('/') ? result.route : `/${result.route}`
Taro.redirectTo({ url: query ? `${route}?${query}` : route })
} catch (error: any) {
console.error('[notification] resolve failed:', error)
setMessage(error?.message || '通知链接已失效')
}
}
void openNotification()
}, [token])
return (
<View className='notification-page'>
<View className='notification-panel'>
<Text className='notification-title'></Text>
<Text className='notification-message'>{message}</Text>
</View>
</View>
)
}

View File

@@ -122,6 +122,8 @@ interface ChildConversationItem {
last_message_preview?: string | null
last_message_at?: string | null
message_count: number
created_at: string
updated_at: string
}
interface ChildConversationListResponse {
@@ -307,9 +309,10 @@ function canSendParentConversation(parentUserId: number | null, context: Binding
return Boolean(parentUserId && parentUserId === context.currentUserId)
}
function getConversationRank(conversation: ChatConversation): number {
if (isParentChildConversation(conversation.conversationTypeName)) return 0
return 1
function compareConversationsByNewest(left: ChatConversation, right: ChatConversation): number {
const timeDiff = parseTime(right.sortAt) - parseTime(left.sortAt)
if (timeDiff !== 0) return timeDiff
return right.key.localeCompare(left.key)
}
async function getBindingContext(): Promise<BindingContext> {
@@ -385,6 +388,7 @@ function toImConversation(item: ChildConversationItem, context: BindingContext):
const parentUserId = isParentConversation ? parseNumericId(item.peer_id) : null
const canSend = isParentConversation ? canSendParentConversation(parentUserId, context) : false
const parentConversationName = getParentConversationName(parentUserId, item.peer_id, item.peer_name, context)
const sortAt = item.last_message_at || item.updated_at || item.created_at
return {
id: item.conversation_id,
@@ -400,8 +404,8 @@ function toImConversation(item: ChildConversationItem, context: BindingContext):
: '其他家长和孩子的留言记录'
: meta.description,
lastMessage: item.last_message_preview || (isParentConversation ? (canSend ? '还没有消息,点进去发送第一条' : '暂无留言记录') : '暂无消息'),
time: formatListTime(item.last_message_at),
sortAt: item.last_message_at || '',
time: formatListTime(sortAt),
sortAt,
conversationTypeName: item.conversation_type_name,
peerId: item.peer_id,
childId: context.childId,
@@ -496,11 +500,7 @@ export async function getConversations(): Promise<ChatConversation[]> {
}
}
return conversations.sort((left, right) => {
const rankDiff = getConversationRank(left) - getConversationRank(right)
if (rankDiff !== 0) return rankDiff
return parseTime(right.sortAt) - parseTime(left.sortAt)
})
return conversations.sort(compareConversationsByNewest)
}
export async function getMessages(

View File

@@ -0,0 +1,10 @@
import { request } from './api'
export interface WechatMpNotificationLink {
route: string
params: Record<string, string | number | null | undefined>
}
export function resolveWechatMpNotificationLink(token: string): Promise<WechatMpNotificationLink> {
return request<WechatMpNotificationLink>(`/banban/wechat-mp/notification-links/${encodeURIComponent(token)}`)
}