Skip to content

Commit

Permalink
Prevent window scrolling on mouse wheel scroll when numeric input fie…
Browse files Browse the repository at this point in the history
…ld is focused and hovered. (#5199)
  • Loading branch information
WithoutPants authored Sep 3, 2024
1 parent c21ded0 commit 306ba63
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion ui/v2.5/src/utils/form.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -98,7 +136,7 @@ export function formikUtils<V extends FormikValues>(
);
} else {
control = (
<Form.Control
<InputField
type={type}
className="text-input"
placeholder={placeholder}
Expand Down

0 comments on commit 306ba63

Please sign in to comment.