Skip to content

Commit

Permalink
raf: add createMs primitive
Browse files Browse the repository at this point in the history
  • Loading branch information
atk committed Jun 30, 2024
1 parent 6cd7857 commit b71cf00
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/dry-tips-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solid-primitives/raf": minor
---

add createMs primitive
24 changes: 24 additions & 0 deletions packages/raf/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>`.

```ts
import { createMs } from "@solid-primitives/raf";

const ms = createMs(60);

const MovingRect() {
return <rect x="0" y="0" width={1000 / 3000 * Math.min(ms(), 3000)} height="10" />;
}
```

#### Defintion

```ts
function createMs(
fps: MaybeAccessor<number>,
): Accessor<number>;
```

## Demo

You may view a working example here: https://codesandbox.io/s/solid-primitives-raf-demo-4xvmjd?file=/src/index.tsx
Expand Down
1 change: 1 addition & 0 deletions packages/raf/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"stage": 3,
"list": [
"createRAF",
"createMs",
"targetFPS"
],
"category": "Animation"
Expand Down
22 changes: 21 additions & 1 deletion packages/raf/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <rect x="0" y="0" height="10" width={Math.min(100, ms() / 5000)} />
* ```
*/
function createMs(fps: MaybeAccessor<number>) {
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 };

0 comments on commit b71cf00

Please sign in to comment.