Skip to content

Commit

Permalink
Use useTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
mj12albert committed Mar 13, 2024
1 parent ec6d6de commit 8e1eae6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
17 changes: 9 additions & 8 deletions packages/mui-base/src/unstable_useNumberInput/useNumberInput.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
'use client';
import * as React from 'react';
import MuiError from '@mui/internal-babel-macros/MuiError.macro';
import { unstable_useForkRef as useForkRef, unstable_useId as useId } from '@mui/utils';
import {
unstable_useForkRef as useForkRef,
unstable_useId as useId,
unstable_useTimeout as useTimeout,
} from '@mui/utils';
import { extractEventHandlers } from '../utils/extractEventHandlers';
import { MuiCancellableEvent } from '../utils/MuiCancellableEvent';
import { useControllableReducer } from '../utils/useControllableReducer';
Expand Down Expand Up @@ -82,8 +86,7 @@ export function useNumberInput(parameters: UseNumberInputParameters): UseNumberI
}
}, []);

const timeoutRef = React.useRef<number>();
const clearTimeoutRef = () => window.clearTimeout(timeoutRef.current);
const holdTimer = useTimeout();

const inputRef = React.useRef<HTMLInputElement>(null);
const handleInputRef = useForkRef(inputRef, inputRefProp, handleInputRefWarning);
Expand Down Expand Up @@ -407,18 +410,16 @@ export function useNumberInput(parameters: UseNumberInputParameters): UseNumberI
actionType: typeof NumberInputActionTypes.increment | typeof NumberInputActionTypes.decrement;
event: React.PointerEvent;
}) => {
clearTimeoutRef();

const { actionType, event } = payload;

timeoutRef.current = window.setTimeout(() => {
holdTimer.start(100, () => {
dispatch({
type: actionType,
event,
applyMultiplier: !!event.shiftKey,
});
recurse({ actionType, event });
}, 100);
});
};

const handleStepperButtonMouseDown =
Expand All @@ -438,7 +439,7 @@ export function useNumberInput(parameters: UseNumberInputParameters): UseNumberI
};

const handleStepperButtonMouseUp = () => {
clearTimeoutRef();
holdTimer.clear();
};

const stepperButtonCommonProps = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@ describe('useNumberInput2', () => {

const incrementBtn = screen.getByTestId('incrementBtn');

fireEvent.mouseDown(incrementBtn);
fireEvent.mouseDown(incrementBtn); // onChange x1

clock.tick(100);
clock.tick(100);
clock.tick(100); // onChange x2
clock.tick(100); // onChange x3
clock.tick(100); // onChange x4
clock.runToLast();

expect(handleChange.callCount).to.equal(3);
expect(handleChange.callCount).to.equal(4);
});
});
});

0 comments on commit 8e1eae6

Please sign in to comment.