Skip to content

Visualize Your Ideas With Code

feat: add `useDuration` helper (#226)

Tan to the Dashifa97d6c7f076
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 977ff5a5..b313e476 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -17,3 +17,4 @@ export * from './useScene';
export * from './useThread';
export * from './useTime';
export * from './useContext';
+export * from './useDuration';
diff --git a/packages/core/src/utils/useDuration.ts b/packages/core/src/utils/useDuration.ts
new file mode 100644
index 00000000..0372a84e
--- /dev/null
+++ b/packages/core/src/utils/useDuration.ts
@@ -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;
+}
diff --git a/packages/docs/docs/getting-started/time-events.mdx b/packages/docs/docs/getting-started/time-events.mdx
index 8c049005..f2c98d29 100644
--- a/packages/docs/docs/getting-started/time-events.mdx
+++ b/packages/docs/docs/getting-started/time-events.mdx
@@ -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'));
+```
\ No newline at end of file