Prevent window scrolling on mouse wheel scroll when numeric input field is focused and hovered. (#5199)

This commit is contained in:
WithoutPants 2024-09-03 16:33:49 +10:00 committed by GitHub
parent c21ded028a
commit 306ba63ab6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,10 +1,12 @@
import { faTrashAlt } from "@fortawesome/free-solid-svg-icons";
import { FormikValues, useFormik } from "formik";
import React, { InputHTMLAttributes, useEffect, useRef } from "react";
import {
Button,
Col,
ColProps,
Form,
FormControlProps,
FormLabelProps,
Row,
} from "react-bootstrap";
@ -41,6 +43,42 @@ export function renderLabel(options: {
);
}
// useStopWheelScroll is a hook to provide a workaround for a bug in React/Chrome.
// If a number field is focused and the mouse pointer is over the field, then scrolling
// the mouse wheel will change the field value _and_ scroll the window.
// This hook prevents the propagation that causes the window to scroll.
export function useStopWheelScroll(ref: React.RefObject<HTMLElement>) {
useEffect(() => {
const { current } = ref;
function stopWheelScroll(e: WheelEvent) {
if (current) {
e.stopPropagation();
}
}
if (current) {
current.addEventListener("wheel", stopWheelScroll);
}
return () => {
if (current) {
current.removeEventListener("wheel", stopWheelScroll);
}
};
}, [ref]);
}
const InputField: React.FC<
InputHTMLAttributes<HTMLInputElement> & FormControlProps
> = (props) => {
const inputRef = useRef<HTMLInputElement>(null);
useStopWheelScroll(inputRef);
return <Form.Control {...props} ref={inputRef} />;
};
type Formik<V extends FormikValues> = ReturnType<typeof useFormik<V>>;
interface IProps {
@ -98,7 +136,7 @@ export function formikUtils<V extends FormikValues>(
);
} else {
control = (
<Form.Control
<InputField
type={type}
className="text-input"
placeholder={placeholder}