From c118ddb392bdccb42ea00bff6a37637bcb895445 Mon Sep 17 00:00:00 2001 From: Shu Yi Kang <185901261@qq.com> Date: Sun, 27 Oct 2024 17:20:27 +0800 Subject: [PATCH] feat: add useTimer --- packages/hooks/src/index.ts | 2 + .../src/useTimer/__tests__/index.test.ts | 69 +++++++++ packages/hooks/src/useTimer/demo/demo1.tsx | 35 +++++ packages/hooks/src/useTimer/demo/demo2.tsx | 12 ++ packages/hooks/src/useTimer/demo/demo3.tsx | 15 ++ packages/hooks/src/useTimer/index.en-US.md | 64 ++++++++ packages/hooks/src/useTimer/index.ts | 140 ++++++++++++++++++ packages/hooks/src/useTimer/index.zh-CN.md | 62 ++++++++ packages/hooks/src/useTimer/utils/index.ts | 34 +++++ 9 files changed, 433 insertions(+) create mode 100644 packages/hooks/src/useTimer/__tests__/index.test.ts create mode 100644 packages/hooks/src/useTimer/demo/demo1.tsx create mode 100644 packages/hooks/src/useTimer/demo/demo2.tsx create mode 100644 packages/hooks/src/useTimer/demo/demo3.tsx create mode 100644 packages/hooks/src/useTimer/index.en-US.md create mode 100644 packages/hooks/src/useTimer/index.ts create mode 100644 packages/hooks/src/useTimer/index.zh-CN.md create mode 100644 packages/hooks/src/useTimer/utils/index.ts diff --git a/packages/hooks/src/index.ts b/packages/hooks/src/index.ts index 58cefd9c79..f3e272462e 100644 --- a/packages/hooks/src/index.ts +++ b/packages/hooks/src/index.ts @@ -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, @@ -156,4 +157,5 @@ export { useRafTimeout, useResetState, useMutationObserver, + useTimer, }; diff --git a/packages/hooks/src/useTimer/__tests__/index.test.ts b/packages/hooks/src/useTimer/__tests__/index.test.ts new file mode 100644 index 0000000000..5e5d2eecb5 --- /dev/null +++ b/packages/hooks/src/useTimer/__tests__/index.test.ts @@ -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(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(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(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(); + }); +}); diff --git a/packages/hooks/src/useTimer/demo/demo1.tsx b/packages/hooks/src/useTimer/demo/demo1.tsx new file mode 100644 index 0000000000..cf2d987dd9 --- /dev/null +++ b/packages/hooks/src/useTimer/demo/demo1.tsx @@ -0,0 +1,35 @@ +import React from 'react'; +import useTimer from '..'; + +export default () => { + const { seconds, minutes, hours, days, start, pause, reset, isPaused } = useTimer( + 1000 * 3, + { + onComplete: () => { + console.info('计时完成'); + }, + auto: false, + }, + ); + + return ( + <> + {isPaused && 暂停中} +
+ {days ? {days}天 : null} + + {hours}:{minutes}:{seconds} + +
+ + + + + ); +}; diff --git a/packages/hooks/src/useTimer/demo/demo2.tsx b/packages/hooks/src/useTimer/demo/demo2.tsx new file mode 100644 index 0000000000..76035a752b --- /dev/null +++ b/packages/hooks/src/useTimer/demo/demo2.tsx @@ -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(time.current); + return ( +
+ 阿里巴巴至今已经{days}天 {hours}:{minutes}:{seconds} +
+ ); +}; diff --git a/packages/hooks/src/useTimer/demo/demo3.tsx b/packages/hooks/src/useTimer/demo/demo3.tsx new file mode 100644 index 0000000000..60a492f7e7 --- /dev/null +++ b/packages/hooks/src/useTimer/demo/demo3.tsx @@ -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(time.current, { + onComplete: () => console.log('计时结束'), + isCountDown: true, + }); + return ( +
+ 距离2028年洛杉矶奥运会还有{days}天 {hours}:{minutes}:{seconds} +
+ ); +}; diff --git a/packages/hooks/src/useTimer/index.en-US.md b/packages/hooks/src/useTimer/index.en-US.md new file mode 100644 index 0000000000..af68ec3892 --- /dev/null +++ b/packages/hooks/src/useTimer/index.en-US.md @@ -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 + + + + + +## API + +```ts +const returnValue= useTimer( + time: number | Date, + options: Options, + deps: DependencyList = [], +):ReturnValue; +``` + +### 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 | diff --git a/packages/hooks/src/useTimer/index.ts b/packages/hooks/src/useTimer/index.ts new file mode 100644 index 0000000000..4f837da566 --- /dev/null +++ b/packages/hooks/src/useTimer/index.ts @@ -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 extends number ? Type : never; + +export interface ReturnValue