Skip to content

Commit a1af92e

Browse files
committed
refactor(core/web): Improve rect caching and frame throttle
1 parent 093107b commit a1af92e

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-scan",
3-
"version": "0.0.10",
3+
"version": "0.0.11",
44
"description": "Scan your React app for renders",
55
"keywords": [
66
"react",

src/core/web/outline.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { getNearestHostFiber } from '../instrumentation/fiber';
33
import type { Render } from '../instrumentation/index';
44
import { ReactScanInternals } from '../index';
55
import { getLabelText } from '../utils';
6-
import { isOutlineUnstable, throttle } from './utils';
6+
import { isOutlineUnstable, onIdle, throttle } from './utils';
77
import { log } from './log';
88
import { recalcOutlineColor } from './perf-observer';
99
// import { recalcOutlineColor } from './perf-observer';
@@ -32,14 +32,21 @@ export interface PaintedOutline {
3232

3333
export const MONO_FONT =
3434
'Menlo,Consolas,Monaco,Liberation Mono,Lucida Console,monospace';
35-
const DEFAULT_THROTTLE_TIME = 8; // 2 frames
35+
const DEFAULT_THROTTLE_TIME = 16; // 1 frame
3636
export const colorRef = { current: '115,97,230' };
3737

3838
export const getOutlineKey = (outline: PendingOutline): string => {
3939
return `${outline.rect.top}-${outline.rect.left}-${outline.rect.width}-${outline.rect.height}`;
4040
};
4141

42+
const rectCache = new Map<HTMLElement, { rect: DOMRect; timestamp: number }>();
43+
4244
export const getRect = (domNode: HTMLElement): DOMRect | null => {
45+
const cached = rectCache.get(domNode);
46+
if (cached && cached.timestamp > performance.now() - DEFAULT_THROTTLE_TIME) {
47+
return cached.rect;
48+
}
49+
4350
const style = window.getComputedStyle(domNode);
4451
if (
4552
style.display === 'none' ||
@@ -61,6 +68,8 @@ export const getRect = (domNode: HTMLElement): DOMRect | null => {
6168
return null;
6269
}
6370

71+
rectCache.set(domNode, { rect, timestamp: performance.now() });
72+
6473
return rect;
6574
};
6675

@@ -285,10 +294,13 @@ export const fadeOutOutline = (ctx: CanvasRenderingContext2D) => {
285294
const activeOutline = activeOutlines[i];
286295
if (!activeOutline) continue;
287296
const { outline, frame, totalFrames } = activeOutline;
288-
// const newRect = getRect(outline.domNode);
289-
// if (newRect) {
290-
// outline.rect = newRect;
291-
// }
297+
requestAnimationFrame(() => {
298+
if (!outline) return;
299+
const newRect = getRect(outline.domNode);
300+
if (newRect) {
301+
outline.rect = newRect;
302+
}
303+
});
292304
const { rect } = outline;
293305
const unstable = isOutlineUnstable(outline);
294306

0 commit comments

Comments
 (0)