mirror of
https://github.com/excalidraw/excalidraw.git
synced 2025-05-03 10:00:07 -04:00
feat: throttle pointermove
events per framerate (#4727)
This commit is contained in:
parent
96de887cc8
commit
8aff076782
3 changed files with 75 additions and 6 deletions
62
src/utils.ts
62
src/utils.ts
|
@ -119,6 +119,53 @@ export const debounce = <T extends any[]>(
|
|||
return ret;
|
||||
};
|
||||
|
||||
// throttle callback to execute once per animation frame
|
||||
export const throttleRAF = <T extends any[]>(fn: (...args: T) => void) => {
|
||||
let handle: number | null = null;
|
||||
let lastArgs: T | null = null;
|
||||
let callback: ((...args: T) => void) | null = null;
|
||||
const ret = (...args: T) => {
|
||||
if (process.env.NODE_ENV === "test") {
|
||||
fn(...args);
|
||||
return;
|
||||
}
|
||||
lastArgs = args;
|
||||
callback = fn;
|
||||
if (handle === null) {
|
||||
handle = window.requestAnimationFrame(() => {
|
||||
handle = null;
|
||||
lastArgs = null;
|
||||
callback = null;
|
||||
fn(...args);
|
||||
});
|
||||
}
|
||||
};
|
||||
ret.flush = () => {
|
||||
if (handle !== null) {
|
||||
cancelAnimationFrame(handle);
|
||||
handle = null;
|
||||
}
|
||||
if (lastArgs) {
|
||||
const _lastArgs = lastArgs;
|
||||
const _callback = callback;
|
||||
lastArgs = null;
|
||||
callback = null;
|
||||
if (_callback !== null) {
|
||||
_callback(..._lastArgs);
|
||||
}
|
||||
}
|
||||
};
|
||||
ret.cancel = () => {
|
||||
lastArgs = null;
|
||||
callback = null;
|
||||
if (handle !== null) {
|
||||
cancelAnimationFrame(handle);
|
||||
handle = null;
|
||||
}
|
||||
};
|
||||
return ret;
|
||||
};
|
||||
|
||||
// https://github.com/lodash/lodash/blob/es/chunk.js
|
||||
export const chunk = <T extends any>(
|
||||
array: readonly T[],
|
||||
|
@ -356,6 +403,21 @@ export const withBatchedUpdates = <
|
|||
unstable_batchedUpdates(func as TFunction, event);
|
||||
}) as TFunction;
|
||||
|
||||
/**
|
||||
* barches React state updates and throttles the calls to a single call per
|
||||
* animation frame
|
||||
*/
|
||||
export const withBatchedUpdatesThrottled = <
|
||||
TFunction extends ((event: any) => void) | (() => void),
|
||||
>(
|
||||
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
|
||||
) => {
|
||||
// @ts-ignore
|
||||
return throttleRAF<Parameters<TFunction>>(((event) => {
|
||||
unstable_batchedUpdates(func, event);
|
||||
}) as TFunction);
|
||||
};
|
||||
|
||||
//https://stackoverflow.com/a/9462382/8418
|
||||
export const nFormatter = (num: number, digits: number): string => {
|
||||
const si = [
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue