Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "minor",
"comment": "feat: create a new useAnimationFrame hook",
"packageName": "@fluentui/react-utilities",
"email": "marcosvmmoura@gmail.com",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,9 @@ export type UnknownSlotProps = Pick<React_2.HTMLAttributes<HTMLElement>, 'childr
as?: keyof JSX.IntrinsicElements;
};

// @internal
export function useAnimationFrame(): readonly [(fn: () => void, delay?: number | undefined) => number, () => void];

// @internal
export const useControllableState: <State>(options: UseControllableStateOptions<State>) => [State, React_2.Dispatch<React_2.SetStateAction<State>>];

Expand Down Expand Up @@ -350,7 +353,7 @@ export function useScrollbarWidth(options: UseScrollbarWidthOptions): number | u
export function useSelection(params: SelectionHookParams): readonly [Set<SelectionItemId>, SelectionMethods];

// @internal
export function useTimeout(): readonly [(fn: () => void, delay: number) => void, () => void];
export function useTimeout(): readonly [(fn: () => void, delay?: number | undefined) => number, () => void];

// (No @packageDocumentation comment for this package)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './useAnimationFrame';
export * from './useControllableState';
export * from './useEventCallback';
export * from './useFirstMount';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { renderHook } from '@testing-library/react-hooks';
import { useAnimationFrame } from './useAnimationFrame';

