feat: add useDuration helper (#226)

Added a `useDuration` helper function to easily
create a `TimeEvent` and use it to control an
animation.

Added a sub-section for the new `useDuration`
function in the `Time Events` chapter.

Closes: #171
This commit is contained in:
Tan to the Dashi
2023-02-07 12:33:10 +01:00
committed by GitHub
parent 11ee3fef5a
commit fa97d6c7f0
3 changed files with 43 additions and 0 deletions

View File

@@ -17,3 +17,4 @@ export * from './useScene';
export * from './useThread';
export * from './useTime';
export * from './useContext';
export * from './useDuration';

View File

@@ -0,0 +1,31 @@
import {useScene} from './useScene';
/**
* Register a time event and get its duration in seconds.
*
* @remarks
* This can be used to better specify when an animation should start
* as well as how long this animation should take
*
* @example
* ```ts
* export default makeScene2D(function* (view) {
* const circle = createRef<Circle>();
*
* view.add(
* <Circle ref={circle} width={320} height={320} fill={'lightseagreen'} />,
* );
*
* yield* circle().scale(2, useDuration('circleGrow'));
* });
* ```
*
* @param name - The name of the event.
*
* @returns The duration of the event in seconds.
*/
export function useDuration(name: string): number {
const scene = useScene();
scene.timeEvents.register(name);
return scene.timeEvents.get(name).offset;
}

View File

@@ -48,3 +48,14 @@ it. This is useful when you want to extend or shorten a pause in your voiceover
because correcting the first time event after the pause will also fix all events
after it. You can hold `SHIFT` when editing an event to prevent this from
happening.
## Controlling animation duration
Aside from specifying _when_ something should happen, Time Events can also be used to
control _how long_ something should last. You can use the
[`useDuration`](/api/core/utils#useDuration) function to retrieve the duration of an event
and use it in your animation:
```ts
yield* circle().scale(2, useDuration('event'));
```