修改消息也图标

This commit is contained in:
张成
2025-11-16 20:06:22 +08:00
parent ad971796ba
commit eb10ba0a38
7 changed files with 115 additions and 55 deletions

View File

@@ -25,33 +25,13 @@ export const useKeyboardStore = create<KeyboardStore>((set, get) => ({
isInitialized: false,
setKeyboardHeight: (height: number) => {
// 直接更新状态,不触发监听器(监听器由 initializeKeyboardListener 统一处理)
set({ keyboardHeight: height })
const { listeners } = get()
// 使用 requestAnimationFrame 异步执行监听器,避免阻塞主线程
requestAnimationFrame(() => {
listeners.forEach(listener => {
try {
listener(height, get().isKeyboardVisible)
} catch (error) {
console.error('键盘监听器执行错误:', error)
}
})
})
},
setKeyboardVisible: (visible: boolean) => {
// 直接更新状态,不触发监听器(监听器由 initializeKeyboardListener 统一处理)
set({ isKeyboardVisible: visible })
const { listeners } = get()
// 使用 requestAnimationFrame 异步执行监听器,避免阻塞主线程
requestAnimationFrame(() => {
listeners.forEach(listener => {
try {
listener(get().keyboardHeight, visible)
} catch (error) {
console.error('键盘监听器执行错误:', error)
}
})
})
},
addListener: (listener: (height: number, visible: boolean) => void) => {
@@ -73,11 +53,59 @@ export const useKeyboardStore = create<KeyboardStore>((set, get) => ({
// 使用防抖优化,避免频繁触发
let lastHeight = 0
let lastTime = 0
const debounceDelay = 16 // 约一帧的时间
let pendingUpdate: { height: number; visible: boolean } | null = null
let rafId: number | null = null
const debounceDelay = 50 // 增加到50ms减少更新频率
const applyUpdate = () => {
if (!pendingUpdate) return
const { height, visible } = pendingUpdate
const store = get()
// 批量更新,减少状态更新次数
if (visible) {
set({
isKeyboardVisible: true,
keyboardHeight: height
})
// 异步通知监听器
requestAnimationFrame(() => {
const { listeners } = get()
listeners.forEach(listener => {
try {
listener(height, true)
} catch (error) {
console.error('键盘监听器执行错误:', error)
}
})
})
} else {
set({
isKeyboardVisible: false,
keyboardHeight: 0
})
// 异步通知监听器
requestAnimationFrame(() => {
const { listeners } = get()
listeners.forEach(listener => {
try {
listener(0, false)
} catch (error) {
console.error('键盘监听器执行错误:', error)
}
})
})
}
pendingUpdate = null
rafId = null
}
Taro.onKeyboardHeightChange?.((res: any) => {
const height = Number(res?.height || 0)
const now = Date.now()
const visible = height > 0
// 防抖:如果高度没变化或时间间隔太短,忽略
if (height === lastHeight && (now - lastTime) < debounceDelay) {
@@ -87,18 +115,17 @@ export const useKeyboardStore = create<KeyboardStore>((set, get) => ({
lastHeight = height
lastTime = now
console.log('全局键盘高度变化:', height)
// 保存待更新的状态
pendingUpdate = { height, visible }
// 使用 requestAnimationFrame 延迟执行,避免阻塞消息处理
requestAnimationFrame(() => {
const store = get()
if (height > 0) {
store.setKeyboardVisible(true)
store.setKeyboardHeight(height)
} else {
store.setKeyboardVisible(false)
store.setKeyboardHeight(0)
}
// 取消之前的更新
if (rafId !== null) {
cancelAnimationFrame(rafId)
}
// 延迟执行更新,避免阻塞消息处理
rafId = requestAnimationFrame(() => {
requestAnimationFrame(applyUpdate)
})
})