1
1
import type { Binding } from "@rbxts/react" ;
2
- import { useBinding , useMemo } from "@rbxts/react" ;
2
+ import { useBinding , useEffect , useMemo } from "@rbxts/react" ;
3
3
import type { Motion , MotionGoal } from "@rbxts/ripple" ;
4
4
import { createMotion } from "@rbxts/ripple" ;
5
- import { useEventListener } from "../use-event-listener" ;
6
5
import { RunService } from "@rbxts/services" ;
7
6
7
+ const callbacks = new Set < ( dt : number ) => void > ( ) ;
8
+ let connection : RBXScriptConnection | undefined ;
9
+
10
+ function connect ( callback : ( dt : number ) => void ) {
11
+ callbacks . add ( callback ) ;
12
+
13
+ if ( ! connection ) {
14
+ connection = RunService . Heartbeat . Connect ( ( dt ) => {
15
+ for ( const callback of callbacks ) {
16
+ callback ( dt ) ;
17
+ }
18
+ } ) ;
19
+ }
20
+ }
21
+
22
+ function disconnect ( callback : ( dt : number ) => void ) {
23
+ callbacks . delete ( callback ) ;
24
+
25
+ if ( callbacks . isEmpty ( ) ) {
26
+ connection ?. Disconnect ( ) ;
27
+ connection = undefined ;
28
+ }
29
+ }
30
+
8
31
export function useMotion ( initialValue : number ) : LuaTuple < [ Binding < number > , Motion ] > ;
9
32
export function useMotion < T extends MotionGoal > ( initialValue : T ) : LuaTuple < [ Binding < T > , Motion < T > ] > ;
10
33
export function useMotion < T extends MotionGoal > ( initialValue : T ) {
@@ -14,13 +37,19 @@ export function useMotion<T extends MotionGoal>(initialValue: T) {
14
37
15
38
const [ binding , setValue ] = useBinding ( initialValue ) ;
16
39
17
- useEventListener ( RunService . Heartbeat , ( delta ) => {
18
- const value = motion . step ( delta ) ;
40
+ useEffect ( ( ) => {
41
+ const callback = ( delta : number ) => {
42
+ const value = motion . step ( delta ) ;
43
+
44
+ if ( value !== binding . getValue ( ) ) {
45
+ setValue ( value ) ;
46
+ }
47
+ } ;
19
48
20
- if ( value !== binding . getValue ( ) ) {
21
- setValue ( value ) ;
22
- }
23
- } ) ;
49
+ connect ( callback ) ;
50
+
51
+ return ( ) => disconnect ( callback ) ;
52
+ } , [ ] ) ;
24
53
25
54
return $tuple ( binding , motion ) ;
26
55
}
0 commit comments