From b71cf00194e3ae8a8ac4a1173c907dbbb0b3e639 Mon Sep 17 00:00:00 2001 From: Alex Lohr Date: Wed, 26 Jun 2024 22:20:19 +0200 Subject: [PATCH] raf: add createMs primitive --- .changeset/dry-tips-kneel.md | 5 +++++ packages/raf/README.md | 24 ++++++++++++++++++++++++ packages/raf/package.json | 1 + packages/raf/src/index.ts | 22 +++++++++++++++++++++- 4 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 .changeset/dry-tips-kneel.md diff --git a/.changeset/dry-tips-kneel.md b/.changeset/dry-tips-kneel.md new file mode 100644 index 000000000..1d4ca3935 --- /dev/null +++ b/.changeset/dry-tips-kneel.md @@ -0,0 +1,5 @@ +--- +"@solid-primitives/raf": minor +--- + +add createMs primitive diff --git a/packages/raf/README.md b/packages/raf/README.md index b484ca07d..c2ad057ee 100644 --- a/packages/raf/README.md +++ b/packages/raf/README.md @@ -84,6 +84,30 @@ function targetFPS( ): FrameRequestCallback; ``` +## createMs + +Using createRAF and targetFPS to create a reactive milliseconds counter with configurable frame rate. + +It takes the framerate as single argument, either as `number` or `Accessor`. + +```ts +import { createMs } from "@solid-primitives/raf"; + +const ms = createMs(60); + +const MovingRect() { + return ; +} +``` + +#### Defintion + +```ts +function createMs( + fps: MaybeAccessor, +): Accessor; +``` + ## Demo You may view a working example here: https://codesandbox.io/s/solid-primitives-raf-demo-4xvmjd?file=/src/index.tsx diff --git a/packages/raf/package.json b/packages/raf/package.json index 668f9076c..33d0305fb 100644 --- a/packages/raf/package.json +++ b/packages/raf/package.json @@ -18,6 +18,7 @@ "stage": 3, "list": [ "createRAF", + "createMs", "targetFPS" ], "category": "Animation" diff --git a/packages/raf/src/index.ts b/packages/raf/src/index.ts index 0bb830f17..752a7e963 100644 --- a/packages/raf/src/index.ts +++ b/packages/raf/src/index.ts @@ -87,4 +87,24 @@ function targetFPS( }; } -export { createRAF, createRAF as default, targetFPS }; +/** + * A primitive that creates a reactive milliseconds signal with a given frame rate to base your animations on. + * + * ```ts + * const ms = createMs(60); + * return + * ``` + */ +function createMs(fps: MaybeAccessor) { + const [ms, setMs] = createSignal(0); + let initialTs = 0; + const [_, start, stop] = createRAF(targetFPS((ts) => { + initialTs ||= ts; + setMs(ts - initialTs); + }, fps)); + start(); + onCleanup(stop); + return ms; +} + +export { createMs, createRAF, createRAF as default, targetFPS };