Skip to content

Commit

Permalink
feat(rstream): update fromRAF() & opts
Browse files Browse the repository at this point in the history
- update timestamp handling/opts
  • Loading branch information
postspectacular committed Feb 6, 2024
1 parent e4966fd commit 27f4cde
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/rstream/src/metastream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export interface MetaStreamOpts extends CommonOpts {
* // transform each received odd number into a stream
* // producing 3 copies of that number in the metastream
* // even numbers are ignored
* a = metastream(
* a = metaStream(
* (x) => (x & 1)
* ? fromIterable(tx.repeat(x, 3), { delay: 100 })
* : null
Expand Down
14 changes: 14 additions & 0 deletions packages/rstream/src/raf.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isNode } from "@thi.ng/checks/is-node";
import { isNumber } from "@thi.ng/checks/is-number";
import type { CommonOpts } from "./api.js";
import { __optsWithID } from "./idgen.js";
import { fromInterval } from "./interval.js";
Expand All @@ -13,6 +14,14 @@ export interface FromRAFOpts extends CommonOpts {
* @defaultValue false
*/
timestamp: boolean;
/**
* Only used if {@link FromRAFOpts.timestamp} is enabled. If given as
* number, the value will be subtracted from all emitted timestamps. If this
* option is set to true, the timestamps will be automatically zero-adjusted
* such that the first emitted value will be zero. If undefined (default),
* the browser supplied timestamps will be used as is.
*/
t0: number | boolean;
}

/**
Expand All @@ -34,7 +43,12 @@ export const fromRAF = (opts: Partial<FromRAFOpts> = {}) =>
: stream<number>((stream) => {
let i = 0;
let isActive = true;
let t0 = isNumber(opts.t0) ? opts.t0 : undefined;
const loop: FrameRequestCallback = (time) => {
if (opts.timestamp && opts.t0) {
if (t0 === undefined) t0 = time;
time -= t0;
}
isActive && stream.next(opts.timestamp ? time : i++);
isActive && (id = requestAnimationFrame(loop));
};
Expand Down

0 comments on commit 27f4cde

Please sign in to comment.