Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/keyboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
},
"peerDependencies": {
"@capacitor/core": ">=3.0.0",
"@capacitor/device": ">=3.0.0",
"@capacitor/keyboard": "*",
"react": "*"
},
Expand Down
49 changes: 36 additions & 13 deletions packages/keyboard/src/useKeyboard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { Keyboard, KeyboardInfo, KeyboardPlugin } from '@capacitor/keyboard';
import { AvailableResult } from './util/models';
import { Capacitor } from '@capacitor/core';
import { Capacitor, PluginListenerHandle } from '@capacitor/core';
import { Device } from '@capacitor/device';
interface KeyboardResult extends AvailableResult {
isOpen: boolean;
keyboardHeight: number;
Expand All @@ -15,24 +16,46 @@ if (!Capacitor.isPluginAvailable('Keyboard')) {
export function useKeyboard(): KeyboardResult {
const [isOpen, setIsOpen] = useState(false);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const [platform, setPlatform] = useState('web');

const showCallback = useCallback((ki: KeyboardInfo) => {
const keyboardHeight = ki.keyboardHeight;
setIsOpen(true);
setKeyboardHeight(keyboardHeight);
}, []);

const hideCallback = useCallback(() => {
setIsOpen(false);
setKeyboardHeight(0);
}, []);

useEffect(() => {
const showCallback = (ki: KeyboardInfo) => {
const keyboardHeight = ki.keyboardHeight;
setIsOpen(true);
setKeyboardHeight(keyboardHeight);
const checkIsNativePlatform = async () => {
const deviceInfo = await Device.getInfo();
setPlatform(deviceInfo.platform);
};
const hideCallback = () => {
setIsOpen(false);
setKeyboardHeight(0);
checkIsNativePlatform();
}, []);

useEffect(() => {
let showListener: PluginListenerHandle, hideListener: PluginListenerHandle;

const getKeyboardListener = async () => {
showListener = await Keyboard.addListener('keyboardDidShow', showCallback);
hideListener = await Keyboard.addListener('keyboardDidHide', hideCallback);
};
Keyboard.addListener('keyboardDidShow', showCallback);
Keyboard.addListener('keyboardDidHide', hideCallback);

if (platform !== 'web') {
getKeyboardListener();
}

return () => {
Keyboard.removeAllListeners();
if (platform !== 'web' && showListener && hideListener) {
showListener.remove();
hideListener.remove();
}
};
}, [setIsOpen, setKeyboardHeight]);
}, [setIsOpen, setKeyboardHeight, platform]);

return {
isOpen,
Expand Down