describe('useAnimationFrame', () => {
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());

it('calls the callback only on the next frame', () => {
const [setTestRequestAnimationFrame] = renderHook(() => useAnimationFrame()).result.current;
const callback = jest.fn();

setTestRequestAnimationFrame(callback);

expect(callback).not.toHaveBeenCalled();

jest.runAllTimers();

expect(callback).toHaveBeenCalledTimes(1);
});

it('does not call the callback if cancel is called', () => {
const [setTestRequestAnimationFrame, cancelTEstRequestAnimationFrame] = renderHook(() => useAnimationFrame()).result
.current;
const callback = jest.fn();

setTestRequestAnimationFrame(callback);
cancelTEstRequestAnimationFrame();

jest.runAllTimers();

expect(callback).not.toHaveBeenCalled();
});

it('cancel the previous requestAnimationFrame if set is called again', () => {
const [setTestRequestAnimationFrame] = renderHook(() => useAnimationFrame()).result.current;
const callbackA = jest.fn();
const callbackB = jest.fn();

setTestRequestAnimationFrame(callbackA);
setTestRequestAnimationFrame(callbackB);

jest.runAllTimers();

expect(callbackA).not.toHaveBeenCalledTimes(1);
expect(callbackB).toHaveBeenCalledTimes(1);
});

it('allows another requestAnimationFrame to be set after the previous has run', () => {
const [setTestRequestAnimationFrame] = renderHook(() => useAnimationFrame()).result.current;
const callbackA = jest.fn();
const callbackB = jest.fn();

setTestRequestAnimationFrame(callbackA);

jest.runAllTimers();

setTestRequestAnimationFrame(callbackB);

jest.runAllTimers();

expect(callbackA).toHaveBeenCalledTimes(1);
expect(callbackB).toHaveBeenCalledTimes(1);
});

it('does not cancel the requestAnimationFrame between renders', () => {
const { result, rerender } = renderHook(() => useAnimationFrame());
const [setTestRequestAnimationFrame] = result.current;
const callback = jest.fn();

setTestRequestAnimationFrame(callback);

rerender();

jest.runAllTimers();

expect(callback).toHaveBeenCalledTimes(1);
});

it('cancel the requestAnimationFrame when the component is unmounted', () => {
const { result, unmount } = renderHook(() => useAnimationFrame());
const [setTestRequestAnimationFrame] = result.current;
const callback = jest.fn();

setTestRequestAnimationFrame(callback);

unmount();

jest.runAllTimers();

expect(callback).not.toHaveBeenCalled();
});

it('returns the same functions every render', () => {
const { result, rerender } = renderHook(() => useAnimationFrame());
const [setTestRequestAnimationFrame, cancelTEstRequestAnimationFrame] = result.current;

rerender();

expect(result.current).toStrictEqual([setTestRequestAnimationFrame, cancelTEstRequestAnimationFrame]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useBrowserTimer } from './useBrowserTimer';

/**
* @internal
* Helper to manage a browser requestAnimationFrame.
* Ensures that the requestAnimationFrame isn't set multiple times at once and is cleaned up
* when the component is unloaded.
*
* @returns A pair of [requestAnimationFrame, cancelAnimationFrame] that are stable between renders.
*/
export function useAnimationFrame() {
// TODO: figure it out a way to not call global.requestAnimationFrame and instead infer window from some context
return useBrowserTimer(requestAnimationFrame, cancelAnimationFrame);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { renderHook } from '@testing-library/react-hooks';
import { useBrowserTimer } from './useBrowserTimer';

const setTimer = jest.fn((callback: jest.Func) => {
callback();
return 0;
});

const cancelTimer = jest.fn(() => {
return;
});

describe('useBrowserTimer', () => {
it('should return array with functions', () => {
const hookValues = renderHook(() => useBrowserTimer(setTimer, cancelTimer)).result.current;

expect(hookValues).toHaveLength(2);
expect(typeof hookValues[0]).toBe('function');
expect(typeof hookValues[1]).toBe('function');
});

it('calls the setter only n times', () => {
const [setTestTimer] = renderHook(() => useBrowserTimer(setTimer, cancelTimer)).result.current;
const callback = jest.fn();

setTestTimer(callback);

expect(callback).toHaveBeenCalledTimes(1);
expect(callback).not.toHaveBeenCalledTimes(2);
expect(setTimer).toHaveBeenCalledTimes(1);
expect(setTimer).not.toHaveBeenCalledTimes(2);
});

it('setter should return timer id', () => {
const [setTestTimer] = renderHook(() => useBrowserTimer(setTimer, cancelTimer)).result.current;
const callback = jest.fn();

const timerId = setTestTimer(callback);

expect(callback).toHaveBeenCalledTimes(1);
expect(timerId).toBe(0);
});

it('should not call the cancel callback if no setter was called', () => {
const [, cancelTestTimer] = renderHook(() => useBrowserTimer(setTimer, cancelTimer)).result.current;

cancelTestTimer();

expect(cancelTimer).not.toHaveBeenCalledTimes(1);
});

it('calls the cancel only n times', () => {
const [setTestTimer, cancelTestTimer] = renderHook(() => useBrowserTimer(setTimer, cancelTimer)).result.current;

setTestTimer(jest.fn());
cancelTestTimer();

expect(cancelTimer).toHaveBeenCalledTimes(1);
expect(cancelTimer).not.toHaveBeenCalledTimes(2);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import * as React from 'react';

type BrowserTimerSetter =
| ((fn: () => void, duration?: number, ...args: Record<string, unknown>[]) => number)
| ((fn: () => void) => number);

/**
* @internal
* Helper to manage a browser timer.
* Ensures that the timer isn't set multiple times at once,
* and is cleaned up when the component is unloaded.
*
* @param setTimer - The timer setter function
* @param cancelTimer - The timer cancel function
* @returns A pair of [setTimer, cancelTimer] that are stable between renders.
*
* @example
* const [setTimer, cancelTimer] = useBrowserTimer(setTimeout, cancelTimeout);
*
* setTimer(() => console.log('Hello world!'), 1000);
* cancelTimer();
*/
export function useBrowserTimer(setTimer: BrowserTimerSetter, cancelTimer: (id: number) => void) {
const id = React.useRef<number | undefined>(undefined);

const set = React.useCallback(
(fn: () => void, delay?: number) => {
if (id.current !== undefined) {
cancelTimer(id.current);
}

id.current = setTimer(fn, delay);
return id.current;
},
[cancelTimer, setTimer],
);

const cancel = React.useCallback(() => {
if (id.current !== undefined) {
cancelTimer(id.current);
id.current = undefined;
}
}, [cancelTimer]);

// Clean up the timeout when the component is unloaded
React.useEffect(() => cancel, [cancel]);

return [set, cancel] as const;
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,14 @@
import * as React from 'react';
import { useBrowserTimer } from './useBrowserTimer';

/**
* @internal
* Helper to manage a browser timeout.
* Ensures that the timeout isn't set multiple times at once,
* and is cleaned up when the component is unloaded.
* Ensures that the timeout isn't set multiple times at once and is cleaned up
* when the component is unloaded.
*
* @returns A pair of [setTimeout, clearTimeout] that are stable between renders.
*/
export function useTimeout() {
const [timeout] = React.useState(() => ({
id: undefined as ReturnType<typeof setTimeout> | undefined,
set: (fn: () => void, delay: number) => {
timeout.clear();
timeout.id = setTimeout(fn, delay);
},
clear: () => {
if (timeout.id !== undefined) {
clearTimeout(timeout.id);
timeout.id = undefined;
}
},
}));

// Clean up the timeout when the component is unloaded
React.useEffect(() => timeout.clear, [timeout]);

return [timeout.set, timeout.clear] as const;
// TODO: figure it out a way to not call global.setTimeout and instead infer window from some context
return useBrowserTimer(setTimeout, clearTimeout);
}
1 change: 1 addition & 0 deletions packages/react-components/react-utilities/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export type {
export {
IdPrefixProvider,
resetIdsForTests,
useAnimationFrame,
useControllableState,
useEventCallback,
useFirstMount,
Expand Down