react-native-reanimated
Version:
More powerful alternative to Animated library for React Native.
87 lines (86 loc) • 2.58 kB
JavaScript
'use strict';
export default class FrameCallbackRegistryJS {
nextCallbackId = 0;
nextCallId = 0;
previousFrameTimestamp = null;
frameCallbackRegistry = new Map();
activeFrameCallbacks = new Set();
registerFrameCallback(callback) {
if (!callback) {
return -1;
}
const callbackId = this.nextCallbackId;
this.nextCallbackId++;
this.frameCallbackRegistry.set(callbackId, {
callback,
startTime: null
});
return callbackId;
}
unregisterFrameCallback(callbackId) {
this.manageStateFrameCallback(callbackId, false);
this.frameCallbackRegistry.delete(callbackId);
}
manageStateFrameCallback(callbackId, state) {
if (callbackId === -1) {
return;
}
if (state) {
if (!this.activeFrameCallbacks.has(callbackId)) {
this.activeFrameCallbacks.add(callbackId);
this.runCallbacks(this.nextCallId);
}
} else {
const callback = this.frameCallbackRegistry.get(callbackId);
callback.startTime = null;
this.activeFrameCallbacks.delete(callbackId);
if (this.activeFrameCallbacks.size === 0) {
this.nextCallId += 1;
}
}
}
runCallbacks(callId) {
const loop = timestamp => {
if (callId !== this.nextCallId) {
return;
}
if (this.previousFrameTimestamp === null) {
this.previousFrameTimestamp = timestamp;
}
const delta = timestamp - this.previousFrameTimestamp;
Array.from(this.activeFrameCallbacks).forEach(callbackId => {
if (!this.activeFrameCallbacks.has(callbackId)) {
return;
}
const callbackDetails = this.frameCallbackRegistry.get(callbackId);
const {
startTime
} = callbackDetails;
if (startTime === null) {
callbackDetails.startTime = timestamp;
callbackDetails.callback({
timestamp,
timeSincePreviousFrame: null,
timeSinceFirstFrame: 0
});
} else {
callbackDetails.callback({
timestamp,
timeSincePreviousFrame: delta,
timeSinceFirstFrame: timestamp - startTime
});
}
});
if (this.activeFrameCallbacks.size > 0) {
this.previousFrameTimestamp = timestamp;
requestAnimationFrame(loop);
} else {
this.previousFrameTimestamp = null;
}
};
if (this.activeFrameCallbacks.size === 1 && callId === this.nextCallId) {
requestAnimationFrame(loop);
}
}
}
//# sourceMappingURL=FrameCallbackRegistryJS.js.map