forked from NervJS/taro
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkeyboard.ts
60 lines (53 loc) · 1.8 KB
/
keyboard.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Keyboard } from 'react-native'
import { createCallbackManager, errorHandler, successHandler } from '../utils'
const hideKeyboard = (opts: Taro.hideKeyboard.Option = {}): Promise<TaroGeneral.CallbackResult> => {
const { success, fail, complete } = opts
try {
Keyboard.dismiss()
const res = { errMsg: 'hideKeyboard:ok' }
return successHandler(success, complete)(res)
} catch (err) {
const res = { errMsg: err.message }
return errorHandler(fail, complete)(res)
}
}
const _cbManager = createCallbackManager()
let _hasListener = false
const keyboardHeightListener = (height: number) => {
_cbManager.trigger({ height })
}
/**
* 监听键盘高度变化
* @param {(height: number) => void} callback 键盘高度变化事件的回调函数
*/
const onKeyboardHeightChange = (callback: Taro.onKeyboardHeightChange.Callback): void => {
_cbManager.add(callback)
if (!_hasListener) {
Keyboard.addListener('keyboardDidShow', (e) => {
keyboardHeightListener(e.endCoordinates.height)
})
Keyboard.addListener('keyboardDidHide', () => {
keyboardHeightListener(0)
})
_hasListener = true
}
}
/**
* 取消监听键盘高度变化事件
* @param {(height: number) => void} callback 键盘高度变化事件的回调函数
*/
const offKeyboardHeightChange = (callback?: Taro.onKeyboardHeightChange.Callback): void => {
if (callback && typeof callback === 'function') {
_cbManager.remove(callback)
} else if (callback === undefined) {
_cbManager.clear()
} else {
console.warn('offKeyboardHeightChange failed')
}
if (_cbManager.count() === 0) {
Keyboard.removeAllListeners('keyboardDidShow')
Keyboard.removeAllListeners('keyboardDidHide')
_hasListener = false
}
}
export { hideKeyboard, offKeyboardHeightChange, onKeyboardHeightChange }