Files
PetCommunity/miniprogram/pages/search/search.ts
2026-06-05 17:46:51 +08:00

74 lines
2.0 KiB
TypeScript

import { getAvatarGradient } from '../../utils/format'
Page({
data: {
statusBarHeight: 0,
keyword: '',
resultTab: 'posts' as 'posts' | 'users',
postResults: [] as any[],
userResults: [] as any[],
hotTopics: [] as any[],
loading: false,
},
onLoad() {
const info = wx.getSystemInfoSync()
this.setData({ statusBarHeight: info.statusBarHeight })
this.loadHotTopics()
},
async loadHotTopics() {
try {
const res = await wx.cloud.callFunction({ name: 'getHotTopics', data: {} }) as any
this.setData({ hotTopics: res.result?.data || [] })
} catch {}
},
onInput(e: WechatMiniprogram.CustomEvent) {
this.setData({ keyword: e.detail.value })
},
onClear() {
this.setData({ keyword: '', postResults: [], userResults: [] })
},
async onSearch() {
const kw = this.data.keyword.trim()
if (!kw) return
this.setData({ loading: true })
try {
const [posts, users] = await Promise.all([
wx.cloud.callFunction({ name: 'searchPosts', data: { keyword: kw } }) as any,
wx.cloud.callFunction({ name: 'searchUsers', data: { keyword: kw } }) as any,
])
this.setData({
postResults: posts.result?.data || [],
userResults: (users.result?.data || []).map((u: any) => ({
...u,
gradient: getAvatarGradient(u._id),
})),
})
} catch {
wx.showToast({ title: '搜索失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
onTopicTap(e: WechatMiniprogram.CustomEvent) {
const tag = e.currentTarget.dataset.tag as string
this.setData({ keyword: tag })
this.onSearch()
},
onResultTab(e: WechatMiniprogram.CustomEvent) {
this.setData({ resultTab: e.currentTarget.dataset.t as 'posts' | 'users' })
},
onUserTap(e: WechatMiniprogram.CustomEvent) {
wx.navigateTo({ url: `/pages/pet-detail/pet-detail?userId=${e.currentTarget.dataset.uid}` })
},
onBack() { wx.navigateBack() },
})