Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Sep 3, 2024
Merged
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
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
Loading