allow typing phone number with desktop keyboard

This commit is contained in:
m5r 2021-09-01 06:42:39 +08:00
parent b4f06e5471
commit 98485bd034
2 changed files with 30 additions and 1 deletions

View File

@ -0,0 +1,17 @@
import { useCallback, useEffect } from "react";
export default function useKeyPress(onKeyPress: (key: string) => void) {
const onKeyDown = useCallback(
({ key }: KeyboardEvent) => {
onKeyPress(key);
},
[onKeyPress],
);
useEffect(() => {
window.addEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
};
}, [onKeyDown]);
}

View File

@ -1,6 +1,6 @@
import { Fragment, useRef } from "react";
import type { BlitzPage } from "blitz";
import { Link, Routes, useRouter } from "blitz";
import { Routes, useRouter } from "blitz";
import { atom, useAtom } from "jotai";
import { usePress } from "@react-aria/interactions";
import { Transition } from "@headlessui/react";
@ -12,6 +12,7 @@ import Layout from "../../core/layouts/layout";
import Keypad from "../components/keypad";
import useRequireOnboarding from "../../core/hooks/use-require-onboarding";
import usePhoneCalls from "../hooks/use-phone-calls";
import useKeyPress from "../hooks/use-key-press";
const KeypadPage: BlitzPage = () => {
useRequireOnboarding();
@ -22,6 +23,13 @@ const KeypadPage: BlitzPage = () => {
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const pressDigit = useAtom(pressDigitAtom)[1];
useKeyPress((key) => {
if (key === "Backspace") {
return removeDigit();
}
pressDigit(key);
});
const longPressDigit = useAtom(longPressDigitAtom)[1];
const onZeroPressProps = {
onPressStart() {
@ -119,6 +127,10 @@ const pressDigitAtom = atom(null, (get, set, digit: string) => {
return;
}
if ("0123456789+#*".indexOf(digit) === -1) {
return;
}
set(phoneNumberAtom, (prevState) => prevState + digit);
});
const longPressDigitAtom = atom(null, (get, set, replaceWith: string) => {