Skip to content

Commit

Permalink
feat: add useTimer
Browse files Browse the repository at this point in the history
  • Loading branch information
jacksyk committed Oct 27, 2024
1 parent 929f75f commit c118ddb
Show file tree
Hide file tree
Showing 9 changed files with 433 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import useVirtualList from './useVirtualList';
import useWebSocket from './useWebSocket';
import useWhyDidYouUpdate from './useWhyDidYouUpdate';
import useMutationObserver from './useMutationObserver';
import useTimer from './useTimer';

export {
useRequest,
Expand Down Expand Up @@ -156,4 +157,5 @@ export {
useRafTimeout,
useResetState,
useMutationObserver,
useTimer,
};
69 changes: 69 additions & 0 deletions packages/hooks/src/useTimer/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { act, renderHook } from '@testing-library/react';
import useTimer from '../index';

describe('useTimer', () => {
let callback;

beforeAll(() => {
jest.useFakeTimers();
});

beforeEach(() => {
callback = jest.fn();
});

afterEach(() => {
callback.mockRestore();
jest.clearAllTimers();
});

afterAll(() => {
jest.useRealTimers();
});

it('test countdown', async () => {
const hook = renderHook(() =>
useTimer<number>(3, {
onComplete: callback,
auto: false,
}),
);

jest.advanceTimersByTime(2999);
expect(callback).not.toHaveBeenCalled();

jest.advanceTimersByTime(10);
expect(callback).not.toHaveBeenCalled();

act(() => {
hook.result.current.start();
});
act(() => {
Promise.resolve(jest.advanceTimersByTime(3000));
});
expect(callback).toHaveBeenCalled();
expect(Number(hook.result.current.remainingTime)).toBeFalsy();
expect(Number(hook.result.current.seconds)).toBeFalsy();
expect(Number(hook.result.current.minutes)).toBeFalsy();
expect(Number(hook.result.current.hours)).toBeFalsy();
expect(Number(hook.result.current.days)).toBeFalsy();
});

it('test from pass', () => {
const hook = renderHook(() => useTimer<number>(new Date('1999, 4, 4')));
expect(hook.result.current.remainingTime).toBeTruthy();
expect(hook.result.current.seconds).toBeDefined();
expect(hook.result.current.minutes).toBeDefined();
expect(hook.result.current.hours).toBeDefined();
expect(hook.result.current.days).toBeDefined();
});

it('test from future', () => {
const hook = renderHook(() => useTimer<number>(new Date('2028-07-14')));
expect(hook.result.current.remainingTime).toBeTruthy();
expect(hook.result.current.seconds).toBeDefined();
expect(hook.result.current.minutes).toBeDefined();
expect(hook.result.current.hours).toBeDefined();
expect(hook.result.current.days).toBeDefined();
});
});
35 changes: 35 additions & 0 deletions packages/hooks/src/useTimer/demo/demo1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from 'react';
import useTimer from '..';

export default () => {
const { seconds, minutes, hours, days, start, pause, reset, isPaused } = useTimer<number>(
1000 * 3,
{
onComplete: () => {
console.info('计时完成');
},
auto: false,
},
);

return (
<>
{isPaused && <span>暂停中</span>}
<div>
{days ? <span>{days}</span> : null}
<span style={{ fontSize: 20 }}>
{hours}:{minutes}:{seconds}
</span>
</div>
<button style={{ marginRight: 10 }} onClick={() => start()}>
开始/恢复
</button>
<button style={{ marginRight: 10 }} onClick={() => pause()}>
暂停
</button>
<button style={{ marginRight: 10 }} onClick={() => reset()}>
复位
</button>
</>
);
};
12 changes: 12 additions & 0 deletions packages/hooks/src/useTimer/demo/demo2.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React, { useRef } from 'react';
import useTimer from '..';

export default () => {
const time = useRef(new Date(1999, 4, 4));
const { seconds, minutes, hours, days } = useTimer<Date>(time.current);
return (
<div>
阿里巴巴至今已经{days}{hours}:{minutes}:{seconds}
</div>
);
};
15 changes: 15 additions & 0 deletions packages/hooks/src/useTimer/demo/demo3.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React, { useRef } from 'react';
import useTimer from '..';

export default () => {
const time = useRef(new Date('2028-07-14'));
const { seconds, minutes, hours, days } = useTimer<Date>(time.current, {
onComplete: () => console.log('计时结束'),
isCountDown: true,
});
return (
<div>
距离2028年洛杉矶奥运会还有{days}{hours}:{minutes}:{seconds}
</div>
);
};
64 changes: 64 additions & 0 deletions packages/hooks/src/useTimer/index.en-US.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
title: useTimer
nav: Hooks
group:
title: Scene
order: 5
order: 2
toc: content
demo:
cols: 1
---

# useTimer

Some methods for time management, such as countdown and timer. Consolidate operations related to time into a single hook. For example, the countdown function can be done without any mental burden, thereby improving its business logic on this basis, and the business logic does not need to include too many countdown functions

# Examples

## Basic usage

<code src="./demo/demo1.tsx"></code>
<code src="./demo/demo2.tsx"></code>
<code src="./demo/demo3.tsx"></code>

## API

```ts
const returnValue= useTimer<T extends number| Date >(
time: number | Date,
options: Options,
deps: DependencyList = [],
):ReturnValue<T>;
```

### parameter

| parameter | illustrate | type | default value |
| --------- | ------------------------ | ------- | ------------- |
| time | Total countdown time (s) | number | Date |
| options | Related options | Options | {} |
| deps | Dependency array | any[] | [] |

### return value

| 参数 | 说明 | 类型 |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| seconds | Calculate the remaining seconds | string |
| minutes | The remaining minutes | string |
| hours | Calculate the remaining hours | string |
| days | Number of days after division | string |
| remainingTime | How many milliseconds are left overall | number |
| isPaused | Is it in pause (this parameter will only be returned if the passed parameter is of type number) | boolean |
| isCounting | Is the countdown in progress (this parameter will only be returned if the passed parameter is of type number) | boolean |
| start | Start/Resume (this parameter will only be returned if the input parameter is of type number) | () => void |
| pause | Pause (this parameter will only be returned if the input parameter is of type number) | () => void |
| reset | Reset, with Begin: whether to start immediately after reset; ResetTime: The number of milliseconds reset, default is time. (This parameter will only be returned if the input parameter is of type number) | (withBegin: boolean = false, resetTime: number = time) => void |

### Options

| 参数 | 说明 | 类型 | 默认值 |
| ----------- | ---------------------------------------------- | ---------- | -------- |
| onComplete | The callback after the countdown ends | () => void | () => {} |
| auto | Do you want to start the countdown immediately | boolean | true |
| isCountDown | Is it mandatory to switch to countdown mode | boolean | false |
140 changes: 140 additions & 0 deletions packages/hooks/src/useTimer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import type { DependencyList } from 'react';
import { useState, useEffect, useRef, useMemo } from 'react';
import useUpdateEffect from '../useUpdateEffect';
import { formatTime } from './utils';

interface Options {
onComplete?: () => void;
auto?: boolean;
isCountDown?: boolean;
}
type CheckNumber<Time, Type> = Time extends number ? Type : never;

export interface ReturnValue<Time extends Date | number> {
seconds: string;
minutes: string;
hours: string;
days: string;
remainingTime: number;
start: CheckNumber<Time, () => void>;
pause: () => CheckNumber<Time, () => void>;
reset: CheckNumber<Time, (withBegin?: boolean, resetTime?: number) => void>;
isPaused?: boolean;
isCounting?: boolean;
}

function useTimer<T extends Date | number>(
time: Date | number,
options: Options = {},
deps: DependencyList = [],
): ReturnValue<T> {
const [isPaused, setIsPaused] = useState(false);
const { auto = true, onComplete = () => {} } = options;
const [isCounting, setisCounting] = useState<boolean>(false);
const isCountDown = options.isCountDown || typeof time === 'number';
const timeRef = useRef<number>(
isCountDown ? (typeof time === 'number' ? Date.now() + time : Number(time)) : Number(time),
);
const timeHandle = useRef<number>();
const [timeProperties, setTimeProperties] = useState(() => formatTime(timeRef.current, true));

const clearRef = () => {
timeHandle.current = 0;
setisCounting(false);
window.cancelAnimationFrame(timeHandle.current || 0);
};

const showTime = () => {
const formatedTime = formatTime(timeRef.current, !isCountDown);
setTimeProperties(formatedTime);
if (formatedTime.remainingTime >= 16 && timeHandle.current) {
timeHandle.current = window.requestAnimationFrame(() => showTime());
} else {
if (timeHandle.current) {
onComplete();
clearRef();
}
}
};

useEffect(() => {
if (!isCountDown || (auto && isCountDown)) {
setisCounting(true);
timeHandle.current = window.requestAnimationFrame(() => showTime());
}
return clearRef;
}, []);

useUpdateEffect(() => {
timeRef.current = isCountDown
? typeof time === 'number'
? Date.now() + time
: Number(time)
: Number(time);
setTimeProperties(() => formatTime(timeRef.current, true));
if (auto) {
setisCounting(true);
if (timeHandle.current) {
window.cancelAnimationFrame(timeHandle.current);
}
timeHandle.current = window.requestAnimationFrame(() => showTime());
}
}, [...deps, isCountDown && time]);

const timeMethods = useMemo(() => {
const start = () => {
setisCounting(true);
setIsPaused(false);
// 在开始前点击 timeRef.current > 0 并且 timeProperties.remainingTime === number * 1000
// 在暂停后点击 timeProperties.remainingTime > 16 并且 timeHandle.current === 0
if (
(timeProperties.remainingTime >= 16 && !timeHandle.current) ||
(timeRef.current && timeProperties.remainingTime === Number(time))
) {
timeRef.current = Date.now() + timeProperties.remainingTime;
timeHandle.current = window.requestAnimationFrame(() => showTime());
}
};

const pause = () => {
clearRef();
setisCounting(false);
setIsPaused(true);
};

const reset = (withBegin: boolean = false, resetTime: number = time as number) => {
clearRef();
const tempTimeProperties = formatTime(Date.now() + Number(resetTime));
setIsPaused(!withBegin);
setisCounting(withBegin);
setTimeProperties(tempTimeProperties);
if (withBegin) {
timeRef.current = Date.now() + tempTimeProperties.remainingTime;
timeHandle.current = window.requestAnimationFrame(() => showTime());
}
};

return {
start,
pause,
reset,
};
}, [timeProperties, isCounting, isPaused]);

if (isCountDown) {
// @ts-ignore
return {
...timeProperties,
...timeMethods,
isCounting,
isPaused,
isPausing: isPaused,
} as ReturnValue<number>;
}
// @ts-ignore
return {
...timeProperties,
} as ReturnValue<Date>;
}

export default useTimer;
Loading

0 comments on commit c118ddb

Please sign in to comment.