Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 37 additions & 8 deletions src/use-motion/use-motion.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
import type { Binding } from "@rbxts/react";
import { useBinding, useMemo } from "@rbxts/react";
import { useBinding, useEffect, useMemo } from "@rbxts/react";
import type { Motion, MotionGoal } from "@rbxts/ripple";
import { createMotion } from "@rbxts/ripple";
import { useEventListener } from "../use-event-listener";
import { RunService } from "@rbxts/services";

const callbacks = new Set<(dt: number) => void>();
let connection: RBXScriptConnection | undefined;

function connect(callback: (dt: number) => void) {
callbacks.add(callback);

if (!connection) {
connection = RunService.Heartbeat.Connect((dt) => {
for (const callback of callbacks) {
callback(dt);
}
});
}
}

function disconnect(callback: (dt: number) => void) {
callbacks.delete(callback);

if (callbacks.isEmpty()) {
connection?.Disconnect();
connection = undefined;
}
}

export function useMotion(initialValue: number): LuaTuple<[Binding<number>, Motion]>;
export function useMotion<T extends MotionGoal>(initialValue: T): LuaTuple<[Binding<T>, Motion<T>]>;
export function useMotion<T extends MotionGoal>(initialValue: T) {
Expand All @@ -14,13 +37,19 @@ export function useMotion<T extends MotionGoal>(initialValue: T) {

const [binding, setValue] = useBinding(initialValue);

useEventListener(RunService.Heartbeat, (delta) => {
const value = motion.step(delta);
useEffect(() => {
const callback = (delta: number) => {
const value = motion.step(delta);

if (value !== binding.getValue()) {
setValue(value);
}
};

if (value !== binding.getValue()) {
setValue(value);
}
});
connect(callback);

return () => disconnect(callback);
}, []);

return $tuple(binding, motion);
}