feat(useRafLoop): implement #1090

This commit is contained in:
xobotyi 2020-04-01 08:49:05 +03:00
parent 1653a6d9e4
commit 1ef1272d6d
No known key found for this signature in database
GPG Key ID: 53F9989A26474798
3 changed files with 19 additions and 4 deletions

View File

@ -31,5 +31,5 @@ const Demo = () => {
```ts
const [stopLoop, isActive, startLoop] = useRafLoop(callback: CallableFunction, deps?: DependencyList);
```
* `callback` — function to call each RAF tick
* `callback(time: number)` — function to call each RAF tick

View File

@ -1,4 +1,3 @@
/* eslint-disable */
import { useEffect, useRef, useState } from 'react';
export type RafLoopReturns = [() => void, boolean, () => void];
@ -7,8 +6,8 @@ export default function useRafLoop(callback: CallableFunction): RafLoopReturns {
const raf = useRef<number | null>(null);
const [isActive, setIsActive] = useState<boolean>(true);
function loopStep() {
callback();
function loopStep(time: number) {
callback(time);
raf.current = requestAnimationFrame(loopStep);
}

View File

@ -99,4 +99,20 @@ describe('useRafLoop', () => {
expect(spy).not.toBeCalled();
});
it('should pass timestamp as 1st argument of callback', () => {
const spy = jest.fn();
const hook = renderHook(() => useRafLoop(spy), { initialProps: false });
requestAnimationFrame.step();
act(() => {
hook.result.current[0]();
});
requestAnimationFrame.step();
expect(spy).toHaveBeenCalled();
expect(typeof spy.mock.calls[0][0]).toBe('number');
});
});